blob: bb291bb45356c7d003ab3b522a85b02f515d2241 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000028#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000030#include <algorithm>
31
32namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000033using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034
John McCall5c32be02010-08-24 20:38:10 +000035static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
36 bool InOverloadResolution,
37 StandardConversionSequence &SCS);
38static OverloadingResult
39IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
40 UserDefinedConversionSequence& User,
41 OverloadCandidateSet& Conversions,
42 bool AllowExplicit);
43
44
45static ImplicitConversionSequence::CompareKind
46CompareStandardConversionSequences(Sema &S,
47 const StandardConversionSequence& SCS1,
48 const StandardConversionSequence& SCS2);
49
50static ImplicitConversionSequence::CompareKind
51CompareQualificationConversions(Sema &S,
52 const StandardConversionSequence& SCS1,
53 const StandardConversionSequence& SCS2);
54
55static ImplicitConversionSequence::CompareKind
56CompareDerivedToBaseConversions(Sema &S,
57 const StandardConversionSequence& SCS1,
58 const StandardConversionSequence& SCS2);
59
60
61
Douglas Gregor5251f1b2008-10-21 16:13:35 +000062/// GetConversionCategory - Retrieve the implicit conversion
63/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000064ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000065GetConversionCategory(ImplicitConversionKind Kind) {
66 static const ImplicitConversionCategory
67 Category[(int)ICK_Num_Conversion_Kinds] = {
68 ICC_Identity,
69 ICC_Lvalue_Transformation,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000072 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 ICC_Qualification_Adjustment,
74 ICC_Promotion,
75 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000076 ICC_Promotion,
77 ICC_Conversion,
78 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000079 ICC_Conversion,
80 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000084 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000085 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000086 ICC_Conversion,
87 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000088 ICC_Conversion
89 };
90 return Category[(int)Kind];
91}
92
93/// GetConversionRank - Retrieve the implicit conversion rank
94/// corresponding to the given implicit conversion kind.
95ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
96 static const ImplicitConversionRank
97 Rank[(int)ICK_Num_Conversion_Kinds] = {
98 ICR_Exact_Match,
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000103 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 ICR_Promotion,
105 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000106 ICR_Promotion,
107 ICR_Conversion,
108 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 ICR_Conversion,
110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000114 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000115 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000116 ICR_Conversion,
117 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000118 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000119 };
120 return Rank[(int)Kind];
121}
122
123/// GetImplicitConversionName - Return the name of this kind of
124/// implicit conversion.
125const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000126 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000127 "No conversion",
128 "Lvalue-to-rvalue",
129 "Array-to-pointer",
130 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000131 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 "Qualification",
133 "Integral promotion",
134 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000135 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000136 "Integral conversion",
137 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000138 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 "Floating-integral conversion",
140 "Pointer conversion",
141 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000144 "Derived-to-base conversion",
145 "Vector conversion",
146 "Vector splat",
147 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 };
149 return Name[Kind];
150}
151
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000152/// StandardConversionSequence - Set the standard conversion
153/// sequence to the identity conversion.
154void StandardConversionSequence::setAsIdentityConversion() {
155 First = ICK_Identity;
156 Second = ICK_Identity;
157 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000158 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000159 ReferenceBinding = false;
160 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000161 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000162 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000163}
164
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000165/// getRank - Retrieve the rank of this standard conversion sequence
166/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
167/// implicit conversions.
168ImplicitConversionRank StandardConversionSequence::getRank() const {
169 ImplicitConversionRank Rank = ICR_Exact_Match;
170 if (GetConversionRank(First) > Rank)
171 Rank = GetConversionRank(First);
172 if (GetConversionRank(Second) > Rank)
173 Rank = GetConversionRank(Second);
174 if (GetConversionRank(Third) > Rank)
175 Rank = GetConversionRank(Third);
176 return Rank;
177}
178
179/// isPointerConversionToBool - Determines whether this conversion is
180/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000181/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000183bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 // Note that FromType has not necessarily been transformed by the
185 // array-to-pointer or function-to-pointer implicit conversions, so
186 // check for their presence as well as checking whether FromType is
187 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000188 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000189 (getFromType()->isPointerType() ||
190 getFromType()->isObjCObjectPointerType() ||
191 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000192 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
193 return true;
194
195 return false;
196}
197
Douglas Gregor5c407d92008-10-23 00:40:37 +0000198/// isPointerConversionToVoidPointer - Determines whether this
199/// conversion is a conversion of a pointer to a void pointer. This is
200/// used as part of the ranking of standard conversion sequences (C++
201/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000202bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000203StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000204isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000205 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000206 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000207
208 // Note that FromType has not necessarily been transformed by the
209 // array-to-pointer implicit conversion, so check for its presence
210 // and redo the conversion to get a pointer.
211 if (First == ICK_Array_To_Pointer)
212 FromType = Context.getArrayDecayedType(FromType);
213
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000214 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000215 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000216 return ToPtrType->getPointeeType()->isVoidType();
217
218 return false;
219}
220
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// DebugPrint - Print this standard conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 bool PrintedSomething = false;
226 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 PrintedSomething = true;
229 }
230
231 if (Second != ICK_Identity) {
232 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000233 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000236
237 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000238 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000239 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000240 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000241 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000243 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000244 PrintedSomething = true;
245 }
246
247 if (Third != ICK_Identity) {
248 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000249 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000251 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000252 PrintedSomething = true;
253 }
254
255 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 }
258}
259
260/// DebugPrint - Print this user-defined conversion sequence to standard
261/// error. Useful for debugging overloading issues.
262void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000263 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000264 if (Before.First || Before.Second || Before.Third) {
265 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000268 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000270 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 After.DebugPrint();
272 }
273}
274
275/// DebugPrint - Print this implicit conversion sequence to standard
276/// error. Useful for debugging overloading issues.
277void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 switch (ConversionKind) {
280 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000281 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000282 Standard.DebugPrint();
283 break;
284 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000285 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 UserDefined.DebugPrint();
287 break;
288 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000289 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000290 break;
John McCall0d1da222010-01-12 00:44:57 +0000291 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000292 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000293 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000295 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 break;
297 }
298
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000299 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000300}
301
John McCall0d1da222010-01-12 00:44:57 +0000302void AmbiguousConversionSequence::construct() {
303 new (&conversions()) ConversionSet();
304}
305
306void AmbiguousConversionSequence::destruct() {
307 conversions().~ConversionSet();
308}
309
310void
311AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
312 FromTypePtr = O.FromTypePtr;
313 ToTypePtr = O.ToTypePtr;
314 new (&conversions()) ConversionSet(O.conversions());
315}
316
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000317namespace {
318 // Structure used by OverloadCandidate::DeductionFailureInfo to store
319 // template parameter and template argument information.
320 struct DFIParamWithArguments {
321 TemplateParameter Param;
322 TemplateArgument FirstArg;
323 TemplateArgument SecondArg;
324 };
325}
326
327/// \brief Convert from Sema's representation of template deduction information
328/// to the form used in overload-candidate information.
329OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000330static MakeDeductionFailureInfo(ASTContext &Context,
331 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000332 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000333 OverloadCandidate::DeductionFailureInfo Result;
334 Result.Result = static_cast<unsigned>(TDK);
335 Result.Data = 0;
336 switch (TDK) {
337 case Sema::TDK_Success:
338 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000339 case Sema::TDK_TooManyArguments:
340 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000341 break;
342
343 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000344 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000345 Result.Data = Info.Param.getOpaqueValue();
346 break;
347
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000349 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000350 // FIXME: Should allocate from normal heap so that we can free this later.
351 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000352 Saved->Param = Info.Param;
353 Saved->FirstArg = Info.FirstArg;
354 Saved->SecondArg = Info.SecondArg;
355 Result.Data = Saved;
356 break;
357 }
358
359 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000360 Result.Data = Info.take();
361 break;
362
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000363 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364 case Sema::TDK_FailedOverloadResolution:
365 break;
366 }
367
368 return Result;
369}
John McCall0d1da222010-01-12 00:44:57 +0000370
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000371void OverloadCandidate::DeductionFailureInfo::Destroy() {
372 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
373 case Sema::TDK_Success:
374 case Sema::TDK_InstantiationDepth:
375 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000376 case Sema::TDK_TooManyArguments:
377 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000378 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000379 break;
380
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000382 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000383 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 Data = 0;
385 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000386
387 case Sema::TDK_SubstitutionFailure:
388 // FIXME: Destroy the template arugment list?
389 Data = 0;
390 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000391
Douglas Gregor461761d2010-05-08 18:20:53 +0000392 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_FailedOverloadResolution:
395 break;
396 }
397}
398
399TemplateParameter
400OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000404 case Sema::TDK_TooManyArguments:
405 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000406 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000407 return TemplateParameter();
408
409 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000410 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 return TemplateParameter::getFromOpaqueValue(Data);
412
413 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000414 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000415 return static_cast<DFIParamWithArguments*>(Data)->Param;
416
417 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000418 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 case Sema::TDK_FailedOverloadResolution:
420 break;
421 }
422
423 return TemplateParameter();
424}
Douglas Gregord09efd42010-05-08 20:07:26 +0000425
426TemplateArgumentList *
427OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
428 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
429 case Sema::TDK_Success:
430 case Sema::TDK_InstantiationDepth:
431 case Sema::TDK_TooManyArguments:
432 case Sema::TDK_TooFewArguments:
433 case Sema::TDK_Incomplete:
434 case Sema::TDK_InvalidExplicitArguments:
435 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000436 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000437 return 0;
438
439 case Sema::TDK_SubstitutionFailure:
440 return static_cast<TemplateArgumentList*>(Data);
441
442 // Unhandled
443 case Sema::TDK_NonDeducedMismatch:
444 case Sema::TDK_FailedOverloadResolution:
445 break;
446 }
447
448 return 0;
449}
450
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000451const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
452 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
453 case Sema::TDK_Success:
454 case Sema::TDK_InstantiationDepth:
455 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000456 case Sema::TDK_TooManyArguments:
457 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000458 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000459 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 return 0;
461
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000463 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000464 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
465
Douglas Gregor461761d2010-05-08 18:20:53 +0000466 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000467 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468 case Sema::TDK_FailedOverloadResolution:
469 break;
470 }
471
472 return 0;
473}
474
475const TemplateArgument *
476OverloadCandidate::DeductionFailureInfo::getSecondArg() {
477 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
478 case Sema::TDK_Success:
479 case Sema::TDK_InstantiationDepth:
480 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000481 case Sema::TDK_TooManyArguments:
482 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000483 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000484 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000485 return 0;
486
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000487 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000488 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
490
Douglas Gregor461761d2010-05-08 18:20:53 +0000491 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000492 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000493 case Sema::TDK_FailedOverloadResolution:
494 break;
495 }
496
497 return 0;
498}
499
500void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000501 inherited::clear();
502 Functions.clear();
503}
504
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000506// overload of the declarations in Old. This routine returns false if
507// New and Old cannot be overloaded, e.g., if New has the same
508// signature as some function in Old (C++ 1.3.10) or if the Old
509// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000510// it does return false, MatchedDecl will point to the decl that New
511// cannot be overloaded with. This decl may be a UsingShadowDecl on
512// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513//
514// Example: Given the following input:
515//
516// void f(int, float); // #1
517// void f(int, int); // #2
518// int f(int, int); // #3
519//
520// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000521// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000522//
John McCall3d988d92009-12-02 08:47:38 +0000523// When we process #2, Old contains only the FunctionDecl for #1. By
524// comparing the parameter types, we see that #1 and #2 are overloaded
525// (since they have different signatures), so this routine returns
526// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527//
John McCall3d988d92009-12-02 08:47:38 +0000528// When we process #3, Old is an overload set containing #1 and #2. We
529// compare the signatures of #3 to #1 (they're overloaded, so we do
530// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
531// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532// signature), IsOverload returns false and MatchedDecl will be set to
533// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000534//
535// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
536// into a class by a using declaration. The rules for whether to hide
537// shadow declarations ignore some properties which otherwise figure
538// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000539Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000540Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
541 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000542 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000543 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000544 NamedDecl *OldD = *I;
545
546 bool OldIsUsingDecl = false;
547 if (isa<UsingShadowDecl>(OldD)) {
548 OldIsUsingDecl = true;
549
550 // We can always introduce two using declarations into the same
551 // context, even if they have identical signatures.
552 if (NewIsUsingDecl) continue;
553
554 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
555 }
556
557 // If either declaration was introduced by a using declaration,
558 // we'll need to use slightly different rules for matching.
559 // Essentially, these rules are the normal rules, except that
560 // function templates hide function templates with different
561 // return types or template parameter lists.
562 bool UseMemberUsingDeclRules =
563 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
564
John McCall3d988d92009-12-02 08:47:38 +0000565 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000566 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
567 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
568 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
569 continue;
570 }
571
John McCalldaa3d6b2009-12-09 03:35:25 +0000572 Match = *I;
573 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000574 }
John McCall3d988d92009-12-02 08:47:38 +0000575 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000576 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
577 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
578 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
579 continue;
580 }
581
John McCalldaa3d6b2009-12-09 03:35:25 +0000582 Match = *I;
583 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000584 }
John McCall84d87672009-12-10 09:41:52 +0000585 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
586 // We can overload with these, which can show up when doing
587 // redeclaration checks for UsingDecls.
588 assert(Old.getLookupKind() == LookupUsingDeclName);
589 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
590 // Optimistically assume that an unresolved using decl will
591 // overload; if it doesn't, we'll have to diagnose during
592 // template instantiation.
593 } else {
John McCall1f82f242009-11-18 22:49:29 +0000594 // (C++ 13p1):
595 // Only function declarations can be overloaded; object and type
596 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000597 Match = *I;
598 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000599 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000600 }
John McCall1f82f242009-11-18 22:49:29 +0000601
John McCalldaa3d6b2009-12-09 03:35:25 +0000602 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000603}
604
John McCalle9cccd82010-06-16 08:42:20 +0000605bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
606 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000607 // If both of the functions are extern "C", then they are not
608 // overloads.
609 if (Old->isExternC() && New->isExternC())
610 return false;
611
John McCall1f82f242009-11-18 22:49:29 +0000612 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
613 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
614
615 // C++ [temp.fct]p2:
616 // A function template can be overloaded with other function templates
617 // and with normal (non-template) functions.
618 if ((OldTemplate == 0) != (NewTemplate == 0))
619 return true;
620
621 // Is the function New an overload of the function Old?
622 QualType OldQType = Context.getCanonicalType(Old->getType());
623 QualType NewQType = Context.getCanonicalType(New->getType());
624
625 // Compare the signatures (C++ 1.3.10) of the two functions to
626 // determine whether they are overloads. If we find any mismatch
627 // in the signature, they are overloads.
628
629 // If either of these functions is a K&R-style function (no
630 // prototype), then we consider them to have matching signatures.
631 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
632 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
633 return false;
634
635 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
636 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
637
638 // The signature of a function includes the types of its
639 // parameters (C++ 1.3.10), which includes the presence or absence
640 // of the ellipsis; see C++ DR 357).
641 if (OldQType != NewQType &&
642 (OldType->getNumArgs() != NewType->getNumArgs() ||
643 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000644 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000645 return true;
646
647 // C++ [temp.over.link]p4:
648 // The signature of a function template consists of its function
649 // signature, its return type and its template parameter list. The names
650 // of the template parameters are significant only for establishing the
651 // relationship between the template parameters and the rest of the
652 // signature.
653 //
654 // We check the return type and template parameter lists for function
655 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000656 //
657 // However, we don't consider either of these when deciding whether
658 // a member introduced by a shadow declaration is hidden.
659 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000660 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
661 OldTemplate->getTemplateParameters(),
662 false, TPL_TemplateMatch) ||
663 OldType->getResultType() != NewType->getResultType()))
664 return true;
665
666 // If the function is a class member, its signature includes the
667 // cv-qualifiers (if any) on the function itself.
668 //
669 // As part of this, also check whether one of the member functions
670 // is static, in which case they are not overloads (C++
671 // 13.1p2). While not part of the definition of the signature,
672 // this check is important to determine whether these functions
673 // can be overloaded.
674 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
675 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
676 if (OldMethod && NewMethod &&
677 !OldMethod->isStatic() && !NewMethod->isStatic() &&
678 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
679 return true;
680
681 // The signatures match; this is not an overload.
682 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000683}
684
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000685/// TryImplicitConversion - Attempt to perform an implicit conversion
686/// from the given expression (Expr) to the given type (ToType). This
687/// function returns an implicit conversion sequence that can be used
688/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000689///
690/// void f(float f);
691/// void g(int i) { f(i); }
692///
693/// this routine would produce an implicit conversion sequence to
694/// describe the initialization of f from i, which will be a standard
695/// conversion sequence containing an lvalue-to-rvalue conversion (C++
696/// 4.1) followed by a floating-integral conversion (C++ 4.9).
697//
698/// Note that this routine only determines how the conversion can be
699/// performed; it does not actually perform the conversion. As such,
700/// it will not produce any diagnostics if no conversion is available,
701/// but will instead return an implicit conversion sequence of kind
702/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000703///
704/// If @p SuppressUserConversions, then user-defined conversions are
705/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000706/// If @p AllowExplicit, then explicit user-defined conversions are
707/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000708static ImplicitConversionSequence
709TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
710 bool SuppressUserConversions,
711 bool AllowExplicit,
712 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000713 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000714 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
715 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000716 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000717 return ICS;
718 }
719
John McCall5c32be02010-08-24 20:38:10 +0000720 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000721 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000722 return ICS;
723 }
724
Douglas Gregor836a7e82010-08-11 02:15:33 +0000725 // C++ [over.ics.user]p4:
726 // A conversion of an expression of class type to the same class
727 // type is given Exact Match rank, and a conversion of an
728 // expression of class type to a base class of that type is
729 // given Conversion rank, in spite of the fact that a copy/move
730 // constructor (i.e., a user-defined conversion function) is
731 // called for those cases.
732 QualType FromType = From->getType();
733 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000734 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
735 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000736 ICS.setStandard();
737 ICS.Standard.setAsIdentityConversion();
738 ICS.Standard.setFromType(FromType);
739 ICS.Standard.setAllToTypes(ToType);
740
741 // We don't actually check at this point whether there is a valid
742 // copy/move constructor, since overloading just assumes that it
743 // exists. When we actually perform initialization, we'll find the
744 // appropriate constructor to copy the returned object, if needed.
745 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000746
Douglas Gregor5ab11652010-04-17 22:01:05 +0000747 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000748 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000749 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000750
751 return ICS;
752 }
753
754 if (SuppressUserConversions) {
755 // We're not in the case above, so there is no conversion that
756 // we can perform.
757 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000758 return ICS;
759 }
760
761 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000762 OverloadCandidateSet Conversions(From->getExprLoc());
763 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000764 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000765 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000766
767 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000768 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000769 // C++ [over.ics.user]p4:
770 // A conversion of an expression of class type to the same class
771 // type is given Exact Match rank, and a conversion of an
772 // expression of class type to a base class of that type is
773 // given Conversion rank, in spite of the fact that a copy
774 // constructor (i.e., a user-defined conversion function) is
775 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000776 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000777 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000778 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000779 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
780 QualType ToCanon
781 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000782 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000783 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000784 // Turn this into a "standard" conversion sequence, so that it
785 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000786 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000787 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000788 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000789 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000790 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000791 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000792 ICS.Standard.Second = ICK_Derived_To_Base;
793 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000794 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000795
796 // C++ [over.best.ics]p4:
797 // However, when considering the argument of a user-defined
798 // conversion function that is a candidate by 13.3.1.3 when
799 // invoked for the copying of the temporary in the second step
800 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
801 // 13.3.1.6 in all cases, only standard conversion sequences and
802 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000803 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000804 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000805 }
John McCalle8c8cd22010-01-13 22:30:33 +0000806 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000807 ICS.setAmbiguous();
808 ICS.Ambiguous.setFromType(From->getType());
809 ICS.Ambiguous.setToType(ToType);
810 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
811 Cand != Conversions.end(); ++Cand)
812 if (Cand->Viable)
813 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000814 } else {
John McCall65eb8792010-02-25 01:37:24 +0000815 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000816 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000817
818 return ICS;
819}
820
John McCall5c32be02010-08-24 20:38:10 +0000821bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
822 const InitializedEntity &Entity,
823 Expr *Initializer,
824 bool SuppressUserConversions,
825 bool AllowExplicitConversions,
826 bool InOverloadResolution) {
827 ImplicitConversionSequence ICS
828 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
829 SuppressUserConversions,
830 AllowExplicitConversions,
831 InOverloadResolution);
832 if (ICS.isBad()) return true;
833
834 // Perform the actual conversion.
835 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
836 return false;
837}
838
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000839/// PerformImplicitConversion - Perform an implicit conversion of the
840/// expression From to the type ToType. Returns true if there was an
841/// error, false otherwise. The expression From is replaced with the
842/// converted expression. Flavor is the kind of conversion we're
843/// performing, used in the error message. If @p AllowExplicit,
844/// explicit user-defined conversions are permitted.
845bool
846Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
847 AssignmentAction Action, bool AllowExplicit) {
848 ImplicitConversionSequence ICS;
849 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
850}
851
852bool
853Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
854 AssignmentAction Action, bool AllowExplicit,
855 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000856 ICS = clang::TryImplicitConversion(*this, From, ToType,
857 /*SuppressUserConversions=*/false,
858 AllowExplicit,
859 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000860 return PerformImplicitConversion(From, ToType, ICS, Action);
861}
862
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000863/// \brief Determine whether the conversion from FromType to ToType is a valid
864/// conversion that strips "noreturn" off the nested function type.
865static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
866 QualType ToType, QualType &ResultTy) {
867 if (Context.hasSameUnqualifiedType(FromType, ToType))
868 return false;
869
870 // Strip the noreturn off the type we're converting from; noreturn can
871 // safely be removed.
872 FromType = Context.getNoReturnType(FromType, false);
873 if (!Context.hasSameUnqualifiedType(FromType, ToType))
874 return false;
875
876 ResultTy = FromType;
877 return true;
878}
Douglas Gregor46188682010-05-18 22:42:18 +0000879
880/// \brief Determine whether the conversion from FromType to ToType is a valid
881/// vector conversion.
882///
883/// \param ICK Will be set to the vector conversion kind, if this is a vector
884/// conversion.
885static bool IsVectorConversion(ASTContext &Context, QualType FromType,
886 QualType ToType, ImplicitConversionKind &ICK) {
887 // We need at least one of these types to be a vector type to have a vector
888 // conversion.
889 if (!ToType->isVectorType() && !FromType->isVectorType())
890 return false;
891
892 // Identical types require no conversions.
893 if (Context.hasSameUnqualifiedType(FromType, ToType))
894 return false;
895
896 // There are no conversions between extended vector types, only identity.
897 if (ToType->isExtVectorType()) {
898 // There are no conversions between extended vector types other than the
899 // identity conversion.
900 if (FromType->isExtVectorType())
901 return false;
902
903 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000904 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000905 ICK = ICK_Vector_Splat;
906 return true;
907 }
908 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000909
910 // We can perform the conversion between vector types in the following cases:
911 // 1)vector types are equivalent AltiVec and GCC vector types
912 // 2)lax vector conversions are permitted and the vector types are of the
913 // same size
914 if (ToType->isVectorType() && FromType->isVectorType()) {
915 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000916 (Context.getLangOptions().LaxVectorConversions &&
917 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000918 ICK = ICK_Vector_Conversion;
919 return true;
920 }
Douglas Gregor46188682010-05-18 22:42:18 +0000921 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000922
Douglas Gregor46188682010-05-18 22:42:18 +0000923 return false;
924}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000925
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000926/// IsStandardConversion - Determines whether there is a standard
927/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
928/// expression From to the type ToType. Standard conversion sequences
929/// only consider non-class types; for conversions that involve class
930/// types, use TryImplicitConversion. If a conversion exists, SCS will
931/// contain the standard conversion sequence required to perform this
932/// conversion and this routine will return true. Otherwise, this
933/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000934static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
935 bool InOverloadResolution,
936 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000937 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000938
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000939 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000940 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000941 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000942 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000943 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000944 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000945
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000946 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000947 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000948 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000949 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000950 return false;
951
Mike Stump11289f42009-09-09 15:08:12 +0000952 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000953 }
954
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 // The first conversion can be an lvalue-to-rvalue conversion,
956 // array-to-pointer conversion, or function-to-pointer conversion
957 // (C++ 4p1).
958
John McCall5c32be02010-08-24 20:38:10 +0000959 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000960 DeclAccessPair AccessPair;
961 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000962 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
963 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000964 // We were able to resolve the address of the overloaded function,
965 // so we can convert to the type of that function.
966 FromType = Fn->getType();
967 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
968 if (!Method->isStatic()) {
969 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000970 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
971 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000972 }
973 }
974
975 // If the "from" expression takes the address of the overloaded
976 // function, update the type of the resulting expression accordingly.
977 if (FromType->getAs<FunctionType>())
978 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
979 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000980 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000981
982 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000983 assert(S.Context.hasSameType(FromType,
984 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +0000985 } else {
986 return false;
987 }
988 }
Mike Stump11289f42009-09-09 15:08:12 +0000989 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000990 // An lvalue (3.10) of a non-function, non-array type T can be
991 // converted to an rvalue.
John McCall5c32be02010-08-24 20:38:10 +0000992 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +0000993 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000994 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +0000995 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000996 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000997
998 // If T is a non-class type, the type of the rvalue is the
999 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001000 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1001 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001002 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001003 } else if (FromType->isArrayType()) {
1004 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001005 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001006
1007 // An lvalue or rvalue of type "array of N T" or "array of unknown
1008 // bound of T" can be converted to an rvalue of type "pointer to
1009 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001010 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001011
John McCall5c32be02010-08-24 20:38:10 +00001012 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001013 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001014 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015
1016 // For the purpose of ranking in overload resolution
1017 // (13.3.3.1.1), this conversion is considered an
1018 // array-to-pointer conversion followed by a qualification
1019 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001020 SCS.Second = ICK_Identity;
1021 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001022 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001023 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001024 }
Mike Stump12b8ce12009-08-04 21:02:39 +00001025 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1026 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001027 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028
1029 // An lvalue of function type T can be converted to an rvalue of
1030 // type "pointer to T." The result is a pointer to the
1031 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001032 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001033 } else {
1034 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001035 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001036 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001037 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038
1039 // The second conversion can be an integral promotion, floating
1040 // point promotion, integral conversion, floating point conversion,
1041 // floating-integral conversion, pointer conversion,
1042 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001043 // For overloading in C, this can also be a "compatible-type"
1044 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001045 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001046 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001047 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001048 // The unqualified versions of the types are the same: there's no
1049 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001050 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001051 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001052 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001053 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001054 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001055 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001056 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001057 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001058 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001059 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001060 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001061 SCS.Second = ICK_Complex_Promotion;
1062 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001063 } else if (FromType->isIntegralOrEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001064 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001065 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001066 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001067 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001068 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1069 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001070 SCS.Second = ICK_Complex_Conversion;
1071 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001072 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1073 (ToType->isComplexType() && FromType->isArithmeticType())) {
1074 // Complex-real conversions (C99 6.3.1.7)
1075 SCS.Second = ICK_Complex_Real;
1076 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001077 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001078 // Floating point conversions (C++ 4.8).
1079 SCS.Second = ICK_Floating_Conversion;
1080 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001081 } else if ((FromType->isRealFloatingType() &&
John McCall5c32be02010-08-24 20:38:10 +00001082 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001083 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001084 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001085 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001086 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001088 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1089 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001090 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001091 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001092 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001093 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1094 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001095 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001096 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001097 } else if (ToType->isBooleanType() &&
1098 (FromType->isArithmeticType() ||
1099 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001100 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001101 FromType->isBlockPointerType() ||
1102 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001103 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001104 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001105 SCS.Second = ICK_Boolean_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001106 FromType = S.Context.BoolTy;
1107 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001108 SCS.Second = SecondICK;
1109 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001110 } else if (!S.getLangOptions().CPlusPlus &&
1111 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001112 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001113 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001114 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001115 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001116 // Treat a conversion that strips "noreturn" as an identity conversion.
1117 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001118 } else {
1119 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001120 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001121 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001122 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001124 QualType CanonFrom;
1125 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001127 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001128 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001130 CanonFrom = S.Context.getCanonicalType(FromType);
1131 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 } else {
1133 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001134 SCS.Third = ICK_Identity;
1135
Mike Stump11289f42009-09-09 15:08:12 +00001136 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001137 // [...] Any difference in top-level cv-qualification is
1138 // subsumed by the initialization itself and does not constitute
1139 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001140 CanonFrom = S.Context.getCanonicalType(FromType);
1141 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001142 if (CanonFrom.getLocalUnqualifiedType()
1143 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001144 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1145 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001146 FromType = ToType;
1147 CanonFrom = CanonTo;
1148 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001150 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151
1152 // If we have not converted the argument type to the parameter type,
1153 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001154 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158}
1159
1160/// IsIntegralPromotion - Determines whether the conversion from the
1161/// expression From (whose potentially-adjusted type is FromType) to
1162/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1163/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001164bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001165 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001166 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001167 if (!To) {
1168 return false;
1169 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
1171 // An rvalue of type char, signed char, unsigned char, short int, or
1172 // unsigned short int can be converted to an rvalue of type int if
1173 // int can represent all the values of the source type; otherwise,
1174 // the source rvalue can be converted to an rvalue of type unsigned
1175 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001176 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1177 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001178 if (// We can promote any signed, promotable integer type to an int
1179 (FromType->isSignedIntegerType() ||
1180 // We can promote any unsigned integer type whose size is
1181 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001182 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001183 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001185 }
1186
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::UInt;
1188 }
1189
1190 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1191 // can be converted to an rvalue of the first of the following types
1192 // that can represent all the values of its underlying type: int,
1193 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001194
1195 // We pre-calculate the promotion type for enum types.
1196 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1197 if (ToType->isIntegerType())
1198 return Context.hasSameUnqualifiedType(ToType,
1199 FromEnumType->getDecl()->getPromotionType());
1200
1201 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202 // Determine whether the type we're converting from is signed or
1203 // unsigned.
1204 bool FromIsSigned;
1205 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001206
1207 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1208 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209
1210 // The types we'll try to promote to, in the appropriate
1211 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001212 QualType PromoteTypes[6] = {
1213 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001214 Context.LongTy, Context.UnsignedLongTy ,
1215 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001216 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001217 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001218 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1219 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001220 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001221 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1222 // We found the type that we can promote to. If this is the
1223 // type we wanted, we have a promotion. Otherwise, no
1224 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001225 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 }
1227 }
1228 }
1229
1230 // An rvalue for an integral bit-field (9.6) can be converted to an
1231 // rvalue of type int if int can represent all the values of the
1232 // bit-field; otherwise, it can be converted to unsigned int if
1233 // unsigned int can represent all the values of the bit-field. If
1234 // the bit-field is larger yet, no integral promotion applies to
1235 // it. If the bit-field has an enumerated type, it is treated as any
1236 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001237 // FIXME: We should delay checking of bit-fields until we actually perform the
1238 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001239 using llvm::APSInt;
1240 if (From)
1241 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001242 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001243 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001244 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1245 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1246 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001247
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001248 // Are we promoting to an int from a bitfield that fits in an int?
1249 if (BitWidth < ToSize ||
1250 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1251 return To->getKind() == BuiltinType::Int;
1252 }
Mike Stump11289f42009-09-09 15:08:12 +00001253
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001254 // Are we promoting to an unsigned int from an unsigned bitfield
1255 // that fits into an unsigned int?
1256 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1257 return To->getKind() == BuiltinType::UInt;
1258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001260 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001261 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264 // An rvalue of type bool can be converted to an rvalue of type int,
1265 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001266 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001268 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269
1270 return false;
1271}
1272
1273/// IsFloatingPointPromotion - Determines whether the conversion from
1274/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1275/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001276bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277 /// An rvalue of type float can be converted to an rvalue of type
1278 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001279 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1280 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001281 if (FromBuiltin->getKind() == BuiltinType::Float &&
1282 ToBuiltin->getKind() == BuiltinType::Double)
1283 return true;
1284
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001285 // C99 6.3.1.5p1:
1286 // When a float is promoted to double or long double, or a
1287 // double is promoted to long double [...].
1288 if (!getLangOptions().CPlusPlus &&
1289 (FromBuiltin->getKind() == BuiltinType::Float ||
1290 FromBuiltin->getKind() == BuiltinType::Double) &&
1291 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1292 return true;
1293 }
1294
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295 return false;
1296}
1297
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001298/// \brief Determine if a conversion is a complex promotion.
1299///
1300/// A complex promotion is defined as a complex -> complex conversion
1301/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001302/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001303bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001304 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001305 if (!FromComplex)
1306 return false;
1307
John McCall9dd450b2009-09-21 23:43:11 +00001308 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001309 if (!ToComplex)
1310 return false;
1311
1312 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001313 ToComplex->getElementType()) ||
1314 IsIntegralPromotion(0, FromComplex->getElementType(),
1315 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001316}
1317
Douglas Gregor237f96c2008-11-26 23:31:11 +00001318/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1319/// the pointer type FromPtr to a pointer to type ToPointee, with the
1320/// same type qualifiers as FromPtr has on its pointee type. ToType,
1321/// if non-empty, will be a pointer to ToType that may or may not have
1322/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001323static QualType
1324BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001325 QualType ToPointee, QualType ToType,
1326 ASTContext &Context) {
1327 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1328 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001329 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001330
1331 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001332 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001333 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001334 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001335 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001336
1337 // Build a pointer to ToPointee. It has the right qualifiers
1338 // already.
1339 return Context.getPointerType(ToPointee);
1340 }
1341
1342 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001343 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001344 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1345 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001346}
1347
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001348/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1349/// the FromType, which is an objective-c pointer, to ToType, which may or may
1350/// not have the right set of qualifiers.
1351static QualType
1352BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1353 QualType ToType,
1354 ASTContext &Context) {
1355 QualType CanonFromType = Context.getCanonicalType(FromType);
1356 QualType CanonToType = Context.getCanonicalType(ToType);
1357 Qualifiers Quals = CanonFromType.getQualifiers();
1358
1359 // Exact qualifier match -> return the pointer type we're converting to.
1360 if (CanonToType.getLocalQualifiers() == Quals)
1361 return ToType;
1362
1363 // Just build a canonical type that has the right qualifiers.
1364 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1365}
1366
Mike Stump11289f42009-09-09 15:08:12 +00001367static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001368 bool InOverloadResolution,
1369 ASTContext &Context) {
1370 // Handle value-dependent integral null pointer constants correctly.
1371 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1372 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001373 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001374 return !InOverloadResolution;
1375
Douglas Gregor56751b52009-09-25 04:25:58 +00001376 return Expr->isNullPointerConstant(Context,
1377 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1378 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001379}
Mike Stump11289f42009-09-09 15:08:12 +00001380
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001381/// IsPointerConversion - Determines whether the conversion of the
1382/// expression From, which has the (possibly adjusted) type FromType,
1383/// can be converted to the type ToType via a pointer conversion (C++
1384/// 4.10). If so, returns true and places the converted type (that
1385/// might differ from ToType in its cv-qualifiers at some level) into
1386/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001387///
Douglas Gregora29dc052008-11-27 01:19:21 +00001388/// This routine also supports conversions to and from block pointers
1389/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1390/// pointers to interfaces. FIXME: Once we've determined the
1391/// appropriate overloading rules for Objective-C, we may want to
1392/// split the Objective-C checks into a different routine; however,
1393/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001394/// conversions, so for now they live here. IncompatibleObjC will be
1395/// set if the conversion is an allowed Objective-C conversion that
1396/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001398 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001399 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001400 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001401 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001402 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1403 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001404
Mike Stump11289f42009-09-09 15:08:12 +00001405 // Conversion from a null pointer constant to any Objective-C pointer type.
1406 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001407 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001408 ConvertedType = ToType;
1409 return true;
1410 }
1411
Douglas Gregor231d1c62008-11-27 00:15:41 +00001412 // Blocks: Block pointers can be converted to void*.
1413 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001414 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001415 ConvertedType = ToType;
1416 return true;
1417 }
1418 // Blocks: A null pointer constant can be converted to a block
1419 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001420 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001421 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001422 ConvertedType = ToType;
1423 return true;
1424 }
1425
Sebastian Redl576fd422009-05-10 18:38:11 +00001426 // If the left-hand-side is nullptr_t, the right side can be a null
1427 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001428 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001429 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001430 ConvertedType = ToType;
1431 return true;
1432 }
1433
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001434 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435 if (!ToTypePtr)
1436 return false;
1437
1438 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001439 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440 ConvertedType = ToType;
1441 return true;
1442 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001443
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001444 // Beyond this point, both types need to be pointers
1445 // , including objective-c pointers.
1446 QualType ToPointeeType = ToTypePtr->getPointeeType();
1447 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1448 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1449 ToType, Context);
1450 return true;
1451
1452 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001453 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001454 if (!FromTypePtr)
1455 return false;
1456
1457 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001458
Douglas Gregorfb640862010-08-18 21:25:30 +00001459 // If the unqualified pointee types are the same, this can't be a
1460 // pointer conversion, so don't do all of the work below.
1461 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1462 return false;
1463
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001464 // An rvalue of type "pointer to cv T," where T is an object type,
1465 // can be converted to an rvalue of type "pointer to cv void" (C++
1466 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001467 if (FromPointeeType->isIncompleteOrObjectType() &&
1468 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001469 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001470 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001471 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472 return true;
1473 }
1474
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001475 // When we're overloading in C, we allow a special kind of pointer
1476 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001477 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001478 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001479 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001480 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001481 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001482 return true;
1483 }
1484
Douglas Gregor5c407d92008-10-23 00:40:37 +00001485 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001486 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001487 // An rvalue of type "pointer to cv D," where D is a class type,
1488 // can be converted to an rvalue of type "pointer to cv B," where
1489 // B is a base class (clause 10) of D. If B is an inaccessible
1490 // (clause 11) or ambiguous (10.2) base class of D, a program that
1491 // necessitates this conversion is ill-formed. The result of the
1492 // conversion is a pointer to the base class sub-object of the
1493 // derived class object. The null pointer value is converted to
1494 // the null pointer value of the destination type.
1495 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001496 // Note that we do not check for ambiguity or inaccessibility
1497 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001498 if (getLangOptions().CPlusPlus &&
1499 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001500 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001501 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001502 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001503 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001504 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001505 ToType, Context);
1506 return true;
1507 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001508
Douglas Gregora119f102008-12-19 19:13:09 +00001509 return false;
1510}
1511
1512/// isObjCPointerConversion - Determines whether this is an
1513/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1514/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001515bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001516 QualType& ConvertedType,
1517 bool &IncompatibleObjC) {
1518 if (!getLangOptions().ObjC1)
1519 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001520
Steve Naroff7cae42b2009-07-10 23:34:53 +00001521 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001522 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001523 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001524 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001525
Steve Naroff7cae42b2009-07-10 23:34:53 +00001526 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001527 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001528 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001529 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001530 ConvertedType = ToType;
1531 return true;
1532 }
1533 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001534 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001535 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001536 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001537 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001538 ConvertedType = ToType;
1539 return true;
1540 }
1541 // Objective C++: We're able to convert from a pointer to an
1542 // interface to a pointer to a different interface.
1543 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001544 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1545 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1546 if (getLangOptions().CPlusPlus && LHS && RHS &&
1547 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1548 FromObjCPtr->getPointeeType()))
1549 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001550 ConvertedType = ToType;
1551 return true;
1552 }
1553
1554 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1555 // Okay: this is some kind of implicit downcast of Objective-C
1556 // interfaces, which is permitted. However, we're going to
1557 // complain about it.
1558 IncompatibleObjC = true;
1559 ConvertedType = FromType;
1560 return true;
1561 }
Mike Stump11289f42009-09-09 15:08:12 +00001562 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001563 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001564 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001565 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001566 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001567 else if (const BlockPointerType *ToBlockPtr =
1568 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001569 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001570 // to a block pointer type.
1571 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1572 ConvertedType = ToType;
1573 return true;
1574 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001575 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001576 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001577 else if (FromType->getAs<BlockPointerType>() &&
1578 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1579 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001580 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001581 ConvertedType = ToType;
1582 return true;
1583 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001584 else
Douglas Gregora119f102008-12-19 19:13:09 +00001585 return false;
1586
Douglas Gregor033f56d2008-12-23 00:53:59 +00001587 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001588 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001589 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001590 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001591 FromPointeeType = FromBlockPtr->getPointeeType();
1592 else
Douglas Gregora119f102008-12-19 19:13:09 +00001593 return false;
1594
Douglas Gregora119f102008-12-19 19:13:09 +00001595 // If we have pointers to pointers, recursively check whether this
1596 // is an Objective-C conversion.
1597 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1598 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1599 IncompatibleObjC)) {
1600 // We always complain about this conversion.
1601 IncompatibleObjC = true;
1602 ConvertedType = ToType;
1603 return true;
1604 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001605 // Allow conversion of pointee being objective-c pointer to another one;
1606 // as in I* to id.
1607 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1608 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1609 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1610 IncompatibleObjC)) {
1611 ConvertedType = ToType;
1612 return true;
1613 }
1614
Douglas Gregor033f56d2008-12-23 00:53:59 +00001615 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001616 // differences in the argument and result types are in Objective-C
1617 // pointer conversions. If so, we permit the conversion (but
1618 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001619 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001620 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001621 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001622 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001623 if (FromFunctionType && ToFunctionType) {
1624 // If the function types are exactly the same, this isn't an
1625 // Objective-C pointer conversion.
1626 if (Context.getCanonicalType(FromPointeeType)
1627 == Context.getCanonicalType(ToPointeeType))
1628 return false;
1629
1630 // Perform the quick checks that will tell us whether these
1631 // function types are obviously different.
1632 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1633 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1634 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1635 return false;
1636
1637 bool HasObjCConversion = false;
1638 if (Context.getCanonicalType(FromFunctionType->getResultType())
1639 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1640 // Okay, the types match exactly. Nothing to do.
1641 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1642 ToFunctionType->getResultType(),
1643 ConvertedType, IncompatibleObjC)) {
1644 // Okay, we have an Objective-C pointer conversion.
1645 HasObjCConversion = true;
1646 } else {
1647 // Function types are too different. Abort.
1648 return false;
1649 }
Mike Stump11289f42009-09-09 15:08:12 +00001650
Douglas Gregora119f102008-12-19 19:13:09 +00001651 // Check argument types.
1652 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1653 ArgIdx != NumArgs; ++ArgIdx) {
1654 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1655 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1656 if (Context.getCanonicalType(FromArgType)
1657 == Context.getCanonicalType(ToArgType)) {
1658 // Okay, the types match exactly. Nothing to do.
1659 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1660 ConvertedType, IncompatibleObjC)) {
1661 // Okay, we have an Objective-C pointer conversion.
1662 HasObjCConversion = true;
1663 } else {
1664 // Argument types are too different. Abort.
1665 return false;
1666 }
1667 }
1668
1669 if (HasObjCConversion) {
1670 // We had an Objective-C conversion. Allow this pointer
1671 // conversion, but complain about it.
1672 ConvertedType = ToType;
1673 IncompatibleObjC = true;
1674 return true;
1675 }
1676 }
1677
Sebastian Redl72b597d2009-01-25 19:43:20 +00001678 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001680
1681/// FunctionArgTypesAreEqual - This routine checks two function proto types
1682/// for equlity of their argument types. Caller has already checked that
1683/// they have same number of arguments. This routine assumes that Objective-C
1684/// pointer types which only differ in their protocol qualifiers are equal.
1685bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1686 FunctionProtoType* NewType){
1687 if (!getLangOptions().ObjC1)
1688 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1689 NewType->arg_type_begin());
1690
1691 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1692 N = NewType->arg_type_begin(),
1693 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1694 QualType ToType = (*O);
1695 QualType FromType = (*N);
1696 if (ToType != FromType) {
1697 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1698 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001699 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1700 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1701 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1702 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001703 continue;
1704 }
John McCall8b07ec22010-05-15 11:32:37 +00001705 else if (const ObjCObjectPointerType *PTTo =
1706 ToType->getAs<ObjCObjectPointerType>()) {
1707 if (const ObjCObjectPointerType *PTFr =
1708 FromType->getAs<ObjCObjectPointerType>())
1709 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1710 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001711 }
1712 return false;
1713 }
1714 }
1715 return true;
1716}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717
Douglas Gregor39c16d42008-10-24 04:54:22 +00001718/// CheckPointerConversion - Check the pointer conversion from the
1719/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001720/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001721/// conversions for which IsPointerConversion has already returned
1722/// true. It returns true and produces a diagnostic if there was an
1723/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001724bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001725 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001726 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001727 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001728 QualType FromType = From->getType();
1729
Douglas Gregor4038cf42010-06-08 17:35:15 +00001730 if (CXXBoolLiteralExpr* LitBool
1731 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1732 if (LitBool->getValue() == false)
1733 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1734 << ToType;
1735
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001736 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1737 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001738 QualType FromPointeeType = FromPtrType->getPointeeType(),
1739 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001740
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001741 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1742 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001743 // We must have a derived-to-base conversion. Check an
1744 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001745 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1746 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001747 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001748 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001749 return true;
1750
1751 // The conversion was successful.
1752 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001753 }
1754 }
Mike Stump11289f42009-09-09 15:08:12 +00001755 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001756 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001757 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001758 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001759 // Objective-C++ conversions are always okay.
1760 // FIXME: We should have a different class of conversions for the
1761 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001762 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001763 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001764
Steve Naroff7cae42b2009-07-10 23:34:53 +00001765 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001766 return false;
1767}
1768
Sebastian Redl72b597d2009-01-25 19:43:20 +00001769/// IsMemberPointerConversion - Determines whether the conversion of the
1770/// expression From, which has the (possibly adjusted) type FromType, can be
1771/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1772/// If so, returns true and places the converted type (that might differ from
1773/// ToType in its cv-qualifiers at some level) into ConvertedType.
1774bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001775 QualType ToType,
1776 bool InOverloadResolution,
1777 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001778 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001779 if (!ToTypePtr)
1780 return false;
1781
1782 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001783 if (From->isNullPointerConstant(Context,
1784 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1785 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001786 ConvertedType = ToType;
1787 return true;
1788 }
1789
1790 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001791 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001792 if (!FromTypePtr)
1793 return false;
1794
1795 // A pointer to member of B can be converted to a pointer to member of D,
1796 // where D is derived from B (C++ 4.11p2).
1797 QualType FromClass(FromTypePtr->getClass(), 0);
1798 QualType ToClass(ToTypePtr->getClass(), 0);
1799 // FIXME: What happens when these are dependent? Is this function even called?
1800
1801 if (IsDerivedFrom(ToClass, FromClass)) {
1802 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1803 ToClass.getTypePtr());
1804 return true;
1805 }
1806
1807 return false;
1808}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001809
Sebastian Redl72b597d2009-01-25 19:43:20 +00001810/// CheckMemberPointerConversion - Check the member pointer conversion from the
1811/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001812/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001813/// for which IsMemberPointerConversion has already returned true. It returns
1814/// true and produces a diagnostic if there was an error, or returns false
1815/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001816bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001817 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001818 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001819 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001820 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001821 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001822 if (!FromPtrType) {
1823 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001824 assert(From->isNullPointerConstant(Context,
1825 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001826 "Expr must be null pointer constant!");
1827 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001828 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001829 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001830
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001831 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001832 assert(ToPtrType && "No member pointer cast has a target type "
1833 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001834
Sebastian Redled8f2002009-01-28 18:33:18 +00001835 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1836 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001837
Sebastian Redled8f2002009-01-28 18:33:18 +00001838 // FIXME: What about dependent types?
1839 assert(FromClass->isRecordType() && "Pointer into non-class.");
1840 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001841
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001842 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001843 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001844 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1845 assert(DerivationOkay &&
1846 "Should not have been called if derivation isn't OK.");
1847 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001848
Sebastian Redled8f2002009-01-28 18:33:18 +00001849 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1850 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001851 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1852 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1853 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1854 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001855 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001856
Douglas Gregor89ee6822009-02-28 01:32:25 +00001857 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001858 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1859 << FromClass << ToClass << QualType(VBase, 0)
1860 << From->getSourceRange();
1861 return true;
1862 }
1863
John McCall5b0829a2010-02-10 09:31:12 +00001864 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001865 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1866 Paths.front(),
1867 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001868
Anders Carlssond7923c62009-08-22 23:33:40 +00001869 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001870 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001871 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001872 return false;
1873}
1874
Douglas Gregor9a657932008-10-21 23:43:52 +00001875/// IsQualificationConversion - Determines whether the conversion from
1876/// an rvalue of type FromType to ToType is a qualification conversion
1877/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001878bool
1879Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001880 FromType = Context.getCanonicalType(FromType);
1881 ToType = Context.getCanonicalType(ToType);
1882
1883 // If FromType and ToType are the same type, this is not a
1884 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001885 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001886 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001887
Douglas Gregor9a657932008-10-21 23:43:52 +00001888 // (C++ 4.4p4):
1889 // A conversion can add cv-qualifiers at levels other than the first
1890 // in multi-level pointers, subject to the following rules: [...]
1891 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001892 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001893 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001894 // Within each iteration of the loop, we check the qualifiers to
1895 // determine if this still looks like a qualification
1896 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001897 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001898 // until there are no more pointers or pointers-to-members left to
1899 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001900 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001901
1902 // -- for every j > 0, if const is in cv 1,j then const is in cv
1903 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001904 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001905 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001906
Douglas Gregor9a657932008-10-21 23:43:52 +00001907 // -- if the cv 1,j and cv 2,j are different, then const is in
1908 // every cv for 0 < k < j.
1909 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001910 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001911 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregor9a657932008-10-21 23:43:52 +00001913 // Keep track of whether all prior cv-qualifiers in the "to" type
1914 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001915 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001916 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001917 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001918
1919 // We are left with FromType and ToType being the pointee types
1920 // after unwrapping the original FromType and ToType the same number
1921 // of types. If we unwrapped any pointers, and if FromType and
1922 // ToType have the same unqualified type (since we checked
1923 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001924 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001925}
1926
Douglas Gregor576e98c2009-01-30 23:27:23 +00001927/// Determines whether there is a user-defined conversion sequence
1928/// (C++ [over.ics.user]) that converts expression From to the type
1929/// ToType. If such a conversion exists, User will contain the
1930/// user-defined conversion sequence that performs such a conversion
1931/// and this routine will return true. Otherwise, this routine returns
1932/// false and User is unspecified.
1933///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001934/// \param AllowExplicit true if the conversion should consider C++0x
1935/// "explicit" conversion functions as well as non-explicit conversion
1936/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001937static OverloadingResult
1938IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1939 UserDefinedConversionSequence& User,
1940 OverloadCandidateSet& CandidateSet,
1941 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001942 // Whether we will only visit constructors.
1943 bool ConstructorsOnly = false;
1944
1945 // If the type we are conversion to is a class type, enumerate its
1946 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001947 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001948 // C++ [over.match.ctor]p1:
1949 // When objects of class type are direct-initialized (8.5), or
1950 // copy-initialized from an expression of the same or a
1951 // derived class type (8.5), overload resolution selects the
1952 // constructor. [...] For copy-initialization, the candidate
1953 // functions are all the converting constructors (12.3.1) of
1954 // that class. The argument list is the expression-list within
1955 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00001956 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00001957 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001958 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001959 ConstructorsOnly = true;
1960
John McCall5c32be02010-08-24 20:38:10 +00001961 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001962 // We're not going to find any constructors.
1963 } else if (CXXRecordDecl *ToRecordDecl
1964 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001965 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00001966 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001967 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001968 NamedDecl *D = *Con;
1969 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1970
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001971 // Find the constructor (which may be a template).
1972 CXXConstructorDecl *Constructor = 0;
1973 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001974 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001975 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001976 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001977 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1978 else
John McCalla0296f72010-03-19 07:35:19 +00001979 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001980
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001981 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001982 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001983 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00001984 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1985 /*ExplicitArgs*/ 0,
1986 &From, 1, CandidateSet,
1987 /*SuppressUserConversions=*/
1988 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001989 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001990 // Allow one user-defined conversion when user specifies a
1991 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00001992 S.AddOverloadCandidate(Constructor, FoundDecl,
1993 &From, 1, CandidateSet,
1994 /*SuppressUserConversions=*/
1995 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001996 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001997 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001998 }
1999 }
2000
Douglas Gregor5ab11652010-04-17 22:01:05 +00002001 // Enumerate conversion functions, if we're allowed to.
2002 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002003 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2004 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002005 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002006 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002007 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002008 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002009 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2010 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002011 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002012 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002013 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002014 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002015 DeclAccessPair FoundDecl = I.getPair();
2016 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002017 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2018 if (isa<UsingShadowDecl>(D))
2019 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2020
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002021 CXXConversionDecl *Conv;
2022 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002023 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2024 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002025 else
John McCallda4458e2010-03-31 01:36:47 +00002026 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002027
2028 if (AllowExplicit || !Conv->isExplicit()) {
2029 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002030 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2031 ActingContext, From, ToType,
2032 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002033 else
John McCall5c32be02010-08-24 20:38:10 +00002034 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2035 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002036 }
2037 }
2038 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002039 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002040
2041 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00002042 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best)) {
2043 case OR_Success:
2044 // Record the standard conversion we used and the conversion function.
2045 if (CXXConstructorDecl *Constructor
2046 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2047 // C++ [over.ics.user]p1:
2048 // If the user-defined conversion is specified by a
2049 // constructor (12.3.1), the initial standard conversion
2050 // sequence converts the source type to the type required by
2051 // the argument of the constructor.
2052 //
2053 QualType ThisType = Constructor->getThisType(S.Context);
2054 if (Best->Conversions[0].isEllipsis())
2055 User.EllipsisConversion = true;
2056 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002057 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002058 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002059 }
John McCall5c32be02010-08-24 20:38:10 +00002060 User.ConversionFunction = Constructor;
2061 User.After.setAsIdentityConversion();
2062 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2063 User.After.setAllToTypes(ToType);
2064 return OR_Success;
2065 } else if (CXXConversionDecl *Conversion
2066 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2067 // C++ [over.ics.user]p1:
2068 //
2069 // [...] If the user-defined conversion is specified by a
2070 // conversion function (12.3.2), the initial standard
2071 // conversion sequence converts the source type to the
2072 // implicit object parameter of the conversion function.
2073 User.Before = Best->Conversions[0].Standard;
2074 User.ConversionFunction = Conversion;
2075 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002076
John McCall5c32be02010-08-24 20:38:10 +00002077 // C++ [over.ics.user]p2:
2078 // The second standard conversion sequence converts the
2079 // result of the user-defined conversion to the target type
2080 // for the sequence. Since an implicit conversion sequence
2081 // is an initialization, the special rules for
2082 // initialization by user-defined conversion apply when
2083 // selecting the best user-defined conversion for a
2084 // user-defined conversion sequence (see 13.3.3 and
2085 // 13.3.3.1).
2086 User.After = Best->FinalConversion;
2087 return OR_Success;
2088 } else {
2089 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002090 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002091 }
2092
John McCall5c32be02010-08-24 20:38:10 +00002093 case OR_No_Viable_Function:
2094 return OR_No_Viable_Function;
2095 case OR_Deleted:
2096 // No conversion here! We're done.
2097 return OR_Deleted;
2098
2099 case OR_Ambiguous:
2100 return OR_Ambiguous;
2101 }
2102
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002103 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002104}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002105
2106bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002107Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002108 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002109 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002110 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002111 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002112 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002113 if (OvResult == OR_Ambiguous)
2114 Diag(From->getSourceRange().getBegin(),
2115 diag::err_typecheck_ambiguous_condition)
2116 << From->getType() << ToType << From->getSourceRange();
2117 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2118 Diag(From->getSourceRange().getBegin(),
2119 diag::err_typecheck_nonviable_condition)
2120 << From->getType() << ToType << From->getSourceRange();
2121 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002122 return false;
John McCall5c32be02010-08-24 20:38:10 +00002123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002124 return true;
2125}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002126
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002127/// CompareImplicitConversionSequences - Compare two implicit
2128/// conversion sequences to determine whether one is better than the
2129/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002130static ImplicitConversionSequence::CompareKind
2131CompareImplicitConversionSequences(Sema &S,
2132 const ImplicitConversionSequence& ICS1,
2133 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002134{
2135 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2136 // conversion sequences (as defined in 13.3.3.1)
2137 // -- a standard conversion sequence (13.3.3.1.1) is a better
2138 // conversion sequence than a user-defined conversion sequence or
2139 // an ellipsis conversion sequence, and
2140 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2141 // conversion sequence than an ellipsis conversion sequence
2142 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002143 //
John McCall0d1da222010-01-12 00:44:57 +00002144 // C++0x [over.best.ics]p10:
2145 // For the purpose of ranking implicit conversion sequences as
2146 // described in 13.3.3.2, the ambiguous conversion sequence is
2147 // treated as a user-defined sequence that is indistinguishable
2148 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002149 if (ICS1.getKindRank() < ICS2.getKindRank())
2150 return ImplicitConversionSequence::Better;
2151 else if (ICS2.getKindRank() < ICS1.getKindRank())
2152 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002153
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002154 // The following checks require both conversion sequences to be of
2155 // the same kind.
2156 if (ICS1.getKind() != ICS2.getKind())
2157 return ImplicitConversionSequence::Indistinguishable;
2158
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002159 // Two implicit conversion sequences of the same form are
2160 // indistinguishable conversion sequences unless one of the
2161 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002162 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002163 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002164 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002165 // User-defined conversion sequence U1 is a better conversion
2166 // sequence than another user-defined conversion sequence U2 if
2167 // they contain the same user-defined conversion function or
2168 // constructor and if the second standard conversion sequence of
2169 // U1 is better than the second standard conversion sequence of
2170 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002171 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002172 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002173 return CompareStandardConversionSequences(S,
2174 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002175 ICS2.UserDefined.After);
2176 }
2177
2178 return ImplicitConversionSequence::Indistinguishable;
2179}
2180
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002181static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2182 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2183 Qualifiers Quals;
2184 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2185 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2186 }
2187
2188 return Context.hasSameUnqualifiedType(T1, T2);
2189}
2190
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002191// Per 13.3.3.2p3, compare the given standard conversion sequences to
2192// determine if one is a proper subset of the other.
2193static ImplicitConversionSequence::CompareKind
2194compareStandardConversionSubsets(ASTContext &Context,
2195 const StandardConversionSequence& SCS1,
2196 const StandardConversionSequence& SCS2) {
2197 ImplicitConversionSequence::CompareKind Result
2198 = ImplicitConversionSequence::Indistinguishable;
2199
Douglas Gregore87561a2010-05-23 22:10:15 +00002200 // the identity conversion sequence is considered to be a subsequence of
2201 // any non-identity conversion sequence
2202 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2203 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2204 return ImplicitConversionSequence::Better;
2205 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2206 return ImplicitConversionSequence::Worse;
2207 }
2208
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002209 if (SCS1.Second != SCS2.Second) {
2210 if (SCS1.Second == ICK_Identity)
2211 Result = ImplicitConversionSequence::Better;
2212 else if (SCS2.Second == ICK_Identity)
2213 Result = ImplicitConversionSequence::Worse;
2214 else
2215 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002216 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002217 return ImplicitConversionSequence::Indistinguishable;
2218
2219 if (SCS1.Third == SCS2.Third) {
2220 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2221 : ImplicitConversionSequence::Indistinguishable;
2222 }
2223
2224 if (SCS1.Third == ICK_Identity)
2225 return Result == ImplicitConversionSequence::Worse
2226 ? ImplicitConversionSequence::Indistinguishable
2227 : ImplicitConversionSequence::Better;
2228
2229 if (SCS2.Third == ICK_Identity)
2230 return Result == ImplicitConversionSequence::Better
2231 ? ImplicitConversionSequence::Indistinguishable
2232 : ImplicitConversionSequence::Worse;
2233
2234 return ImplicitConversionSequence::Indistinguishable;
2235}
2236
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002237/// CompareStandardConversionSequences - Compare two standard
2238/// conversion sequences to determine whether one is better than the
2239/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002240static ImplicitConversionSequence::CompareKind
2241CompareStandardConversionSequences(Sema &S,
2242 const StandardConversionSequence& SCS1,
2243 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002244{
2245 // Standard conversion sequence S1 is a better conversion sequence
2246 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2247
2248 // -- S1 is a proper subsequence of S2 (comparing the conversion
2249 // sequences in the canonical form defined by 13.3.3.1.1,
2250 // excluding any Lvalue Transformation; the identity conversion
2251 // sequence is considered to be a subsequence of any
2252 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002253 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002254 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002255 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002256
2257 // -- the rank of S1 is better than the rank of S2 (by the rules
2258 // defined below), or, if not that,
2259 ImplicitConversionRank Rank1 = SCS1.getRank();
2260 ImplicitConversionRank Rank2 = SCS2.getRank();
2261 if (Rank1 < Rank2)
2262 return ImplicitConversionSequence::Better;
2263 else if (Rank2 < Rank1)
2264 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002266 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2267 // are indistinguishable unless one of the following rules
2268 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002269
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002270 // A conversion that is not a conversion of a pointer, or
2271 // pointer to member, to bool is better than another conversion
2272 // that is such a conversion.
2273 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2274 return SCS2.isPointerConversionToBool()
2275 ? ImplicitConversionSequence::Better
2276 : ImplicitConversionSequence::Worse;
2277
Douglas Gregor5c407d92008-10-23 00:40:37 +00002278 // C++ [over.ics.rank]p4b2:
2279 //
2280 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002281 // conversion of B* to A* is better than conversion of B* to
2282 // void*, and conversion of A* to void* is better than conversion
2283 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002284 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002285 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002286 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002287 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002288 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2289 // Exactly one of the conversion sequences is a conversion to
2290 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002291 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2292 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002293 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2294 // Neither conversion sequence converts to a void pointer; compare
2295 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002296 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002297 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002298 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002299 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2300 // Both conversion sequences are conversions to void
2301 // pointers. Compare the source types to determine if there's an
2302 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002303 QualType FromType1 = SCS1.getFromType();
2304 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002305
2306 // Adjust the types we're converting from via the array-to-pointer
2307 // conversion, if we need to.
2308 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002309 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002310 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002311 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002312
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002313 QualType FromPointee1
2314 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2315 QualType FromPointee2
2316 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002317
John McCall5c32be02010-08-24 20:38:10 +00002318 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002319 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002320 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002321 return ImplicitConversionSequence::Worse;
2322
2323 // Objective-C++: If one interface is more specific than the
2324 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002325 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2326 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002327 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002328 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002329 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002330 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002331 return ImplicitConversionSequence::Worse;
2332 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002333 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002334
2335 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2336 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002337 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002338 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002339 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002340
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002342 // C++0x [over.ics.rank]p3b4:
2343 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2344 // implicit object parameter of a non-static member function declared
2345 // without a ref-qualifier, and S1 binds an rvalue reference to an
2346 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002347 // FIXME: We don't know if we're dealing with the implicit object parameter,
2348 // or if the member function in this case has a ref qualifier.
2349 // (Of course, we don't have ref qualifiers yet.)
2350 if (SCS1.RRefBinding != SCS2.RRefBinding)
2351 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2352 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002353
2354 // C++ [over.ics.rank]p3b4:
2355 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2356 // which the references refer are the same type except for
2357 // top-level cv-qualifiers, and the type to which the reference
2358 // initialized by S2 refers is more cv-qualified than the type
2359 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002360 QualType T1 = SCS1.getToType(2);
2361 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002362 T1 = S.Context.getCanonicalType(T1);
2363 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002364 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002365 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2366 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002367 if (UnqualT1 == UnqualT2) {
2368 // If the type is an array type, promote the element qualifiers to the type
2369 // for comparison.
2370 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002371 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002372 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002373 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002374 if (T2.isMoreQualifiedThan(T1))
2375 return ImplicitConversionSequence::Better;
2376 else if (T1.isMoreQualifiedThan(T2))
2377 return ImplicitConversionSequence::Worse;
2378 }
2379 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002380
2381 return ImplicitConversionSequence::Indistinguishable;
2382}
2383
2384/// CompareQualificationConversions - Compares two standard conversion
2385/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002386/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2387ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002388CompareQualificationConversions(Sema &S,
2389 const StandardConversionSequence& SCS1,
2390 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002391 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002392 // -- S1 and S2 differ only in their qualification conversion and
2393 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2394 // cv-qualification signature of type T1 is a proper subset of
2395 // the cv-qualification signature of type T2, and S1 is not the
2396 // deprecated string literal array-to-pointer conversion (4.2).
2397 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2398 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2399 return ImplicitConversionSequence::Indistinguishable;
2400
2401 // FIXME: the example in the standard doesn't use a qualification
2402 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002403 QualType T1 = SCS1.getToType(2);
2404 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002405 T1 = S.Context.getCanonicalType(T1);
2406 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002407 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002408 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2409 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002410
2411 // If the types are the same, we won't learn anything by unwrapped
2412 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002413 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002414 return ImplicitConversionSequence::Indistinguishable;
2415
Chandler Carruth607f38e2009-12-29 07:16:59 +00002416 // If the type is an array type, promote the element qualifiers to the type
2417 // for comparison.
2418 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002419 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002420 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002421 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002422
Mike Stump11289f42009-09-09 15:08:12 +00002423 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002424 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002425 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002426 // Within each iteration of the loop, we check the qualifiers to
2427 // determine if this still looks like a qualification
2428 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002429 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002430 // until there are no more pointers or pointers-to-members left
2431 // to unwrap. This essentially mimics what
2432 // IsQualificationConversion does, but here we're checking for a
2433 // strict subset of qualifiers.
2434 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2435 // The qualifiers are the same, so this doesn't tell us anything
2436 // about how the sequences rank.
2437 ;
2438 else if (T2.isMoreQualifiedThan(T1)) {
2439 // T1 has fewer qualifiers, so it could be the better sequence.
2440 if (Result == ImplicitConversionSequence::Worse)
2441 // Neither has qualifiers that are a subset of the other's
2442 // qualifiers.
2443 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002444
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002445 Result = ImplicitConversionSequence::Better;
2446 } else if (T1.isMoreQualifiedThan(T2)) {
2447 // T2 has fewer qualifiers, so it could be the better sequence.
2448 if (Result == ImplicitConversionSequence::Better)
2449 // Neither has qualifiers that are a subset of the other's
2450 // qualifiers.
2451 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002452
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002453 Result = ImplicitConversionSequence::Worse;
2454 } else {
2455 // Qualifiers are disjoint.
2456 return ImplicitConversionSequence::Indistinguishable;
2457 }
2458
2459 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002460 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002461 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002462 }
2463
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002464 // Check that the winning standard conversion sequence isn't using
2465 // the deprecated string literal array to pointer conversion.
2466 switch (Result) {
2467 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002468 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002469 Result = ImplicitConversionSequence::Indistinguishable;
2470 break;
2471
2472 case ImplicitConversionSequence::Indistinguishable:
2473 break;
2474
2475 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002476 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002477 Result = ImplicitConversionSequence::Indistinguishable;
2478 break;
2479 }
2480
2481 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002482}
2483
Douglas Gregor5c407d92008-10-23 00:40:37 +00002484/// CompareDerivedToBaseConversions - Compares two standard conversion
2485/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002486/// various kinds of derived-to-base conversions (C++
2487/// [over.ics.rank]p4b3). As part of these checks, we also look at
2488/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002489ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002490CompareDerivedToBaseConversions(Sema &S,
2491 const StandardConversionSequence& SCS1,
2492 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002493 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002494 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002495 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002496 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002497
2498 // Adjust the types we're converting from via the array-to-pointer
2499 // conversion, if we need to.
2500 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002501 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002502 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002503 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002504
2505 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002506 FromType1 = S.Context.getCanonicalType(FromType1);
2507 ToType1 = S.Context.getCanonicalType(ToType1);
2508 FromType2 = S.Context.getCanonicalType(FromType2);
2509 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002510
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002511 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002512 //
2513 // If class B is derived directly or indirectly from class A and
2514 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002515 //
2516 // For Objective-C, we let A, B, and C also be Objective-C
2517 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002518
2519 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002520 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002521 SCS2.Second == ICK_Pointer_Conversion &&
2522 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2523 FromType1->isPointerType() && FromType2->isPointerType() &&
2524 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002525 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002526 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002527 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002528 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002529 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002530 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002531 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002532 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002533
John McCall8b07ec22010-05-15 11:32:37 +00002534 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2535 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2536 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2537 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002538
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002539 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002540 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002541 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002542 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002543 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002544 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002545
2546 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002547 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002548 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002549 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002550 return ImplicitConversionSequence::Worse;
2551 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002552 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002553
2554 // -- conversion of B* to A* is better than conversion of C* to A*,
2555 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002556 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002557 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002558 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002559 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregor237f96c2008-11-26 23:31:11 +00002561 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002562 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002563 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002564 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002565 return ImplicitConversionSequence::Worse;
2566 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002567 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002568 }
2569
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002570 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002571 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2572 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2573 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2574 const MemberPointerType * FromMemPointer1 =
2575 FromType1->getAs<MemberPointerType>();
2576 const MemberPointerType * ToMemPointer1 =
2577 ToType1->getAs<MemberPointerType>();
2578 const MemberPointerType * FromMemPointer2 =
2579 FromType2->getAs<MemberPointerType>();
2580 const MemberPointerType * ToMemPointer2 =
2581 ToType2->getAs<MemberPointerType>();
2582 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2583 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2584 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2585 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2586 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2587 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2588 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2589 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002590 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002591 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002592 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002593 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002594 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002595 return ImplicitConversionSequence::Better;
2596 }
2597 // conversion of B::* to C::* is better than conversion of A::* to C::*
2598 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002599 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002600 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002601 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002602 return ImplicitConversionSequence::Worse;
2603 }
2604 }
2605
Douglas Gregor5ab11652010-04-17 22:01:05 +00002606 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002607 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002608 // -- binding of an expression of type C to a reference of type
2609 // B& is better than binding an expression of type C to a
2610 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002611 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2612 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2613 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002614 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002615 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002616 return ImplicitConversionSequence::Worse;
2617 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002618
Douglas Gregor2fe98832008-11-03 19:09:14 +00002619 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002620 // -- binding of an expression of type B to a reference of type
2621 // A& is better than binding an expression of type C to a
2622 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002623 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2624 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2625 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002626 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002627 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002628 return ImplicitConversionSequence::Worse;
2629 }
2630 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002631
Douglas Gregor5c407d92008-10-23 00:40:37 +00002632 return ImplicitConversionSequence::Indistinguishable;
2633}
2634
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002635/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2636/// determine whether they are reference-related,
2637/// reference-compatible, reference-compatible with added
2638/// qualification, or incompatible, for use in C++ initialization by
2639/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2640/// type, and the first type (T1) is the pointee type of the reference
2641/// type being initialized.
2642Sema::ReferenceCompareResult
2643Sema::CompareReferenceRelationship(SourceLocation Loc,
2644 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002645 bool &DerivedToBase,
2646 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002647 assert(!OrigT1->isReferenceType() &&
2648 "T1 must be the pointee type of the reference type");
2649 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2650
2651 QualType T1 = Context.getCanonicalType(OrigT1);
2652 QualType T2 = Context.getCanonicalType(OrigT2);
2653 Qualifiers T1Quals, T2Quals;
2654 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2655 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2656
2657 // C++ [dcl.init.ref]p4:
2658 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2659 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2660 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002661 DerivedToBase = false;
2662 ObjCConversion = false;
2663 if (UnqualT1 == UnqualT2) {
2664 // Nothing to do.
2665 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002666 IsDerivedFrom(UnqualT2, UnqualT1))
2667 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002668 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2669 UnqualT2->isObjCObjectOrInterfaceType() &&
2670 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2671 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002672 else
2673 return Ref_Incompatible;
2674
2675 // At this point, we know that T1 and T2 are reference-related (at
2676 // least).
2677
2678 // If the type is an array type, promote the element qualifiers to the type
2679 // for comparison.
2680 if (isa<ArrayType>(T1) && T1Quals)
2681 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2682 if (isa<ArrayType>(T2) && T2Quals)
2683 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2684
2685 // C++ [dcl.init.ref]p4:
2686 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2687 // reference-related to T2 and cv1 is the same cv-qualification
2688 // as, or greater cv-qualification than, cv2. For purposes of
2689 // overload resolution, cases for which cv1 is greater
2690 // cv-qualification than cv2 are identified as
2691 // reference-compatible with added qualification (see 13.3.3.2).
2692 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2693 return Ref_Compatible;
2694 else if (T1.isMoreQualifiedThan(T2))
2695 return Ref_Compatible_With_Added_Qualification;
2696 else
2697 return Ref_Related;
2698}
2699
Douglas Gregor836a7e82010-08-11 02:15:33 +00002700/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002701/// with DeclType. Return true if something definite is found.
2702static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002703FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2704 QualType DeclType, SourceLocation DeclLoc,
2705 Expr *Init, QualType T2, bool AllowRvalues,
2706 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002707 assert(T2->isRecordType() && "Can only find conversions of record types.");
2708 CXXRecordDecl *T2RecordDecl
2709 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2710
Douglas Gregor836a7e82010-08-11 02:15:33 +00002711 QualType ToType
2712 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2713 : DeclType;
2714
Sebastian Redld92badf2010-06-30 18:13:39 +00002715 OverloadCandidateSet CandidateSet(DeclLoc);
2716 const UnresolvedSetImpl *Conversions
2717 = T2RecordDecl->getVisibleConversionFunctions();
2718 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2719 E = Conversions->end(); I != E; ++I) {
2720 NamedDecl *D = *I;
2721 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2722 if (isa<UsingShadowDecl>(D))
2723 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2724
2725 FunctionTemplateDecl *ConvTemplate
2726 = dyn_cast<FunctionTemplateDecl>(D);
2727 CXXConversionDecl *Conv;
2728 if (ConvTemplate)
2729 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2730 else
2731 Conv = cast<CXXConversionDecl>(D);
2732
Douglas Gregor836a7e82010-08-11 02:15:33 +00002733 // If this is an explicit conversion, and we're not allowed to consider
2734 // explicit conversions, skip it.
2735 if (!AllowExplicit && Conv->isExplicit())
2736 continue;
2737
2738 if (AllowRvalues) {
2739 bool DerivedToBase = false;
2740 bool ObjCConversion = false;
2741 if (!ConvTemplate &&
2742 S.CompareReferenceRelationship(DeclLoc,
2743 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2744 DeclType.getNonReferenceType().getUnqualifiedType(),
2745 DerivedToBase, ObjCConversion)
2746 == Sema::Ref_Incompatible)
2747 continue;
2748 } else {
2749 // If the conversion function doesn't return a reference type,
2750 // it can't be considered for this conversion. An rvalue reference
2751 // is only acceptable if its referencee is a function type.
2752
2753 const ReferenceType *RefType =
2754 Conv->getConversionType()->getAs<ReferenceType>();
2755 if (!RefType ||
2756 (!RefType->isLValueReferenceType() &&
2757 !RefType->getPointeeType()->isFunctionType()))
2758 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002759 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002760
2761 if (ConvTemplate)
2762 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2763 Init, ToType, CandidateSet);
2764 else
2765 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2766 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002767 }
2768
2769 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00002770 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002771 case OR_Success:
2772 // C++ [over.ics.ref]p1:
2773 //
2774 // [...] If the parameter binds directly to the result of
2775 // applying a conversion function to the argument
2776 // expression, the implicit conversion sequence is a
2777 // user-defined conversion sequence (13.3.3.1.2), with the
2778 // second standard conversion sequence either an identity
2779 // conversion or, if the conversion function returns an
2780 // entity of a type that is a derived class of the parameter
2781 // type, a derived-to-base Conversion.
2782 if (!Best->FinalConversion.DirectBinding)
2783 return false;
2784
2785 ICS.setUserDefined();
2786 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2787 ICS.UserDefined.After = Best->FinalConversion;
2788 ICS.UserDefined.ConversionFunction = Best->Function;
2789 ICS.UserDefined.EllipsisConversion = false;
2790 assert(ICS.UserDefined.After.ReferenceBinding &&
2791 ICS.UserDefined.After.DirectBinding &&
2792 "Expected a direct reference binding!");
2793 return true;
2794
2795 case OR_Ambiguous:
2796 ICS.setAmbiguous();
2797 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2798 Cand != CandidateSet.end(); ++Cand)
2799 if (Cand->Viable)
2800 ICS.Ambiguous.addConversion(Cand->Function);
2801 return true;
2802
2803 case OR_No_Viable_Function:
2804 case OR_Deleted:
2805 // There was no suitable conversion, or we found a deleted
2806 // conversion; continue with other checks.
2807 return false;
2808 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002809
2810 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002811}
2812
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002813/// \brief Compute an implicit conversion sequence for reference
2814/// initialization.
2815static ImplicitConversionSequence
2816TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2817 SourceLocation DeclLoc,
2818 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002819 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002820 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2821
2822 // Most paths end in a failed conversion.
2823 ImplicitConversionSequence ICS;
2824 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2825
2826 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2827 QualType T2 = Init->getType();
2828
2829 // If the initializer is the address of an overloaded function, try
2830 // to resolve the overloaded function. If all goes well, T2 is the
2831 // type of the resulting function.
2832 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2833 DeclAccessPair Found;
2834 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2835 false, Found))
2836 T2 = Fn->getType();
2837 }
2838
2839 // Compute some basic properties of the types and the initializer.
2840 bool isRValRef = DeclType->isRValueReferenceType();
2841 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002842 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002843 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002844 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002845 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2846 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002847
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002848
Sebastian Redld92badf2010-06-30 18:13:39 +00002849 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002850 // A reference to type "cv1 T1" is initialized by an expression
2851 // of type "cv2 T2" as follows:
2852
Sebastian Redld92badf2010-06-30 18:13:39 +00002853 // -- If reference is an lvalue reference and the initializer expression
2854 // The next bullet point (T1 is a function) is pretty much equivalent to this
2855 // one, so it's handled here.
2856 if (!isRValRef || T1->isFunctionType()) {
2857 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2858 // reference-compatible with "cv2 T2," or
2859 //
2860 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2861 if (InitCategory.isLValue() &&
2862 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002863 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002864 // When a parameter of reference type binds directly (8.5.3)
2865 // to an argument expression, the implicit conversion sequence
2866 // is the identity conversion, unless the argument expression
2867 // has a type that is a derived class of the parameter type,
2868 // in which case the implicit conversion sequence is a
2869 // derived-to-base Conversion (13.3.3.1).
2870 ICS.setStandard();
2871 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002872 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2873 : ObjCConversion? ICK_Compatible_Conversion
2874 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002875 ICS.Standard.Third = ICK_Identity;
2876 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2877 ICS.Standard.setToType(0, T2);
2878 ICS.Standard.setToType(1, T1);
2879 ICS.Standard.setToType(2, T1);
2880 ICS.Standard.ReferenceBinding = true;
2881 ICS.Standard.DirectBinding = true;
2882 ICS.Standard.RRefBinding = isRValRef;
2883 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002884
Sebastian Redld92badf2010-06-30 18:13:39 +00002885 // Nothing more to do: the inaccessibility/ambiguity check for
2886 // derived-to-base conversions is suppressed when we're
2887 // computing the implicit conversion sequence (C++
2888 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002889 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002890 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002891
Sebastian Redld92badf2010-06-30 18:13:39 +00002892 // -- has a class type (i.e., T2 is a class type), where T1 is
2893 // not reference-related to T2, and can be implicitly
2894 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2895 // is reference-compatible with "cv3 T3" 92) (this
2896 // conversion is selected by enumerating the applicable
2897 // conversion functions (13.3.1.6) and choosing the best
2898 // one through overload resolution (13.3)),
2899 if (!SuppressUserConversions && T2->isRecordType() &&
2900 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2901 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002902 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2903 Init, T2, /*AllowRvalues=*/false,
2904 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002905 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002906 }
2907 }
2908
Sebastian Redld92badf2010-06-30 18:13:39 +00002909 // -- Otherwise, the reference shall be an lvalue reference to a
2910 // non-volatile const type (i.e., cv1 shall be const), or the reference
2911 // shall be an rvalue reference and the initializer expression shall be
2912 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002913 //
2914 // We actually handle one oddity of C++ [over.ics.ref] at this
2915 // point, which is that, due to p2 (which short-circuits reference
2916 // binding by only attempting a simple conversion for non-direct
2917 // bindings) and p3's strange wording, we allow a const volatile
2918 // reference to bind to an rvalue. Hence the check for the presence
2919 // of "const" rather than checking for "const" being the only
2920 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002921 // This is also the point where rvalue references and lvalue inits no longer
2922 // go together.
2923 if ((!isRValRef && !T1.isConstQualified()) ||
2924 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002925 return ICS;
2926
Sebastian Redld92badf2010-06-30 18:13:39 +00002927 // -- If T1 is a function type, then
2928 // -- if T2 is the same type as T1, the reference is bound to the
2929 // initializer expression lvalue;
2930 // -- if T2 is a class type and the initializer expression can be
2931 // implicitly converted to an lvalue of type T1 [...], the
2932 // reference is bound to the function lvalue that is the result
2933 // of the conversion;
2934 // This is the same as for the lvalue case above, so it was handled there.
2935 // -- otherwise, the program is ill-formed.
2936 // This is the one difference to the lvalue case.
2937 if (T1->isFunctionType())
2938 return ICS;
2939
2940 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002941 // -- the initializer expression is an rvalue and "cv1 T1"
2942 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002943 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002944 // -- T1 is not reference-related to T2 and the initializer
2945 // expression can be implicitly converted to an rvalue
2946 // of type "cv3 T3" (this conversion is selected by
2947 // enumerating the applicable conversion functions
2948 // (13.3.1.6) and choosing the best one through overload
2949 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002950 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002951 // then the reference is bound to the initializer
2952 // expression rvalue in the first case and to the object
2953 // that is the result of the conversion in the second case
2954 // (or, in either case, to the appropriate base class
2955 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002956 if (T2->isRecordType()) {
2957 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2958 // direct binding in C++0x but not in C++03.
2959 if (InitCategory.isRValue() &&
2960 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2961 ICS.setStandard();
2962 ICS.Standard.First = ICK_Identity;
2963 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2964 : ObjCConversion? ICK_Compatible_Conversion
2965 : ICK_Identity;
2966 ICS.Standard.Third = ICK_Identity;
2967 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2968 ICS.Standard.setToType(0, T2);
2969 ICS.Standard.setToType(1, T1);
2970 ICS.Standard.setToType(2, T1);
2971 ICS.Standard.ReferenceBinding = true;
2972 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2973 ICS.Standard.RRefBinding = isRValRef;
2974 ICS.Standard.CopyConstructor = 0;
2975 return ICS;
2976 }
2977
2978 // Second case: not reference-related.
2979 if (RefRelationship == Sema::Ref_Incompatible &&
2980 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2981 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2982 Init, T2, /*AllowRvalues=*/true,
2983 AllowExplicit))
2984 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002985 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002986
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002987 // -- Otherwise, a temporary of type "cv1 T1" is created and
2988 // initialized from the initializer expression using the
2989 // rules for a non-reference copy initialization (8.5). The
2990 // reference is then bound to the temporary. If T1 is
2991 // reference-related to T2, cv1 must be the same
2992 // cv-qualification as, or greater cv-qualification than,
2993 // cv2; otherwise, the program is ill-formed.
2994 if (RefRelationship == Sema::Ref_Related) {
2995 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2996 // we would be reference-compatible or reference-compatible with
2997 // added qualification. But that wasn't the case, so the reference
2998 // initialization fails.
2999 return ICS;
3000 }
3001
3002 // If at least one of the types is a class type, the types are not
3003 // related, and we aren't allowed any user conversions, the
3004 // reference binding fails. This case is important for breaking
3005 // recursion, since TryImplicitConversion below will attempt to
3006 // create a temporary through the use of a copy constructor.
3007 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3008 (T1->isRecordType() || T2->isRecordType()))
3009 return ICS;
3010
3011 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003012 // When a parameter of reference type is not bound directly to
3013 // an argument expression, the conversion sequence is the one
3014 // required to convert the argument expression to the
3015 // underlying type of the reference according to
3016 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3017 // to copy-initializing a temporary of the underlying type with
3018 // the argument expression. Any difference in top-level
3019 // cv-qualification is subsumed by the initialization itself
3020 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003021 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3022 /*AllowExplicit=*/false,
3023 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003024
3025 // Of course, that's still a reference binding.
3026 if (ICS.isStandard()) {
3027 ICS.Standard.ReferenceBinding = true;
3028 ICS.Standard.RRefBinding = isRValRef;
3029 } else if (ICS.isUserDefined()) {
3030 ICS.UserDefined.After.ReferenceBinding = true;
3031 ICS.UserDefined.After.RRefBinding = isRValRef;
3032 }
3033 return ICS;
3034}
3035
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003036/// TryCopyInitialization - Try to copy-initialize a value of type
3037/// ToType from the expression From. Return the implicit conversion
3038/// sequence required to pass this argument, which may be a bad
3039/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003040/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003041/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003042static ImplicitConversionSequence
3043TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003044 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003045 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003046 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003047 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003048 /*FIXME:*/From->getLocStart(),
3049 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003050 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003051
John McCall5c32be02010-08-24 20:38:10 +00003052 return TryImplicitConversion(S, From, ToType,
3053 SuppressUserConversions,
3054 /*AllowExplicit=*/false,
3055 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003056}
3057
Douglas Gregor436424c2008-11-18 23:14:02 +00003058/// TryObjectArgumentInitialization - Try to initialize the object
3059/// parameter of the given member function (@c Method) from the
3060/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003061static ImplicitConversionSequence
3062TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3063 CXXMethodDecl *Method,
3064 CXXRecordDecl *ActingContext) {
3065 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003066 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3067 // const volatile object.
3068 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3069 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003070 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003071
3072 // Set up the conversion sequence as a "bad" conversion, to allow us
3073 // to exit early.
3074 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003075
3076 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003077 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003078 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003079 FromType = PT->getPointeeType();
3080
3081 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003082
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003083 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003084 // where X is the class of which the function is a member
3085 // (C++ [over.match.funcs]p4). However, when finding an implicit
3086 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003087 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003088 // (C++ [over.match.funcs]p5). We perform a simplified version of
3089 // reference binding here, that allows class rvalues to bind to
3090 // non-constant references.
3091
3092 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3093 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003094 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003095 if (ImplicitParamType.getCVRQualifiers()
3096 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003097 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003098 ICS.setBad(BadConversionSequence::bad_qualifiers,
3099 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003100 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003101 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003102
3103 // Check that we have either the same type or a derived type. It
3104 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003105 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003106 ImplicitConversionKind SecondKind;
3107 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3108 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003109 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003110 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003111 else {
John McCall65eb8792010-02-25 01:37:24 +00003112 ICS.setBad(BadConversionSequence::unrelated_class,
3113 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003114 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003115 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003116
3117 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003118 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003119 ICS.Standard.setAsIdentityConversion();
3120 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003121 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003122 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003123 ICS.Standard.ReferenceBinding = true;
3124 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003125 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003126 return ICS;
3127}
3128
3129/// PerformObjectArgumentInitialization - Perform initialization of
3130/// the implicit object parameter for the given Method with the given
3131/// expression.
3132bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003133Sema::PerformObjectArgumentInitialization(Expr *&From,
3134 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003135 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003136 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003137 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003138 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003139 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003140
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003141 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003142 FromRecordType = PT->getPointeeType();
3143 DestType = Method->getThisType(Context);
3144 } else {
3145 FromRecordType = From->getType();
3146 DestType = ImplicitParamRecordType;
3147 }
3148
John McCall6e9f8f62009-12-03 04:06:58 +00003149 // Note that we always use the true parent context when performing
3150 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003151 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003152 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003153 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003154 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003155 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003156 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003157 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003158
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003159 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003160 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003161
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003162 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003163 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003164 From->getType()->isPointerType() ?
3165 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003166 return false;
3167}
3168
Douglas Gregor5fb53972009-01-14 15:45:31 +00003169/// TryContextuallyConvertToBool - Attempt to contextually convert the
3170/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003171static ImplicitConversionSequence
3172TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003173 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003174 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003175 // FIXME: Are these flags correct?
3176 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003177 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003178 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003179}
3180
3181/// PerformContextuallyConvertToBool - Perform a contextual conversion
3182/// of the expression From to bool (C++0x [conv]p3).
3183bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003184 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003185 if (!ICS.isBad())
3186 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003187
Fariborz Jahanian76197412009-11-18 18:26:29 +00003188 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003189 return Diag(From->getSourceRange().getBegin(),
3190 diag::err_typecheck_bool_condition)
3191 << From->getType() << From->getSourceRange();
3192 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003193}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003194
3195/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3196/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003197static ImplicitConversionSequence
3198TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3199 QualType Ty = S.Context.getObjCIdType();
3200 return TryImplicitConversion(S, From, Ty,
3201 // FIXME: Are these flags correct?
3202 /*SuppressUserConversions=*/false,
3203 /*AllowExplicit=*/true,
3204 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003205}
John McCall5c32be02010-08-24 20:38:10 +00003206
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003207/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3208/// of the expression From to 'id'.
3209bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003210 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003211 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003212 if (!ICS.isBad())
3213 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3214 return true;
3215}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003216
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003217/// \brief Attempt to convert the given expression to an integral or
3218/// enumeration type.
3219///
3220/// This routine will attempt to convert an expression of class type to an
3221/// integral or enumeration type, if that class type only has a single
3222/// conversion to an integral or enumeration type.
3223///
Douglas Gregor4799d032010-06-30 00:20:43 +00003224/// \param Loc The source location of the construct that requires the
3225/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003226///
Douglas Gregor4799d032010-06-30 00:20:43 +00003227/// \param FromE The expression we're converting from.
3228///
3229/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3230/// have integral or enumeration type.
3231///
3232/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3233/// incomplete class type.
3234///
3235/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3236/// explicit conversion function (because no implicit conversion functions
3237/// were available). This is a recovery mode.
3238///
3239/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3240/// showing which conversion was picked.
3241///
3242/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3243/// conversion function that could convert to integral or enumeration type.
3244///
3245/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3246/// usable conversion function.
3247///
3248/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3249/// function, which may be an extension in this case.
3250///
3251/// \returns The expression, converted to an integral or enumeration type if
3252/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003253ExprResult
John McCallb268a282010-08-23 23:25:46 +00003254Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003255 const PartialDiagnostic &NotIntDiag,
3256 const PartialDiagnostic &IncompleteDiag,
3257 const PartialDiagnostic &ExplicitConvDiag,
3258 const PartialDiagnostic &ExplicitConvNote,
3259 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003260 const PartialDiagnostic &AmbigNote,
3261 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003262 // We can't perform any more checking for type-dependent expressions.
3263 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003264 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003265
3266 // If the expression already has integral or enumeration type, we're golden.
3267 QualType T = From->getType();
3268 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003269 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003270
3271 // FIXME: Check for missing '()' if T is a function type?
3272
3273 // If we don't have a class type in C++, there's no way we can get an
3274 // expression of integral or enumeration type.
3275 const RecordType *RecordTy = T->getAs<RecordType>();
3276 if (!RecordTy || !getLangOptions().CPlusPlus) {
3277 Diag(Loc, NotIntDiag)
3278 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003279 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003280 }
3281
3282 // We must have a complete class type.
3283 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003284 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003285
3286 // Look for a conversion to an integral or enumeration type.
3287 UnresolvedSet<4> ViableConversions;
3288 UnresolvedSet<4> ExplicitConversions;
3289 const UnresolvedSetImpl *Conversions
3290 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3291
3292 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3293 E = Conversions->end();
3294 I != E;
3295 ++I) {
3296 if (CXXConversionDecl *Conversion
3297 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3298 if (Conversion->getConversionType().getNonReferenceType()
3299 ->isIntegralOrEnumerationType()) {
3300 if (Conversion->isExplicit())
3301 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3302 else
3303 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3304 }
3305 }
3306
3307 switch (ViableConversions.size()) {
3308 case 0:
3309 if (ExplicitConversions.size() == 1) {
3310 DeclAccessPair Found = ExplicitConversions[0];
3311 CXXConversionDecl *Conversion
3312 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3313
3314 // The user probably meant to invoke the given explicit
3315 // conversion; use it.
3316 QualType ConvTy
3317 = Conversion->getConversionType().getNonReferenceType();
3318 std::string TypeStr;
3319 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3320
3321 Diag(Loc, ExplicitConvDiag)
3322 << T << ConvTy
3323 << FixItHint::CreateInsertion(From->getLocStart(),
3324 "static_cast<" + TypeStr + ">(")
3325 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3326 ")");
3327 Diag(Conversion->getLocation(), ExplicitConvNote)
3328 << ConvTy->isEnumeralType() << ConvTy;
3329
3330 // If we aren't in a SFINAE context, build a call to the
3331 // explicit conversion function.
3332 if (isSFINAEContext())
3333 return ExprError();
3334
3335 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003336 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003337 }
3338
3339 // We'll complain below about a non-integral condition type.
3340 break;
3341
3342 case 1: {
3343 // Apply this conversion.
3344 DeclAccessPair Found = ViableConversions[0];
3345 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003346
3347 CXXConversionDecl *Conversion
3348 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3349 QualType ConvTy
3350 = Conversion->getConversionType().getNonReferenceType();
3351 if (ConvDiag.getDiagID()) {
3352 if (isSFINAEContext())
3353 return ExprError();
3354
3355 Diag(Loc, ConvDiag)
3356 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3357 }
3358
John McCallb268a282010-08-23 23:25:46 +00003359 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003360 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003361 break;
3362 }
3363
3364 default:
3365 Diag(Loc, AmbigDiag)
3366 << T << From->getSourceRange();
3367 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3368 CXXConversionDecl *Conv
3369 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3370 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3371 Diag(Conv->getLocation(), AmbigNote)
3372 << ConvTy->isEnumeralType() << ConvTy;
3373 }
John McCallb268a282010-08-23 23:25:46 +00003374 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003375 }
3376
Douglas Gregor5823da32010-06-29 23:25:20 +00003377 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003378 Diag(Loc, NotIntDiag)
3379 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003380
John McCallb268a282010-08-23 23:25:46 +00003381 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003382}
3383
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003384/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003385/// candidate functions, using the given function call arguments. If
3386/// @p SuppressUserConversions, then don't allow user-defined
3387/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003388///
3389/// \para PartialOverloading true if we are performing "partial" overloading
3390/// based on an incomplete set of function arguments. This feature is used by
3391/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003392void
3393Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003394 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003395 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003396 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003397 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003398 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003399 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003400 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003401 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003402 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003403 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003404
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003405 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003406 if (!isa<CXXConstructorDecl>(Method)) {
3407 // If we get here, it's because we're calling a member function
3408 // that is named without a member access expression (e.g.,
3409 // "this->f") that was either written explicitly or created
3410 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003411 // function, e.g., X::f(). We use an empty type for the implied
3412 // object argument (C++ [over.call.func]p3), and the acting context
3413 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003414 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003415 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003416 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003417 return;
3418 }
3419 // We treat a constructor like a non-member function, since its object
3420 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003421 }
3422
Douglas Gregorff7028a2009-11-13 23:59:09 +00003423 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003424 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003425
Douglas Gregor27381f32009-11-23 12:27:39 +00003426 // Overload resolution is always an unevaluated context.
3427 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3428
Douglas Gregorffe14e32009-11-14 01:20:54 +00003429 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3430 // C++ [class.copy]p3:
3431 // A member function template is never instantiated to perform the copy
3432 // of a class object to an object of its class type.
3433 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3434 if (NumArgs == 1 &&
3435 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003436 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3437 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003438 return;
3439 }
3440
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003441 // Add this candidate
3442 CandidateSet.push_back(OverloadCandidate());
3443 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003444 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003445 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003446 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003447 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003448 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003449
3450 unsigned NumArgsInProto = Proto->getNumArgs();
3451
3452 // (C++ 13.3.2p2): A candidate function having fewer than m
3453 // parameters is viable only if it has an ellipsis in its parameter
3454 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003455 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3456 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003457 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003458 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003459 return;
3460 }
3461
3462 // (C++ 13.3.2p2): A candidate function having more than m parameters
3463 // is viable only if the (m+1)st parameter has a default argument
3464 // (8.3.6). For the purposes of overload resolution, the
3465 // parameter list is truncated on the right, so that there are
3466 // exactly m parameters.
3467 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003468 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003469 // Not enough arguments.
3470 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003471 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003472 return;
3473 }
3474
3475 // Determine the implicit conversion sequences for each of the
3476 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003477 Candidate.Conversions.resize(NumArgs);
3478 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3479 if (ArgIdx < NumArgsInProto) {
3480 // (C++ 13.3.2p3): for F to be a viable function, there shall
3481 // exist for each argument an implicit conversion sequence
3482 // (13.3.3.1) that converts that argument to the corresponding
3483 // parameter of F.
3484 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003485 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003486 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003487 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003488 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003489 if (Candidate.Conversions[ArgIdx].isBad()) {
3490 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003491 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003492 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003493 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003494 } else {
3495 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3496 // argument for which there is no corresponding parameter is
3497 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003498 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003499 }
3500 }
3501}
3502
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003503/// \brief Add all of the function declarations in the given function set to
3504/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003505void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003506 Expr **Args, unsigned NumArgs,
3507 OverloadCandidateSet& CandidateSet,
3508 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003509 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003510 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3511 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003512 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003513 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003514 cast<CXXMethodDecl>(FD)->getParent(),
3515 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003516 CandidateSet, SuppressUserConversions);
3517 else
John McCalla0296f72010-03-19 07:35:19 +00003518 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003519 SuppressUserConversions);
3520 } else {
John McCalla0296f72010-03-19 07:35:19 +00003521 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003522 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3523 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003524 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003525 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003526 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003527 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003528 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003529 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003530 else
John McCalla0296f72010-03-19 07:35:19 +00003531 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003532 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003533 Args, NumArgs, CandidateSet,
3534 SuppressUserConversions);
3535 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003536 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003537}
3538
John McCallf0f1cf02009-11-17 07:50:12 +00003539/// AddMethodCandidate - Adds a named decl (which is some kind of
3540/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003541void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003542 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003543 Expr **Args, unsigned NumArgs,
3544 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003545 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003546 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003547 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003548
3549 if (isa<UsingShadowDecl>(Decl))
3550 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3551
3552 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3553 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3554 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003555 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3556 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003557 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003558 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003559 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003560 } else {
John McCalla0296f72010-03-19 07:35:19 +00003561 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003562 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003563 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003564 }
3565}
3566
Douglas Gregor436424c2008-11-18 23:14:02 +00003567/// AddMethodCandidate - Adds the given C++ member function to the set
3568/// of candidate functions, using the given function call arguments
3569/// and the object argument (@c Object). For example, in a call
3570/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3571/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3572/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003573/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003574void
John McCalla0296f72010-03-19 07:35:19 +00003575Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003576 CXXRecordDecl *ActingContext, QualType ObjectType,
3577 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003578 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003579 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003580 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003581 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003582 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003583 assert(!isa<CXXConstructorDecl>(Method) &&
3584 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003585
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003586 if (!CandidateSet.isNewCandidate(Method))
3587 return;
3588
Douglas Gregor27381f32009-11-23 12:27:39 +00003589 // Overload resolution is always an unevaluated context.
3590 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3591
Douglas Gregor436424c2008-11-18 23:14:02 +00003592 // Add this candidate
3593 CandidateSet.push_back(OverloadCandidate());
3594 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003595 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003596 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003597 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003598 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003599
3600 unsigned NumArgsInProto = Proto->getNumArgs();
3601
3602 // (C++ 13.3.2p2): A candidate function having fewer than m
3603 // parameters is viable only if it has an ellipsis in its parameter
3604 // list (8.3.5).
3605 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003607 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003608 return;
3609 }
3610
3611 // (C++ 13.3.2p2): A candidate function having more than m parameters
3612 // is viable only if the (m+1)st parameter has a default argument
3613 // (8.3.6). For the purposes of overload resolution, the
3614 // parameter list is truncated on the right, so that there are
3615 // exactly m parameters.
3616 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3617 if (NumArgs < MinRequiredArgs) {
3618 // Not enough arguments.
3619 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003620 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003621 return;
3622 }
3623
3624 Candidate.Viable = true;
3625 Candidate.Conversions.resize(NumArgs + 1);
3626
John McCall6e9f8f62009-12-03 04:06:58 +00003627 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003628 // The implicit object argument is ignored.
3629 Candidate.IgnoreObjectArgument = true;
3630 else {
3631 // Determine the implicit conversion sequence for the object
3632 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003633 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003634 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3635 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003636 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003637 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003638 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003639 return;
3640 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003641 }
3642
3643 // Determine the implicit conversion sequences for each of the
3644 // arguments.
3645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3646 if (ArgIdx < NumArgsInProto) {
3647 // (C++ 13.3.2p3): for F to be a viable function, there shall
3648 // exist for each argument an implicit conversion sequence
3649 // (13.3.3.1) that converts that argument to the corresponding
3650 // parameter of F.
3651 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003652 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003653 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003654 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003655 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003656 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003657 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003658 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003659 break;
3660 }
3661 } else {
3662 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3663 // argument for which there is no corresponding parameter is
3664 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003665 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003666 }
3667 }
3668}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003669
Douglas Gregor97628d62009-08-21 00:16:32 +00003670/// \brief Add a C++ member function template as a candidate to the candidate
3671/// set, using template argument deduction to produce an appropriate member
3672/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003673void
Douglas Gregor97628d62009-08-21 00:16:32 +00003674Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003675 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003676 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003677 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003678 QualType ObjectType,
3679 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003680 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003681 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003682 if (!CandidateSet.isNewCandidate(MethodTmpl))
3683 return;
3684
Douglas Gregor97628d62009-08-21 00:16:32 +00003685 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003686 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003687 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003688 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003689 // candidate functions in the usual way.113) A given name can refer to one
3690 // or more function templates and also to a set of overloaded non-template
3691 // functions. In such a case, the candidate functions generated from each
3692 // function template are combined with the set of non-template candidate
3693 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003694 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003695 FunctionDecl *Specialization = 0;
3696 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003697 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003698 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003699 CandidateSet.push_back(OverloadCandidate());
3700 OverloadCandidate &Candidate = CandidateSet.back();
3701 Candidate.FoundDecl = FoundDecl;
3702 Candidate.Function = MethodTmpl->getTemplatedDecl();
3703 Candidate.Viable = false;
3704 Candidate.FailureKind = ovl_fail_bad_deduction;
3705 Candidate.IsSurrogate = false;
3706 Candidate.IgnoreObjectArgument = false;
3707 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3708 Info);
3709 return;
3710 }
Mike Stump11289f42009-09-09 15:08:12 +00003711
Douglas Gregor97628d62009-08-21 00:16:32 +00003712 // Add the function template specialization produced by template argument
3713 // deduction as a candidate.
3714 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003715 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003716 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003717 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003718 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003719 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003720}
3721
Douglas Gregor05155d82009-08-21 23:19:43 +00003722/// \brief Add a C++ function template specialization as a candidate
3723/// in the candidate set, using template argument deduction to produce
3724/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003725void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003726Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003727 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003728 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003729 Expr **Args, unsigned NumArgs,
3730 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003731 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003732 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3733 return;
3734
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003735 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003736 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003737 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003738 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003739 // candidate functions in the usual way.113) A given name can refer to one
3740 // or more function templates and also to a set of overloaded non-template
3741 // functions. In such a case, the candidate functions generated from each
3742 // function template are combined with the set of non-template candidate
3743 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003744 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003745 FunctionDecl *Specialization = 0;
3746 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003747 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003748 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003749 CandidateSet.push_back(OverloadCandidate());
3750 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003751 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003752 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3753 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003754 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003755 Candidate.IsSurrogate = false;
3756 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003757 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3758 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003759 return;
3760 }
Mike Stump11289f42009-09-09 15:08:12 +00003761
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003762 // Add the function template specialization produced by template argument
3763 // deduction as a candidate.
3764 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003765 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003766 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003767}
Mike Stump11289f42009-09-09 15:08:12 +00003768
Douglas Gregora1f013e2008-11-07 22:36:19 +00003769/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003770/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003771/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003772/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003773/// (which may or may not be the same type as the type that the
3774/// conversion function produces).
3775void
3776Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003777 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003778 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003779 Expr *From, QualType ToType,
3780 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003781 assert(!Conversion->getDescribedFunctionTemplate() &&
3782 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003783 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003784 if (!CandidateSet.isNewCandidate(Conversion))
3785 return;
3786
Douglas Gregor27381f32009-11-23 12:27:39 +00003787 // Overload resolution is always an unevaluated context.
3788 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3789
Douglas Gregora1f013e2008-11-07 22:36:19 +00003790 // Add this candidate
3791 CandidateSet.push_back(OverloadCandidate());
3792 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003793 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003794 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003795 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003796 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003797 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003798 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003799 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003800 Candidate.Viable = true;
3801 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003802
Douglas Gregor6affc782010-08-19 15:37:02 +00003803 // C++ [over.match.funcs]p4:
3804 // For conversion functions, the function is considered to be a member of
3805 // the class of the implicit implied object argument for the purpose of
3806 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003807 //
3808 // Determine the implicit conversion sequence for the implicit
3809 // object parameter.
3810 QualType ImplicitParamType = From->getType();
3811 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3812 ImplicitParamType = FromPtrType->getPointeeType();
3813 CXXRecordDecl *ConversionContext
3814 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3815
3816 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003817 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003818 ConversionContext);
3819
John McCall0d1da222010-01-12 00:44:57 +00003820 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003821 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003822 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003823 return;
3824 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003825
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003826 // We won't go through a user-define type conversion function to convert a
3827 // derived to base as such conversions are given Conversion Rank. They only
3828 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3829 QualType FromCanon
3830 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3831 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3832 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3833 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003834 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003835 return;
3836 }
3837
Douglas Gregora1f013e2008-11-07 22:36:19 +00003838 // To determine what the conversion from the result of calling the
3839 // conversion function to the type we're eventually trying to
3840 // convert to (ToType), we need to synthesize a call to the
3841 // conversion function and attempt copy initialization from it. This
3842 // makes sure that we get the right semantics with respect to
3843 // lvalues/rvalues and the type. Fortunately, we can allocate this
3844 // call on the stack and we don't need its arguments to be
3845 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003846 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003847 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003848 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3849 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003850 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003851 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003852
3853 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003854 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3855 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003856 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003857 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003858 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003859 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003860 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003861 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003862 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003863
John McCall0d1da222010-01-12 00:44:57 +00003864 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003865 case ImplicitConversionSequence::StandardConversion:
3866 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003867
3868 // C++ [over.ics.user]p3:
3869 // If the user-defined conversion is specified by a specialization of a
3870 // conversion function template, the second standard conversion sequence
3871 // shall have exact match rank.
3872 if (Conversion->getPrimaryTemplate() &&
3873 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3874 Candidate.Viable = false;
3875 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3876 }
3877
Douglas Gregora1f013e2008-11-07 22:36:19 +00003878 break;
3879
3880 case ImplicitConversionSequence::BadConversion:
3881 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003882 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003883 break;
3884
3885 default:
Mike Stump11289f42009-09-09 15:08:12 +00003886 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003887 "Can only end up with a standard conversion sequence or failure");
3888 }
3889}
3890
Douglas Gregor05155d82009-08-21 23:19:43 +00003891/// \brief Adds a conversion function template specialization
3892/// candidate to the overload set, using template argument deduction
3893/// to deduce the template arguments of the conversion function
3894/// template from the type that we are converting to (C++
3895/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003896void
Douglas Gregor05155d82009-08-21 23:19:43 +00003897Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003898 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003899 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003900 Expr *From, QualType ToType,
3901 OverloadCandidateSet &CandidateSet) {
3902 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3903 "Only conversion function templates permitted here");
3904
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003905 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3906 return;
3907
John McCallbc077cf2010-02-08 23:07:23 +00003908 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003909 CXXConversionDecl *Specialization = 0;
3910 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003911 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003912 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003913 CandidateSet.push_back(OverloadCandidate());
3914 OverloadCandidate &Candidate = CandidateSet.back();
3915 Candidate.FoundDecl = FoundDecl;
3916 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3917 Candidate.Viable = false;
3918 Candidate.FailureKind = ovl_fail_bad_deduction;
3919 Candidate.IsSurrogate = false;
3920 Candidate.IgnoreObjectArgument = false;
3921 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3922 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003923 return;
3924 }
Mike Stump11289f42009-09-09 15:08:12 +00003925
Douglas Gregor05155d82009-08-21 23:19:43 +00003926 // Add the conversion function template specialization produced by
3927 // template argument deduction as a candidate.
3928 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003929 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003930 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003931}
3932
Douglas Gregorab7897a2008-11-19 22:57:39 +00003933/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3934/// converts the given @c Object to a function pointer via the
3935/// conversion function @c Conversion, and then attempts to call it
3936/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3937/// the type of function that we'll eventually be calling.
3938void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003939 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003940 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003941 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003942 QualType ObjectType,
3943 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003944 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003945 if (!CandidateSet.isNewCandidate(Conversion))
3946 return;
3947
Douglas Gregor27381f32009-11-23 12:27:39 +00003948 // Overload resolution is always an unevaluated context.
3949 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3950
Douglas Gregorab7897a2008-11-19 22:57:39 +00003951 CandidateSet.push_back(OverloadCandidate());
3952 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003953 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003954 Candidate.Function = 0;
3955 Candidate.Surrogate = Conversion;
3956 Candidate.Viable = true;
3957 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003958 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003959 Candidate.Conversions.resize(NumArgs + 1);
3960
3961 // Determine the implicit conversion sequence for the implicit
3962 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003963 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00003964 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3965 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003966 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003967 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003968 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003969 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003970 return;
3971 }
3972
3973 // The first conversion is actually a user-defined conversion whose
3974 // first conversion is ObjectInit's standard conversion (which is
3975 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003976 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003977 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003978 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003979 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003980 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003981 = Candidate.Conversions[0].UserDefined.Before;
3982 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3983
Mike Stump11289f42009-09-09 15:08:12 +00003984 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003985 unsigned NumArgsInProto = Proto->getNumArgs();
3986
3987 // (C++ 13.3.2p2): A candidate function having fewer than m
3988 // parameters is viable only if it has an ellipsis in its parameter
3989 // list (8.3.5).
3990 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3991 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003992 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003993 return;
3994 }
3995
3996 // Function types don't have any default arguments, so just check if
3997 // we have enough arguments.
3998 if (NumArgs < NumArgsInProto) {
3999 // Not enough arguments.
4000 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004001 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004002 return;
4003 }
4004
4005 // Determine the implicit conversion sequences for each of the
4006 // arguments.
4007 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4008 if (ArgIdx < NumArgsInProto) {
4009 // (C++ 13.3.2p3): for F to be a viable function, there shall
4010 // exist for each argument an implicit conversion sequence
4011 // (13.3.3.1) that converts that argument to the corresponding
4012 // parameter of F.
4013 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004014 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004015 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004016 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004017 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004018 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004019 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004020 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004021 break;
4022 }
4023 } else {
4024 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4025 // argument for which there is no corresponding parameter is
4026 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004027 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004028 }
4029 }
4030}
4031
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004032/// \brief Add overload candidates for overloaded operators that are
4033/// member functions.
4034///
4035/// Add the overloaded operator candidates that are member functions
4036/// for the operator Op that was used in an operator expression such
4037/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4038/// CandidateSet will store the added overload candidates. (C++
4039/// [over.match.oper]).
4040void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4041 SourceLocation OpLoc,
4042 Expr **Args, unsigned NumArgs,
4043 OverloadCandidateSet& CandidateSet,
4044 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004045 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4046
4047 // C++ [over.match.oper]p3:
4048 // For a unary operator @ with an operand of a type whose
4049 // cv-unqualified version is T1, and for a binary operator @ with
4050 // a left operand of a type whose cv-unqualified version is T1 and
4051 // a right operand of a type whose cv-unqualified version is T2,
4052 // three sets of candidate functions, designated member
4053 // candidates, non-member candidates and built-in candidates, are
4054 // constructed as follows:
4055 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004056
4057 // -- If T1 is a class type, the set of member candidates is the
4058 // result of the qualified lookup of T1::operator@
4059 // (13.3.1.1.1); otherwise, the set of member candidates is
4060 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004061 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004062 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004063 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004064 return;
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCall27b18f82009-11-17 02:14:36 +00004066 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4067 LookupQualifiedName(Operators, T1Rec->getDecl());
4068 Operators.suppressDiagnostics();
4069
Mike Stump11289f42009-09-09 15:08:12 +00004070 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004071 OperEnd = Operators.end();
4072 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004073 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004074 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004075 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004076 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004077 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004078}
4079
Douglas Gregora11693b2008-11-12 17:17:38 +00004080/// AddBuiltinCandidate - Add a candidate for a built-in
4081/// operator. ResultTy and ParamTys are the result and parameter types
4082/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004083/// arguments being passed to the candidate. IsAssignmentOperator
4084/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004085/// operator. NumContextualBoolArguments is the number of arguments
4086/// (at the beginning of the argument list) that will be contextually
4087/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004088void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004089 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004090 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004091 bool IsAssignmentOperator,
4092 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004093 // Overload resolution is always an unevaluated context.
4094 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4095
Douglas Gregora11693b2008-11-12 17:17:38 +00004096 // Add this candidate
4097 CandidateSet.push_back(OverloadCandidate());
4098 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004099 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004100 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004101 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004102 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004103 Candidate.BuiltinTypes.ResultTy = ResultTy;
4104 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4105 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4106
4107 // Determine the implicit conversion sequences for each of the
4108 // arguments.
4109 Candidate.Viable = true;
4110 Candidate.Conversions.resize(NumArgs);
4111 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004112 // C++ [over.match.oper]p4:
4113 // For the built-in assignment operators, conversions of the
4114 // left operand are restricted as follows:
4115 // -- no temporaries are introduced to hold the left operand, and
4116 // -- no user-defined conversions are applied to the left
4117 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004118 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004119 //
4120 // We block these conversions by turning off user-defined
4121 // conversions, since that is the only way that initialization of
4122 // a reference to a non-class type can occur from something that
4123 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004124 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004125 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004126 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004127 Candidate.Conversions[ArgIdx]
4128 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004129 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004130 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004131 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004132 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004133 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004134 }
John McCall0d1da222010-01-12 00:44:57 +00004135 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004136 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004137 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004138 break;
4139 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004140 }
4141}
4142
4143/// BuiltinCandidateTypeSet - A set of types that will be used for the
4144/// candidate operator functions for built-in operators (C++
4145/// [over.built]). The types are separated into pointer types and
4146/// enumeration types.
4147class BuiltinCandidateTypeSet {
4148 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004149 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004150
4151 /// PointerTypes - The set of pointer types that will be used in the
4152 /// built-in candidates.
4153 TypeSet PointerTypes;
4154
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004155 /// MemberPointerTypes - The set of member pointer types that will be
4156 /// used in the built-in candidates.
4157 TypeSet MemberPointerTypes;
4158
Douglas Gregora11693b2008-11-12 17:17:38 +00004159 /// EnumerationTypes - The set of enumeration types that will be
4160 /// used in the built-in candidates.
4161 TypeSet EnumerationTypes;
4162
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004163 /// \brief The set of vector types that will be used in the built-in
4164 /// candidates.
4165 TypeSet VectorTypes;
4166
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004167 /// Sema - The semantic analysis instance where we are building the
4168 /// candidate type set.
4169 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004170
Douglas Gregora11693b2008-11-12 17:17:38 +00004171 /// Context - The AST context in which we will build the type sets.
4172 ASTContext &Context;
4173
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004174 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4175 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004176 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004177
4178public:
4179 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004180 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004181
Mike Stump11289f42009-09-09 15:08:12 +00004182 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004183 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004184
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004185 void AddTypesConvertedFrom(QualType Ty,
4186 SourceLocation Loc,
4187 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004188 bool AllowExplicitConversions,
4189 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004190
4191 /// pointer_begin - First pointer type found;
4192 iterator pointer_begin() { return PointerTypes.begin(); }
4193
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004194 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004195 iterator pointer_end() { return PointerTypes.end(); }
4196
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004197 /// member_pointer_begin - First member pointer type found;
4198 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4199
4200 /// member_pointer_end - Past the last member pointer type found;
4201 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4202
Douglas Gregora11693b2008-11-12 17:17:38 +00004203 /// enumeration_begin - First enumeration type found;
4204 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4205
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004206 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004207 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004208
4209 iterator vector_begin() { return VectorTypes.begin(); }
4210 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004211};
4212
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004213/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004214/// the set of pointer types along with any more-qualified variants of
4215/// that type. For example, if @p Ty is "int const *", this routine
4216/// will add "int const *", "int const volatile *", "int const
4217/// restrict *", and "int const volatile restrict *" to the set of
4218/// pointer types. Returns true if the add of @p Ty itself succeeded,
4219/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004220///
4221/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004222bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004223BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4224 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004225
Douglas Gregora11693b2008-11-12 17:17:38 +00004226 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004227 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004228 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004229
4230 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004231 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004232 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004233 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004234 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004235 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004236 buildObjCPtr = true;
4237 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004238 else
4239 assert(false && "type was not a pointer type!");
4240 }
4241 else
4242 PointeeTy = PointerTy->getPointeeType();
4243
Sebastian Redl4990a632009-11-18 20:39:26 +00004244 // Don't add qualified variants of arrays. For one, they're not allowed
4245 // (the qualifier would sink to the element type), and for another, the
4246 // only overload situation where it matters is subscript or pointer +- int,
4247 // and those shouldn't have qualifier variants anyway.
4248 if (PointeeTy->isArrayType())
4249 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004250 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004251 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004252 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004253 bool hasVolatile = VisibleQuals.hasVolatile();
4254 bool hasRestrict = VisibleQuals.hasRestrict();
4255
John McCall8ccfcb52009-09-24 19:53:00 +00004256 // Iterate through all strict supersets of BaseCVR.
4257 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4258 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004259 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4260 // in the types.
4261 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4262 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004263 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004264 if (!buildObjCPtr)
4265 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4266 else
4267 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004268 }
4269
4270 return true;
4271}
4272
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004273/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4274/// to the set of pointer types along with any more-qualified variants of
4275/// that type. For example, if @p Ty is "int const *", this routine
4276/// will add "int const *", "int const volatile *", "int const
4277/// restrict *", and "int const volatile restrict *" to the set of
4278/// pointer types. Returns true if the add of @p Ty itself succeeded,
4279/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004280///
4281/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004282bool
4283BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4284 QualType Ty) {
4285 // Insert this type.
4286 if (!MemberPointerTypes.insert(Ty))
4287 return false;
4288
John McCall8ccfcb52009-09-24 19:53:00 +00004289 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4290 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004291
John McCall8ccfcb52009-09-24 19:53:00 +00004292 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004293 // Don't add qualified variants of arrays. For one, they're not allowed
4294 // (the qualifier would sink to the element type), and for another, the
4295 // only overload situation where it matters is subscript or pointer +- int,
4296 // and those shouldn't have qualifier variants anyway.
4297 if (PointeeTy->isArrayType())
4298 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004299 const Type *ClassTy = PointerTy->getClass();
4300
4301 // Iterate through all strict supersets of the pointee type's CVR
4302 // qualifiers.
4303 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4304 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4305 if ((CVR | BaseCVR) != CVR) continue;
4306
4307 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4308 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004309 }
4310
4311 return true;
4312}
4313
Douglas Gregora11693b2008-11-12 17:17:38 +00004314/// AddTypesConvertedFrom - Add each of the types to which the type @p
4315/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004316/// primarily interested in pointer types and enumeration types. We also
4317/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004318/// AllowUserConversions is true if we should look at the conversion
4319/// functions of a class type, and AllowExplicitConversions if we
4320/// should also include the explicit conversion functions of a class
4321/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004322void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004323BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004324 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004325 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004326 bool AllowExplicitConversions,
4327 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004328 // Only deal with canonical types.
4329 Ty = Context.getCanonicalType(Ty);
4330
4331 // Look through reference types; they aren't part of the type of an
4332 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004333 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004334 Ty = RefTy->getPointeeType();
4335
4336 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004337 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004338
Sebastian Redl65ae2002009-11-05 16:36:20 +00004339 // If we're dealing with an array type, decay to the pointer.
4340 if (Ty->isArrayType())
4341 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004342 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4343 PointerTypes.insert(Ty);
4344 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004345 // Insert our type, and its more-qualified variants, into the set
4346 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004347 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004348 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004349 } else if (Ty->isMemberPointerType()) {
4350 // Member pointers are far easier, since the pointee can't be converted.
4351 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4352 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004353 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004354 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004355 } else if (Ty->isVectorType()) {
4356 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004357 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004358 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004359 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004360 // No conversion functions in incomplete types.
4361 return;
4362 }
Mike Stump11289f42009-09-09 15:08:12 +00004363
Douglas Gregora11693b2008-11-12 17:17:38 +00004364 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004365 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004366 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004367 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004368 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004369 NamedDecl *D = I.getDecl();
4370 if (isa<UsingShadowDecl>(D))
4371 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004372
Mike Stump11289f42009-09-09 15:08:12 +00004373 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004374 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004375 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004376 continue;
4377
John McCallda4458e2010-03-31 01:36:47 +00004378 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004379 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004380 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004381 VisibleQuals);
4382 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004383 }
4384 }
4385 }
4386}
4387
Douglas Gregor84605ae2009-08-24 13:43:27 +00004388/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4389/// the volatile- and non-volatile-qualified assignment operators for the
4390/// given type to the candidate set.
4391static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4392 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004393 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004394 unsigned NumArgs,
4395 OverloadCandidateSet &CandidateSet) {
4396 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004397
Douglas Gregor84605ae2009-08-24 13:43:27 +00004398 // T& operator=(T&, T)
4399 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4400 ParamTypes[1] = T;
4401 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4402 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004403
Douglas Gregor84605ae2009-08-24 13:43:27 +00004404 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4405 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004406 ParamTypes[0]
4407 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004408 ParamTypes[1] = T;
4409 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004410 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004411 }
4412}
Mike Stump11289f42009-09-09 15:08:12 +00004413
Sebastian Redl1054fae2009-10-25 17:03:50 +00004414/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4415/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004416static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4417 Qualifiers VRQuals;
4418 const RecordType *TyRec;
4419 if (const MemberPointerType *RHSMPType =
4420 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004421 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004422 else
4423 TyRec = ArgExpr->getType()->getAs<RecordType>();
4424 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004425 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004426 VRQuals.addVolatile();
4427 VRQuals.addRestrict();
4428 return VRQuals;
4429 }
4430
4431 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004432 if (!ClassDecl->hasDefinition())
4433 return VRQuals;
4434
John McCallad371252010-01-20 00:46:10 +00004435 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004436 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004437
John McCallad371252010-01-20 00:46:10 +00004438 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004439 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004440 NamedDecl *D = I.getDecl();
4441 if (isa<UsingShadowDecl>(D))
4442 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4443 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004444 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4445 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4446 CanTy = ResTypeRef->getPointeeType();
4447 // Need to go down the pointer/mempointer chain and add qualifiers
4448 // as see them.
4449 bool done = false;
4450 while (!done) {
4451 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4452 CanTy = ResTypePtr->getPointeeType();
4453 else if (const MemberPointerType *ResTypeMPtr =
4454 CanTy->getAs<MemberPointerType>())
4455 CanTy = ResTypeMPtr->getPointeeType();
4456 else
4457 done = true;
4458 if (CanTy.isVolatileQualified())
4459 VRQuals.addVolatile();
4460 if (CanTy.isRestrictQualified())
4461 VRQuals.addRestrict();
4462 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4463 return VRQuals;
4464 }
4465 }
4466 }
4467 return VRQuals;
4468}
4469
Douglas Gregord08452f2008-11-19 15:42:04 +00004470/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4471/// operator overloads to the candidate set (C++ [over.built]), based
4472/// on the operator @p Op and the arguments given. For example, if the
4473/// operator is a binary '+', this routine might add "int
4474/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004475void
Mike Stump11289f42009-09-09 15:08:12 +00004476Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004477 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004478 Expr **Args, unsigned NumArgs,
4479 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004480 // The set of "promoted arithmetic types", which are the arithmetic
4481 // types are that preserved by promotion (C++ [over.built]p2). Note
4482 // that the first few of these types are the promoted integral
4483 // types; these types need to be first.
4484 // FIXME: What about complex?
4485 const unsigned FirstIntegralType = 0;
4486 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004487 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004488 LastPromotedIntegralType = 13;
4489 const unsigned FirstPromotedArithmeticType = 7,
4490 LastPromotedArithmeticType = 16;
4491 const unsigned NumArithmeticTypes = 16;
4492 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004493 Context.BoolTy, Context.CharTy, Context.WCharTy,
4494// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004495 Context.SignedCharTy, Context.ShortTy,
4496 Context.UnsignedCharTy, Context.UnsignedShortTy,
4497 Context.IntTy, Context.LongTy, Context.LongLongTy,
4498 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4499 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4500 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004501 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4502 "Invalid first promoted integral type");
4503 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4504 == Context.UnsignedLongLongTy &&
4505 "Invalid last promoted integral type");
4506 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4507 "Invalid first promoted arithmetic type");
4508 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4509 == Context.LongDoubleTy &&
4510 "Invalid last promoted arithmetic type");
4511
Douglas Gregora11693b2008-11-12 17:17:38 +00004512 // Find all of the types that the arguments can convert to, but only
4513 // if the operator we're looking at has built-in operator candidates
4514 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004515 Qualifiers VisibleTypeConversionsQuals;
4516 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004517 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4518 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4519
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004520 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004521 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4522 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4523 OpLoc,
4524 true,
4525 (Op == OO_Exclaim ||
4526 Op == OO_AmpAmp ||
4527 Op == OO_PipePipe),
4528 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004529
4530 bool isComparison = false;
4531 switch (Op) {
4532 case OO_None:
4533 case NUM_OVERLOADED_OPERATORS:
4534 assert(false && "Expected an overloaded operator");
4535 break;
4536
Douglas Gregord08452f2008-11-19 15:42:04 +00004537 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004538 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004539 goto UnaryStar;
4540 else
4541 goto BinaryStar;
4542 break;
4543
4544 case OO_Plus: // '+' is either unary or binary
4545 if (NumArgs == 1)
4546 goto UnaryPlus;
4547 else
4548 goto BinaryPlus;
4549 break;
4550
4551 case OO_Minus: // '-' is either unary or binary
4552 if (NumArgs == 1)
4553 goto UnaryMinus;
4554 else
4555 goto BinaryMinus;
4556 break;
4557
4558 case OO_Amp: // '&' is either unary or binary
4559 if (NumArgs == 1)
4560 goto UnaryAmp;
4561 else
4562 goto BinaryAmp;
4563
4564 case OO_PlusPlus:
4565 case OO_MinusMinus:
4566 // C++ [over.built]p3:
4567 //
4568 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4569 // is either volatile or empty, there exist candidate operator
4570 // functions of the form
4571 //
4572 // VQ T& operator++(VQ T&);
4573 // T operator++(VQ T&, int);
4574 //
4575 // C++ [over.built]p4:
4576 //
4577 // For every pair (T, VQ), where T is an arithmetic type other
4578 // than bool, and VQ is either volatile or empty, there exist
4579 // candidate operator functions of the form
4580 //
4581 // VQ T& operator--(VQ T&);
4582 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004583 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004584 Arith < NumArithmeticTypes; ++Arith) {
4585 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004586 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004587 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004588
4589 // Non-volatile version.
4590 if (NumArgs == 1)
4591 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4592 else
4593 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004594 // heuristic to reduce number of builtin candidates in the set.
4595 // Add volatile version only if there are conversions to a volatile type.
4596 if (VisibleTypeConversionsQuals.hasVolatile()) {
4597 // Volatile version
4598 ParamTypes[0]
4599 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4600 if (NumArgs == 1)
4601 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4602 else
4603 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4604 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004605 }
4606
4607 // C++ [over.built]p5:
4608 //
4609 // For every pair (T, VQ), where T is a cv-qualified or
4610 // cv-unqualified object type, and VQ is either volatile or
4611 // empty, there exist candidate operator functions of the form
4612 //
4613 // T*VQ& operator++(T*VQ&);
4614 // T*VQ& operator--(T*VQ&);
4615 // T* operator++(T*VQ&, int);
4616 // T* operator--(T*VQ&, int);
4617 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4618 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4619 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004620 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004621 continue;
4622
Mike Stump11289f42009-09-09 15:08:12 +00004623 QualType ParamTypes[2] = {
4624 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004625 };
Mike Stump11289f42009-09-09 15:08:12 +00004626
Douglas Gregord08452f2008-11-19 15:42:04 +00004627 // Without volatile
4628 if (NumArgs == 1)
4629 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4630 else
4631 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4632
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004633 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4634 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004635 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004636 ParamTypes[0]
4637 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004638 if (NumArgs == 1)
4639 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4640 else
4641 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4642 }
4643 }
4644 break;
4645
4646 UnaryStar:
4647 // C++ [over.built]p6:
4648 // For every cv-qualified or cv-unqualified object type T, there
4649 // exist candidate operator functions of the form
4650 //
4651 // T& operator*(T*);
4652 //
4653 // C++ [over.built]p7:
4654 // For every function type T, there exist candidate operator
4655 // functions of the form
4656 // T& operator*(T*);
4657 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4658 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4659 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004660 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004661 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004662 &ParamTy, Args, 1, CandidateSet);
4663 }
4664 break;
4665
4666 UnaryPlus:
4667 // C++ [over.built]p8:
4668 // For every type T, there exist candidate operator functions of
4669 // the form
4670 //
4671 // T* operator+(T*);
4672 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4673 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4674 QualType ParamTy = *Ptr;
4675 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4676 }
Mike Stump11289f42009-09-09 15:08:12 +00004677
Douglas Gregord08452f2008-11-19 15:42:04 +00004678 // Fall through
4679
4680 UnaryMinus:
4681 // C++ [over.built]p9:
4682 // For every promoted arithmetic type T, there exist candidate
4683 // operator functions of the form
4684 //
4685 // T operator+(T);
4686 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004687 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004688 Arith < LastPromotedArithmeticType; ++Arith) {
4689 QualType ArithTy = ArithmeticTypes[Arith];
4690 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4691 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004692
4693 // Extension: We also add these operators for vector types.
4694 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4695 VecEnd = CandidateTypes.vector_end();
4696 Vec != VecEnd; ++Vec) {
4697 QualType VecTy = *Vec;
4698 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4699 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004700 break;
4701
4702 case OO_Tilde:
4703 // C++ [over.built]p10:
4704 // For every promoted integral type T, there exist candidate
4705 // operator functions of the form
4706 //
4707 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004708 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004709 Int < LastPromotedIntegralType; ++Int) {
4710 QualType IntTy = ArithmeticTypes[Int];
4711 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4712 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004713
4714 // Extension: We also add this operator for vector types.
4715 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4716 VecEnd = CandidateTypes.vector_end();
4717 Vec != VecEnd; ++Vec) {
4718 QualType VecTy = *Vec;
4719 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4720 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004721 break;
4722
Douglas Gregora11693b2008-11-12 17:17:38 +00004723 case OO_New:
4724 case OO_Delete:
4725 case OO_Array_New:
4726 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004727 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004728 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004729 break;
4730
4731 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004732 UnaryAmp:
4733 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004734 // C++ [over.match.oper]p3:
4735 // -- For the operator ',', the unary operator '&', or the
4736 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004737 break;
4738
Douglas Gregor84605ae2009-08-24 13:43:27 +00004739 case OO_EqualEqual:
4740 case OO_ExclaimEqual:
4741 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004742 // For every pointer to member type T, there exist candidate operator
4743 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004744 //
4745 // bool operator==(T,T);
4746 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004747 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004748 MemPtr = CandidateTypes.member_pointer_begin(),
4749 MemPtrEnd = CandidateTypes.member_pointer_end();
4750 MemPtr != MemPtrEnd;
4751 ++MemPtr) {
4752 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4753 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4754 }
Mike Stump11289f42009-09-09 15:08:12 +00004755
Douglas Gregor84605ae2009-08-24 13:43:27 +00004756 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004757
Douglas Gregora11693b2008-11-12 17:17:38 +00004758 case OO_Less:
4759 case OO_Greater:
4760 case OO_LessEqual:
4761 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004762 // C++ [over.built]p15:
4763 //
4764 // For every pointer or enumeration type T, there exist
4765 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004766 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004767 // bool operator<(T, T);
4768 // bool operator>(T, T);
4769 // bool operator<=(T, T);
4770 // bool operator>=(T, T);
4771 // bool operator==(T, T);
4772 // bool operator!=(T, T);
4773 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4774 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4775 QualType ParamTypes[2] = { *Ptr, *Ptr };
4776 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4777 }
Mike Stump11289f42009-09-09 15:08:12 +00004778 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004779 = CandidateTypes.enumeration_begin();
4780 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4781 QualType ParamTypes[2] = { *Enum, *Enum };
4782 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4783 }
4784
4785 // Fall through.
4786 isComparison = true;
4787
Douglas Gregord08452f2008-11-19 15:42:04 +00004788 BinaryPlus:
4789 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004790 if (!isComparison) {
4791 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4792
4793 // C++ [over.built]p13:
4794 //
4795 // For every cv-qualified or cv-unqualified object type T
4796 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004797 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004798 // T* operator+(T*, ptrdiff_t);
4799 // T& operator[](T*, ptrdiff_t); [BELOW]
4800 // T* operator-(T*, ptrdiff_t);
4801 // T* operator+(ptrdiff_t, T*);
4802 // T& operator[](ptrdiff_t, T*); [BELOW]
4803 //
4804 // C++ [over.built]p14:
4805 //
4806 // For every T, where T is a pointer to object type, there
4807 // exist candidate operator functions of the form
4808 //
4809 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004810 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004811 = CandidateTypes.pointer_begin();
4812 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4813 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4814
4815 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4816 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4817
4818 if (Op == OO_Plus) {
4819 // T* operator+(ptrdiff_t, T*);
4820 ParamTypes[0] = ParamTypes[1];
4821 ParamTypes[1] = *Ptr;
4822 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4823 } else {
4824 // ptrdiff_t operator-(T, T);
4825 ParamTypes[1] = *Ptr;
4826 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4827 Args, 2, CandidateSet);
4828 }
4829 }
4830 }
4831 // Fall through
4832
Douglas Gregora11693b2008-11-12 17:17:38 +00004833 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004834 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004835 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004836 // C++ [over.built]p12:
4837 //
4838 // For every pair of promoted arithmetic types L and R, there
4839 // exist candidate operator functions of the form
4840 //
4841 // LR operator*(L, R);
4842 // LR operator/(L, R);
4843 // LR operator+(L, R);
4844 // LR operator-(L, R);
4845 // bool operator<(L, R);
4846 // bool operator>(L, R);
4847 // bool operator<=(L, R);
4848 // bool operator>=(L, R);
4849 // bool operator==(L, R);
4850 // bool operator!=(L, R);
4851 //
4852 // where LR is the result of the usual arithmetic conversions
4853 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004854 //
4855 // C++ [over.built]p24:
4856 //
4857 // For every pair of promoted arithmetic types L and R, there exist
4858 // candidate operator functions of the form
4859 //
4860 // LR operator?(bool, L, R);
4861 //
4862 // where LR is the result of the usual arithmetic conversions
4863 // between types L and R.
4864 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004865 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004866 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004867 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004868 Right < LastPromotedArithmeticType; ++Right) {
4869 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004870 QualType Result
4871 = isComparison
4872 ? Context.BoolTy
4873 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004874 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4875 }
4876 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004877
4878 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4879 // conditional operator for vector types.
4880 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4881 Vec1End = CandidateTypes.vector_end();
4882 Vec1 != Vec1End; ++Vec1)
4883 for (BuiltinCandidateTypeSet::iterator
4884 Vec2 = CandidateTypes.vector_begin(),
4885 Vec2End = CandidateTypes.vector_end();
4886 Vec2 != Vec2End; ++Vec2) {
4887 QualType LandR[2] = { *Vec1, *Vec2 };
4888 QualType Result;
4889 if (isComparison)
4890 Result = Context.BoolTy;
4891 else {
4892 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4893 Result = *Vec1;
4894 else
4895 Result = *Vec2;
4896 }
4897
4898 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4899 }
4900
Douglas Gregora11693b2008-11-12 17:17:38 +00004901 break;
4902
4903 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004904 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004905 case OO_Caret:
4906 case OO_Pipe:
4907 case OO_LessLess:
4908 case OO_GreaterGreater:
4909 // C++ [over.built]p17:
4910 //
4911 // For every pair of promoted integral types L and R, there
4912 // exist candidate operator functions of the form
4913 //
4914 // LR operator%(L, R);
4915 // LR operator&(L, R);
4916 // LR operator^(L, R);
4917 // LR operator|(L, R);
4918 // L operator<<(L, R);
4919 // L operator>>(L, R);
4920 //
4921 // where LR is the result of the usual arithmetic conversions
4922 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004923 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004924 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004925 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004926 Right < LastPromotedIntegralType; ++Right) {
4927 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4928 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4929 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004930 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004931 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4932 }
4933 }
4934 break;
4935
4936 case OO_Equal:
4937 // C++ [over.built]p20:
4938 //
4939 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004940 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004941 // empty, there exist candidate operator functions of the form
4942 //
4943 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004944 for (BuiltinCandidateTypeSet::iterator
4945 Enum = CandidateTypes.enumeration_begin(),
4946 EnumEnd = CandidateTypes.enumeration_end();
4947 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004948 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004949 CandidateSet);
4950 for (BuiltinCandidateTypeSet::iterator
4951 MemPtr = CandidateTypes.member_pointer_begin(),
4952 MemPtrEnd = CandidateTypes.member_pointer_end();
4953 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004954 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004955 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004956
4957 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004958
4959 case OO_PlusEqual:
4960 case OO_MinusEqual:
4961 // C++ [over.built]p19:
4962 //
4963 // For every pair (T, VQ), where T is any type and VQ is either
4964 // volatile or empty, there exist candidate operator functions
4965 // of the form
4966 //
4967 // T*VQ& operator=(T*VQ&, T*);
4968 //
4969 // C++ [over.built]p21:
4970 //
4971 // For every pair (T, VQ), where T is a cv-qualified or
4972 // cv-unqualified object type and VQ is either volatile or
4973 // empty, there exist candidate operator functions of the form
4974 //
4975 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4976 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4977 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4978 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4979 QualType ParamTypes[2];
4980 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4981
4982 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004983 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004984 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4985 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004986
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004987 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4988 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004989 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004990 ParamTypes[0]
4991 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004992 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4993 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004994 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004995 }
4996 // Fall through.
4997
4998 case OO_StarEqual:
4999 case OO_SlashEqual:
5000 // C++ [over.built]p18:
5001 //
5002 // For every triple (L, VQ, R), where L is an arithmetic type,
5003 // VQ is either volatile or empty, and R is a promoted
5004 // arithmetic type, there exist candidate operator functions of
5005 // the form
5006 //
5007 // VQ L& operator=(VQ L&, R);
5008 // VQ L& operator*=(VQ L&, R);
5009 // VQ L& operator/=(VQ L&, R);
5010 // VQ L& operator+=(VQ L&, R);
5011 // VQ L& operator-=(VQ L&, R);
5012 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005013 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005014 Right < LastPromotedArithmeticType; ++Right) {
5015 QualType ParamTypes[2];
5016 ParamTypes[1] = ArithmeticTypes[Right];
5017
5018 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005019 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005020 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5021 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005022
5023 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005024 if (VisibleTypeConversionsQuals.hasVolatile()) {
5025 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5026 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5027 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5028 /*IsAssigmentOperator=*/Op == OO_Equal);
5029 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005030 }
5031 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005032
5033 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5034 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
5035 Vec1End = CandidateTypes.vector_end();
5036 Vec1 != Vec1End; ++Vec1)
5037 for (BuiltinCandidateTypeSet::iterator
5038 Vec2 = CandidateTypes.vector_begin(),
5039 Vec2End = CandidateTypes.vector_end();
5040 Vec2 != Vec2End; ++Vec2) {
5041 QualType ParamTypes[2];
5042 ParamTypes[1] = *Vec2;
5043 // Add this built-in operator as a candidate (VQ is empty).
5044 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5045 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5046 /*IsAssigmentOperator=*/Op == OO_Equal);
5047
5048 // Add this built-in operator as a candidate (VQ is 'volatile').
5049 if (VisibleTypeConversionsQuals.hasVolatile()) {
5050 ParamTypes[0] = Context.getVolatileType(*Vec1);
5051 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5052 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5053 /*IsAssigmentOperator=*/Op == OO_Equal);
5054 }
5055 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005056 break;
5057
5058 case OO_PercentEqual:
5059 case OO_LessLessEqual:
5060 case OO_GreaterGreaterEqual:
5061 case OO_AmpEqual:
5062 case OO_CaretEqual:
5063 case OO_PipeEqual:
5064 // C++ [over.built]p22:
5065 //
5066 // For every triple (L, VQ, R), where L is an integral type, VQ
5067 // is either volatile or empty, and R is a promoted integral
5068 // type, there exist candidate operator functions of the form
5069 //
5070 // VQ L& operator%=(VQ L&, R);
5071 // VQ L& operator<<=(VQ L&, R);
5072 // VQ L& operator>>=(VQ L&, R);
5073 // VQ L& operator&=(VQ L&, R);
5074 // VQ L& operator^=(VQ L&, R);
5075 // VQ L& operator|=(VQ L&, R);
5076 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005077 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005078 Right < LastPromotedIntegralType; ++Right) {
5079 QualType ParamTypes[2];
5080 ParamTypes[1] = ArithmeticTypes[Right];
5081
5082 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005083 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005084 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005085 if (VisibleTypeConversionsQuals.hasVolatile()) {
5086 // Add this built-in operator as a candidate (VQ is 'volatile').
5087 ParamTypes[0] = ArithmeticTypes[Left];
5088 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5089 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5090 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5091 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005092 }
5093 }
5094 break;
5095
Douglas Gregord08452f2008-11-19 15:42:04 +00005096 case OO_Exclaim: {
5097 // C++ [over.operator]p23:
5098 //
5099 // There also exist candidate operator functions of the form
5100 //
Mike Stump11289f42009-09-09 15:08:12 +00005101 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005102 // bool operator&&(bool, bool); [BELOW]
5103 // bool operator||(bool, bool); [BELOW]
5104 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005105 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5106 /*IsAssignmentOperator=*/false,
5107 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005108 break;
5109 }
5110
Douglas Gregora11693b2008-11-12 17:17:38 +00005111 case OO_AmpAmp:
5112 case OO_PipePipe: {
5113 // C++ [over.operator]p23:
5114 //
5115 // There also exist candidate operator functions of the form
5116 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005117 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005118 // bool operator&&(bool, bool);
5119 // bool operator||(bool, bool);
5120 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005121 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5122 /*IsAssignmentOperator=*/false,
5123 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005124 break;
5125 }
5126
5127 case OO_Subscript:
5128 // C++ [over.built]p13:
5129 //
5130 // For every cv-qualified or cv-unqualified object type T there
5131 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005132 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005133 // T* operator+(T*, ptrdiff_t); [ABOVE]
5134 // T& operator[](T*, ptrdiff_t);
5135 // T* operator-(T*, ptrdiff_t); [ABOVE]
5136 // T* operator+(ptrdiff_t, T*); [ABOVE]
5137 // T& operator[](ptrdiff_t, T*);
5138 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5139 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5140 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005141 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005142 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005143
5144 // T& operator[](T*, ptrdiff_t)
5145 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5146
5147 // T& operator[](ptrdiff_t, T*);
5148 ParamTypes[0] = ParamTypes[1];
5149 ParamTypes[1] = *Ptr;
5150 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005151 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005152 break;
5153
5154 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005155 // C++ [over.built]p11:
5156 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5157 // C1 is the same type as C2 or is a derived class of C2, T is an object
5158 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5159 // there exist candidate operator functions of the form
5160 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5161 // where CV12 is the union of CV1 and CV2.
5162 {
5163 for (BuiltinCandidateTypeSet::iterator Ptr =
5164 CandidateTypes.pointer_begin();
5165 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5166 QualType C1Ty = (*Ptr);
5167 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005168 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005169 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5170 if (!isa<RecordType>(C1))
5171 continue;
5172 // heuristic to reduce number of builtin candidates in the set.
5173 // Add volatile/restrict version only if there are conversions to a
5174 // volatile/restrict type.
5175 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5176 continue;
5177 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5178 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005179 for (BuiltinCandidateTypeSet::iterator
5180 MemPtr = CandidateTypes.member_pointer_begin(),
5181 MemPtrEnd = CandidateTypes.member_pointer_end();
5182 MemPtr != MemPtrEnd; ++MemPtr) {
5183 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5184 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005185 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005186 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5187 break;
5188 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5189 // build CV12 T&
5190 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005191 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5192 T.isVolatileQualified())
5193 continue;
5194 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5195 T.isRestrictQualified())
5196 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005197 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005198 QualType ResultTy = Context.getLValueReferenceType(T);
5199 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5200 }
5201 }
5202 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005203 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005204
5205 case OO_Conditional:
5206 // Note that we don't consider the first argument, since it has been
5207 // contextually converted to bool long ago. The candidates below are
5208 // therefore added as binary.
5209 //
5210 // C++ [over.built]p24:
5211 // For every type T, where T is a pointer or pointer-to-member type,
5212 // there exist candidate operator functions of the form
5213 //
5214 // T operator?(bool, T, T);
5215 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005216 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5217 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5218 QualType ParamTypes[2] = { *Ptr, *Ptr };
5219 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5220 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005221 for (BuiltinCandidateTypeSet::iterator Ptr =
5222 CandidateTypes.member_pointer_begin(),
5223 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5224 QualType ParamTypes[2] = { *Ptr, *Ptr };
5225 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5226 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005227 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005228 }
5229}
5230
Douglas Gregore254f902009-02-04 00:32:51 +00005231/// \brief Add function candidates found via argument-dependent lookup
5232/// to the set of overloading candidates.
5233///
5234/// This routine performs argument-dependent name lookup based on the
5235/// given function name (which may also be an operator name) and adds
5236/// all of the overload candidates found by ADL to the overload
5237/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005238void
Douglas Gregore254f902009-02-04 00:32:51 +00005239Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005240 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005241 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005242 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005243 OverloadCandidateSet& CandidateSet,
5244 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005245 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005246
John McCall91f61fc2010-01-26 06:04:06 +00005247 // FIXME: This approach for uniquing ADL results (and removing
5248 // redundant candidates from the set) relies on pointer-equality,
5249 // which means we need to key off the canonical decl. However,
5250 // always going back to the canonical decl might not get us the
5251 // right set of default arguments. What default arguments are
5252 // we supposed to consider on ADL candidates, anyway?
5253
Douglas Gregorcabea402009-09-22 15:41:20 +00005254 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005255 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005256
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005257 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005258 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5259 CandEnd = CandidateSet.end();
5260 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005261 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005262 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005263 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005264 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005265 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005266
5267 // For each of the ADL candidates we found, add it to the overload
5268 // set.
John McCall8fe68082010-01-26 07:16:45 +00005269 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005270 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005272 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005273 continue;
5274
John McCalla0296f72010-03-19 07:35:19 +00005275 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005276 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005277 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005278 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005279 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005280 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005281 }
Douglas Gregore254f902009-02-04 00:32:51 +00005282}
5283
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005284/// isBetterOverloadCandidate - Determines whether the first overload
5285/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005286bool
John McCall5c32be02010-08-24 20:38:10 +00005287isBetterOverloadCandidate(Sema &S,
5288 const OverloadCandidate& Cand1,
5289 const OverloadCandidate& Cand2,
5290 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005291 // Define viable functions to be better candidates than non-viable
5292 // functions.
5293 if (!Cand2.Viable)
5294 return Cand1.Viable;
5295 else if (!Cand1.Viable)
5296 return false;
5297
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005298 // C++ [over.match.best]p1:
5299 //
5300 // -- if F is a static member function, ICS1(F) is defined such
5301 // that ICS1(F) is neither better nor worse than ICS1(G) for
5302 // any function G, and, symmetrically, ICS1(G) is neither
5303 // better nor worse than ICS1(F).
5304 unsigned StartArg = 0;
5305 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5306 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005307
Douglas Gregord3cb3562009-07-07 23:38:56 +00005308 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005309 // A viable function F1 is defined to be a better function than another
5310 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005311 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005312 unsigned NumArgs = Cand1.Conversions.size();
5313 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5314 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005315 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005316 switch (CompareImplicitConversionSequences(S,
5317 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005318 Cand2.Conversions[ArgIdx])) {
5319 case ImplicitConversionSequence::Better:
5320 // Cand1 has a better conversion sequence.
5321 HasBetterConversion = true;
5322 break;
5323
5324 case ImplicitConversionSequence::Worse:
5325 // Cand1 can't be better than Cand2.
5326 return false;
5327
5328 case ImplicitConversionSequence::Indistinguishable:
5329 // Do nothing.
5330 break;
5331 }
5332 }
5333
Mike Stump11289f42009-09-09 15:08:12 +00005334 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005335 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005336 if (HasBetterConversion)
5337 return true;
5338
Mike Stump11289f42009-09-09 15:08:12 +00005339 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005340 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005341 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005342 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5343 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005344
5345 // -- F1 and F2 are function template specializations, and the function
5346 // template for F1 is more specialized than the template for F2
5347 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005348 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005349 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5350 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005351 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005352 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5353 Cand2.Function->getPrimaryTemplate(),
5354 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005355 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5356 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005357 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005358
Douglas Gregora1f013e2008-11-07 22:36:19 +00005359 // -- the context is an initialization by user-defined conversion
5360 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5361 // from the return type of F1 to the destination type (i.e.,
5362 // the type of the entity being initialized) is a better
5363 // conversion sequence than the standard conversion sequence
5364 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005365 if (Cand1.Function && Cand2.Function &&
5366 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005367 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005368 switch (CompareStandardConversionSequences(S,
5369 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005370 Cand2.FinalConversion)) {
5371 case ImplicitConversionSequence::Better:
5372 // Cand1 has a better conversion sequence.
5373 return true;
5374
5375 case ImplicitConversionSequence::Worse:
5376 // Cand1 can't be better than Cand2.
5377 return false;
5378
5379 case ImplicitConversionSequence::Indistinguishable:
5380 // Do nothing
5381 break;
5382 }
5383 }
5384
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005385 return false;
5386}
5387
Mike Stump11289f42009-09-09 15:08:12 +00005388/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005389/// within an overload candidate set.
5390///
5391/// \param CandidateSet the set of candidate functions.
5392///
5393/// \param Loc the location of the function name (or operator symbol) for
5394/// which overload resolution occurs.
5395///
Mike Stump11289f42009-09-09 15:08:12 +00005396/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005397/// function, Best points to the candidate function found.
5398///
5399/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005400OverloadingResult
5401OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
5402 iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005403 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005404 Best = end();
5405 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5406 if (Cand->Viable)
5407 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005408 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005409 }
5410
5411 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005412 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005413 return OR_No_Viable_Function;
5414
5415 // Make sure that this function is better than every other viable
5416 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005417 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005418 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005419 Cand != Best &&
John McCall5c32be02010-08-24 20:38:10 +00005420 !isBetterOverloadCandidate(S, *Best, *Cand, Loc)) {
5421 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005422 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005423 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005424 }
Mike Stump11289f42009-09-09 15:08:12 +00005425
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005426 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005427 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005428 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005429 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005430 return OR_Deleted;
5431
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005432 // C++ [basic.def.odr]p2:
5433 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005434 // when referred to from a potentially-evaluated expression. [Note: this
5435 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005436 // (clause 13), user-defined conversions (12.3.2), allocation function for
5437 // placement new (5.3.4), as well as non-default initialization (8.5).
5438 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005439 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005440 return OR_Success;
5441}
5442
John McCall53262c92010-01-12 02:15:36 +00005443namespace {
5444
5445enum OverloadCandidateKind {
5446 oc_function,
5447 oc_method,
5448 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005449 oc_function_template,
5450 oc_method_template,
5451 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005452 oc_implicit_default_constructor,
5453 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005454 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005455};
5456
John McCalle1ac8d12010-01-13 00:25:19 +00005457OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5458 FunctionDecl *Fn,
5459 std::string &Description) {
5460 bool isTemplate = false;
5461
5462 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5463 isTemplate = true;
5464 Description = S.getTemplateArgumentBindingsText(
5465 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5466 }
John McCallfd0b2f82010-01-06 09:43:14 +00005467
5468 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005469 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005470 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005471
John McCall53262c92010-01-12 02:15:36 +00005472 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5473 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005474 }
5475
5476 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5477 // This actually gets spelled 'candidate function' for now, but
5478 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005479 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005480 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005481
5482 assert(Meth->isCopyAssignment()
5483 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005484 return oc_implicit_copy_assignment;
5485 }
5486
John McCalle1ac8d12010-01-13 00:25:19 +00005487 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005488}
5489
5490} // end anonymous namespace
5491
5492// Notes the location of an overload candidate.
5493void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005494 std::string FnDesc;
5495 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5496 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5497 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005498}
5499
John McCall0d1da222010-01-12 00:44:57 +00005500/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5501/// "lead" diagnostic; it will be given two arguments, the source and
5502/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005503void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5504 Sema &S,
5505 SourceLocation CaretLoc,
5506 const PartialDiagnostic &PDiag) const {
5507 S.Diag(CaretLoc, PDiag)
5508 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005509 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005510 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5511 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005512 }
John McCall12f97bc2010-01-08 04:41:39 +00005513}
5514
John McCall0d1da222010-01-12 00:44:57 +00005515namespace {
5516
John McCall6a61b522010-01-13 09:16:55 +00005517void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5518 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5519 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005520 assert(Cand->Function && "for now, candidate must be a function");
5521 FunctionDecl *Fn = Cand->Function;
5522
5523 // There's a conversion slot for the object argument if this is a
5524 // non-constructor method. Note that 'I' corresponds the
5525 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005526 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005527 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005528 if (I == 0)
5529 isObjectArgument = true;
5530 else
5531 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005532 }
5533
John McCalle1ac8d12010-01-13 00:25:19 +00005534 std::string FnDesc;
5535 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5536
John McCall6a61b522010-01-13 09:16:55 +00005537 Expr *FromExpr = Conv.Bad.FromExpr;
5538 QualType FromTy = Conv.Bad.getFromType();
5539 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005540
John McCallfb7ad0f2010-02-02 02:42:52 +00005541 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005542 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005543 Expr *E = FromExpr->IgnoreParens();
5544 if (isa<UnaryOperator>(E))
5545 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005546 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005547
5548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5549 << (unsigned) FnKind << FnDesc
5550 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5551 << ToTy << Name << I+1;
5552 return;
5553 }
5554
John McCall6d174642010-01-23 08:10:49 +00005555 // Do some hand-waving analysis to see if the non-viability is due
5556 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005557 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5558 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5559 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5560 CToTy = RT->getPointeeType();
5561 else {
5562 // TODO: detect and diagnose the full richness of const mismatches.
5563 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5564 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5565 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5566 }
5567
5568 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5569 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5570 // It is dumb that we have to do this here.
5571 while (isa<ArrayType>(CFromTy))
5572 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5573 while (isa<ArrayType>(CToTy))
5574 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5575
5576 Qualifiers FromQs = CFromTy.getQualifiers();
5577 Qualifiers ToQs = CToTy.getQualifiers();
5578
5579 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5580 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5581 << (unsigned) FnKind << FnDesc
5582 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5583 << FromTy
5584 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5585 << (unsigned) isObjectArgument << I+1;
5586 return;
5587 }
5588
5589 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5590 assert(CVR && "unexpected qualifiers mismatch");
5591
5592 if (isObjectArgument) {
5593 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5594 << (unsigned) FnKind << FnDesc
5595 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5596 << FromTy << (CVR - 1);
5597 } else {
5598 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5599 << (unsigned) FnKind << FnDesc
5600 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5601 << FromTy << (CVR - 1) << I+1;
5602 }
5603 return;
5604 }
5605
John McCall6d174642010-01-23 08:10:49 +00005606 // Diagnose references or pointers to incomplete types differently,
5607 // since it's far from impossible that the incompleteness triggered
5608 // the failure.
5609 QualType TempFromTy = FromTy.getNonReferenceType();
5610 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5611 TempFromTy = PTy->getPointeeType();
5612 if (TempFromTy->isIncompleteType()) {
5613 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5614 << (unsigned) FnKind << FnDesc
5615 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5616 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5617 return;
5618 }
5619
Douglas Gregor56f2e342010-06-30 23:01:39 +00005620 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005621 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005622 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5623 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5624 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5625 FromPtrTy->getPointeeType()) &&
5626 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5627 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5628 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5629 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005630 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005631 }
5632 } else if (const ObjCObjectPointerType *FromPtrTy
5633 = FromTy->getAs<ObjCObjectPointerType>()) {
5634 if (const ObjCObjectPointerType *ToPtrTy
5635 = ToTy->getAs<ObjCObjectPointerType>())
5636 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5637 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5638 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5639 FromPtrTy->getPointeeType()) &&
5640 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005641 BaseToDerivedConversion = 2;
5642 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5643 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5644 !FromTy->isIncompleteType() &&
5645 !ToRefTy->getPointeeType()->isIncompleteType() &&
5646 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5647 BaseToDerivedConversion = 3;
5648 }
5649
5650 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005651 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005652 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005653 << (unsigned) FnKind << FnDesc
5654 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005655 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005656 << FromTy << ToTy << I+1;
5657 return;
5658 }
5659
John McCall47000992010-01-14 03:28:57 +00005660 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5662 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005663 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005664 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005665}
5666
5667void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5668 unsigned NumFormalArgs) {
5669 // TODO: treat calls to a missing default constructor as a special case
5670
5671 FunctionDecl *Fn = Cand->Function;
5672 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5673
5674 unsigned MinParams = Fn->getMinRequiredArguments();
5675
5676 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005677 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005678 unsigned mode, modeCount;
5679 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005680 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5681 (Cand->FailureKind == ovl_fail_bad_deduction &&
5682 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005683 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5684 mode = 0; // "at least"
5685 else
5686 mode = 2; // "exactly"
5687 modeCount = MinParams;
5688 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005689 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5690 (Cand->FailureKind == ovl_fail_bad_deduction &&
5691 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005692 if (MinParams != FnTy->getNumArgs())
5693 mode = 1; // "at most"
5694 else
5695 mode = 2; // "exactly"
5696 modeCount = FnTy->getNumArgs();
5697 }
5698
5699 std::string Description;
5700 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5701
5702 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005703 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5704 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005705}
5706
John McCall8b9ed552010-02-01 18:53:26 +00005707/// Diagnose a failed template-argument deduction.
5708void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5709 Expr **Args, unsigned NumArgs) {
5710 FunctionDecl *Fn = Cand->Function; // pattern
5711
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005712 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005713 NamedDecl *ParamD;
5714 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5715 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5716 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005717 switch (Cand->DeductionFailure.Result) {
5718 case Sema::TDK_Success:
5719 llvm_unreachable("TDK_success while diagnosing bad deduction");
5720
5721 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005722 assert(ParamD && "no parameter found for incomplete deduction result");
5723 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5724 << ParamD->getDeclName();
5725 return;
5726 }
5727
John McCall42d7d192010-08-05 09:05:08 +00005728 case Sema::TDK_Underqualified: {
5729 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5730 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5731
5732 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5733
5734 // Param will have been canonicalized, but it should just be a
5735 // qualified version of ParamD, so move the qualifiers to that.
5736 QualifierCollector Qs(S.Context);
5737 Qs.strip(Param);
5738 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5739 assert(S.Context.hasSameType(Param, NonCanonParam));
5740
5741 // Arg has also been canonicalized, but there's nothing we can do
5742 // about that. It also doesn't matter as much, because it won't
5743 // have any template parameters in it (because deduction isn't
5744 // done on dependent types).
5745 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5746
5747 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5748 << ParamD->getDeclName() << Arg << NonCanonParam;
5749 return;
5750 }
5751
5752 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005753 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005754 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005755 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005756 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005757 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005758 which = 1;
5759 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005760 which = 2;
5761 }
5762
5763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5764 << which << ParamD->getDeclName()
5765 << *Cand->DeductionFailure.getFirstArg()
5766 << *Cand->DeductionFailure.getSecondArg();
5767 return;
5768 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005769
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005770 case Sema::TDK_InvalidExplicitArguments:
5771 assert(ParamD && "no parameter found for invalid explicit arguments");
5772 if (ParamD->getDeclName())
5773 S.Diag(Fn->getLocation(),
5774 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5775 << ParamD->getDeclName();
5776 else {
5777 int index = 0;
5778 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5779 index = TTP->getIndex();
5780 else if (NonTypeTemplateParmDecl *NTTP
5781 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5782 index = NTTP->getIndex();
5783 else
5784 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5785 S.Diag(Fn->getLocation(),
5786 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5787 << (index + 1);
5788 }
5789 return;
5790
Douglas Gregor02eb4832010-05-08 18:13:28 +00005791 case Sema::TDK_TooManyArguments:
5792 case Sema::TDK_TooFewArguments:
5793 DiagnoseArityMismatch(S, Cand, NumArgs);
5794 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005795
5796 case Sema::TDK_InstantiationDepth:
5797 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5798 return;
5799
5800 case Sema::TDK_SubstitutionFailure: {
5801 std::string ArgString;
5802 if (TemplateArgumentList *Args
5803 = Cand->DeductionFailure.getTemplateArgumentList())
5804 ArgString = S.getTemplateArgumentBindingsText(
5805 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5806 *Args);
5807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5808 << ArgString;
5809 return;
5810 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005811
John McCall8b9ed552010-02-01 18:53:26 +00005812 // TODO: diagnose these individually, then kill off
5813 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005814 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005815 case Sema::TDK_FailedOverloadResolution:
5816 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5817 return;
5818 }
5819}
5820
5821/// Generates a 'note' diagnostic for an overload candidate. We've
5822/// already generated a primary error at the call site.
5823///
5824/// It really does need to be a single diagnostic with its caret
5825/// pointed at the candidate declaration. Yes, this creates some
5826/// major challenges of technical writing. Yes, this makes pointing
5827/// out problems with specific arguments quite awkward. It's still
5828/// better than generating twenty screens of text for every failed
5829/// overload.
5830///
5831/// It would be great to be able to express per-candidate problems
5832/// more richly for those diagnostic clients that cared, but we'd
5833/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005834void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5835 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005836 FunctionDecl *Fn = Cand->Function;
5837
John McCall12f97bc2010-01-08 04:41:39 +00005838 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005839 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005840 std::string FnDesc;
5841 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005842
5843 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005844 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005845 return;
John McCall12f97bc2010-01-08 04:41:39 +00005846 }
5847
John McCalle1ac8d12010-01-13 00:25:19 +00005848 // We don't really have anything else to say about viable candidates.
5849 if (Cand->Viable) {
5850 S.NoteOverloadCandidate(Fn);
5851 return;
5852 }
John McCall0d1da222010-01-12 00:44:57 +00005853
John McCall6a61b522010-01-13 09:16:55 +00005854 switch (Cand->FailureKind) {
5855 case ovl_fail_too_many_arguments:
5856 case ovl_fail_too_few_arguments:
5857 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005858
John McCall6a61b522010-01-13 09:16:55 +00005859 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005860 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5861
John McCallfe796dd2010-01-23 05:17:32 +00005862 case ovl_fail_trivial_conversion:
5863 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005864 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005865 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005866
John McCall65eb8792010-02-25 01:37:24 +00005867 case ovl_fail_bad_conversion: {
5868 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5869 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005870 if (Cand->Conversions[I].isBad())
5871 return DiagnoseBadConversion(S, Cand, I);
5872
5873 // FIXME: this currently happens when we're called from SemaInit
5874 // when user-conversion overload fails. Figure out how to handle
5875 // those conditions and diagnose them well.
5876 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005877 }
John McCall65eb8792010-02-25 01:37:24 +00005878 }
John McCalld3224162010-01-08 00:58:21 +00005879}
5880
5881void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5882 // Desugar the type of the surrogate down to a function type,
5883 // retaining as many typedefs as possible while still showing
5884 // the function type (and, therefore, its parameter types).
5885 QualType FnType = Cand->Surrogate->getConversionType();
5886 bool isLValueReference = false;
5887 bool isRValueReference = false;
5888 bool isPointer = false;
5889 if (const LValueReferenceType *FnTypeRef =
5890 FnType->getAs<LValueReferenceType>()) {
5891 FnType = FnTypeRef->getPointeeType();
5892 isLValueReference = true;
5893 } else if (const RValueReferenceType *FnTypeRef =
5894 FnType->getAs<RValueReferenceType>()) {
5895 FnType = FnTypeRef->getPointeeType();
5896 isRValueReference = true;
5897 }
5898 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5899 FnType = FnTypePtr->getPointeeType();
5900 isPointer = true;
5901 }
5902 // Desugar down to a function type.
5903 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5904 // Reconstruct the pointer/reference as appropriate.
5905 if (isPointer) FnType = S.Context.getPointerType(FnType);
5906 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5907 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5908
5909 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5910 << FnType;
5911}
5912
5913void NoteBuiltinOperatorCandidate(Sema &S,
5914 const char *Opc,
5915 SourceLocation OpLoc,
5916 OverloadCandidate *Cand) {
5917 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5918 std::string TypeStr("operator");
5919 TypeStr += Opc;
5920 TypeStr += "(";
5921 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5922 if (Cand->Conversions.size() == 1) {
5923 TypeStr += ")";
5924 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5925 } else {
5926 TypeStr += ", ";
5927 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5928 TypeStr += ")";
5929 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5930 }
5931}
5932
5933void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5934 OverloadCandidate *Cand) {
5935 unsigned NoOperands = Cand->Conversions.size();
5936 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5937 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005938 if (ICS.isBad()) break; // all meaningless after first invalid
5939 if (!ICS.isAmbiguous()) continue;
5940
John McCall5c32be02010-08-24 20:38:10 +00005941 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005942 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005943 }
5944}
5945
John McCall3712d9e2010-01-15 23:32:50 +00005946SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5947 if (Cand->Function)
5948 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005949 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005950 return Cand->Surrogate->getLocation();
5951 return SourceLocation();
5952}
5953
John McCallad2587a2010-01-12 00:48:53 +00005954struct CompareOverloadCandidatesForDisplay {
5955 Sema &S;
5956 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005957
5958 bool operator()(const OverloadCandidate *L,
5959 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005960 // Fast-path this check.
5961 if (L == R) return false;
5962
John McCall12f97bc2010-01-08 04:41:39 +00005963 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005964 if (L->Viable) {
5965 if (!R->Viable) return true;
5966
5967 // TODO: introduce a tri-valued comparison for overload
5968 // candidates. Would be more worthwhile if we had a sort
5969 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00005970 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
5971 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005972 } else if (R->Viable)
5973 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005974
John McCall3712d9e2010-01-15 23:32:50 +00005975 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005976
John McCall3712d9e2010-01-15 23:32:50 +00005977 // Criteria by which we can sort non-viable candidates:
5978 if (!L->Viable) {
5979 // 1. Arity mismatches come after other candidates.
5980 if (L->FailureKind == ovl_fail_too_many_arguments ||
5981 L->FailureKind == ovl_fail_too_few_arguments)
5982 return false;
5983 if (R->FailureKind == ovl_fail_too_many_arguments ||
5984 R->FailureKind == ovl_fail_too_few_arguments)
5985 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005986
John McCallfe796dd2010-01-23 05:17:32 +00005987 // 2. Bad conversions come first and are ordered by the number
5988 // of bad conversions and quality of good conversions.
5989 if (L->FailureKind == ovl_fail_bad_conversion) {
5990 if (R->FailureKind != ovl_fail_bad_conversion)
5991 return true;
5992
5993 // If there's any ordering between the defined conversions...
5994 // FIXME: this might not be transitive.
5995 assert(L->Conversions.size() == R->Conversions.size());
5996
5997 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005998 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5999 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006000 switch (CompareImplicitConversionSequences(S,
6001 L->Conversions[I],
6002 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006003 case ImplicitConversionSequence::Better:
6004 leftBetter++;
6005 break;
6006
6007 case ImplicitConversionSequence::Worse:
6008 leftBetter--;
6009 break;
6010
6011 case ImplicitConversionSequence::Indistinguishable:
6012 break;
6013 }
6014 }
6015 if (leftBetter > 0) return true;
6016 if (leftBetter < 0) return false;
6017
6018 } else if (R->FailureKind == ovl_fail_bad_conversion)
6019 return false;
6020
John McCall3712d9e2010-01-15 23:32:50 +00006021 // TODO: others?
6022 }
6023
6024 // Sort everything else by location.
6025 SourceLocation LLoc = GetLocationForCandidate(L);
6026 SourceLocation RLoc = GetLocationForCandidate(R);
6027
6028 // Put candidates without locations (e.g. builtins) at the end.
6029 if (LLoc.isInvalid()) return false;
6030 if (RLoc.isInvalid()) return true;
6031
6032 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006033 }
6034};
6035
John McCallfe796dd2010-01-23 05:17:32 +00006036/// CompleteNonViableCandidate - Normally, overload resolution only
6037/// computes up to the first
6038void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6039 Expr **Args, unsigned NumArgs) {
6040 assert(!Cand->Viable);
6041
6042 // Don't do anything on failures other than bad conversion.
6043 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6044
6045 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006046 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006047 unsigned ConvCount = Cand->Conversions.size();
6048 while (true) {
6049 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6050 ConvIdx++;
6051 if (Cand->Conversions[ConvIdx - 1].isBad())
6052 break;
6053 }
6054
6055 if (ConvIdx == ConvCount)
6056 return;
6057
John McCall65eb8792010-02-25 01:37:24 +00006058 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6059 "remaining conversion is initialized?");
6060
Douglas Gregoradc7a702010-04-16 17:45:54 +00006061 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006062 // operation somehow.
6063 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006064
6065 const FunctionProtoType* Proto;
6066 unsigned ArgIdx = ConvIdx;
6067
6068 if (Cand->IsSurrogate) {
6069 QualType ConvType
6070 = Cand->Surrogate->getConversionType().getNonReferenceType();
6071 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6072 ConvType = ConvPtrType->getPointeeType();
6073 Proto = ConvType->getAs<FunctionProtoType>();
6074 ArgIdx--;
6075 } else if (Cand->Function) {
6076 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6077 if (isa<CXXMethodDecl>(Cand->Function) &&
6078 !isa<CXXConstructorDecl>(Cand->Function))
6079 ArgIdx--;
6080 } else {
6081 // Builtin binary operator with a bad first conversion.
6082 assert(ConvCount <= 3);
6083 for (; ConvIdx != ConvCount; ++ConvIdx)
6084 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006085 = TryCopyInitialization(S, Args[ConvIdx],
6086 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6087 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006088 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006089 return;
6090 }
6091
6092 // Fill in the rest of the conversions.
6093 unsigned NumArgsInProto = Proto->getNumArgs();
6094 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6095 if (ArgIdx < NumArgsInProto)
6096 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006097 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6098 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006099 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006100 else
6101 Cand->Conversions[ConvIdx].setEllipsis();
6102 }
6103}
6104
John McCalld3224162010-01-08 00:58:21 +00006105} // end anonymous namespace
6106
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006107/// PrintOverloadCandidates - When overload resolution fails, prints
6108/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006109/// set.
John McCall5c32be02010-08-24 20:38:10 +00006110void OverloadCandidateSet::NoteCandidates(Sema &S,
6111 OverloadCandidateDisplayKind OCD,
6112 Expr **Args, unsigned NumArgs,
6113 const char *Opc,
6114 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006115 // Sort the candidates by viability and position. Sorting directly would
6116 // be prohibitive, so we make a set of pointers and sort those.
6117 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006118 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6119 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006120 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006121 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006122 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006123 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006124 if (Cand->Function || Cand->IsSurrogate)
6125 Cands.push_back(Cand);
6126 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6127 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006128 }
6129 }
6130
John McCallad2587a2010-01-12 00:48:53 +00006131 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006132 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006133
John McCall0d1da222010-01-12 00:44:57 +00006134 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006135
John McCall12f97bc2010-01-08 04:41:39 +00006136 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006137 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006138 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006139 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6140 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006141
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006142 // Set an arbitrary limit on the number of candidate functions we'll spam
6143 // the user with. FIXME: This limit should depend on details of the
6144 // candidate list.
6145 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6146 break;
6147 }
6148 ++CandsShown;
6149
John McCalld3224162010-01-08 00:58:21 +00006150 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006151 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006152 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006153 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006154 else {
6155 assert(Cand->Viable &&
6156 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006157 // Generally we only see ambiguities including viable builtin
6158 // operators if overload resolution got screwed up by an
6159 // ambiguous user-defined conversion.
6160 //
6161 // FIXME: It's quite possible for different conversions to see
6162 // different ambiguities, though.
6163 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006164 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006165 ReportedAmbiguousConversions = true;
6166 }
John McCalld3224162010-01-08 00:58:21 +00006167
John McCall0d1da222010-01-12 00:44:57 +00006168 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006169 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006170 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006171 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006172
6173 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006174 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006175}
6176
John McCalla0296f72010-03-19 07:35:19 +00006177static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006178 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006179 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006180
John McCalla0296f72010-03-19 07:35:19 +00006181 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006182}
6183
Douglas Gregorcd695e52008-11-10 20:40:00 +00006184/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6185/// an overloaded function (C++ [over.over]), where @p From is an
6186/// expression with overloaded function type and @p ToType is the type
6187/// we're trying to resolve to. For example:
6188///
6189/// @code
6190/// int f(double);
6191/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006192///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006193/// int (*pfd)(double) = f; // selects f(double)
6194/// @endcode
6195///
6196/// This routine returns the resulting FunctionDecl if it could be
6197/// resolved, and NULL otherwise. When @p Complain is true, this
6198/// routine will emit diagnostics if there is an error.
6199FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006200Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006201 bool Complain,
6202 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006203 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006204 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006205 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006206 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006207 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006208 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006209 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006210 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006211 FunctionType = MemTypePtr->getPointeeType();
6212 IsMember = true;
6213 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006214
Douglas Gregorcd695e52008-11-10 20:40:00 +00006215 // C++ [over.over]p1:
6216 // [...] [Note: any redundant set of parentheses surrounding the
6217 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006218 // C++ [over.over]p1:
6219 // [...] The overloaded function name can be preceded by the &
6220 // operator.
John McCall7d460512010-08-24 23:26:21 +00006221 // However, remember whether the expression has member-pointer form:
6222 // C++ [expr.unary.op]p4:
6223 // A pointer to member is only formed when an explicit & is used
6224 // and its operand is a qualified-id not enclosed in
6225 // parentheses.
6226 bool HasFormOfMemberPointer = false;
6227 OverloadExpr *OvlExpr;
6228 {
6229 Expr *Tmp = From->IgnoreParens();
6230 if (isa<UnaryOperator>(Tmp)) {
6231 Tmp = cast<UnaryOperator>(Tmp)->getSubExpr();
6232 OvlExpr = cast<OverloadExpr>(Tmp->IgnoreParens());
6233 HasFormOfMemberPointer = (Tmp == OvlExpr && OvlExpr->getQualifier());
6234 } else {
6235 OvlExpr = cast<OverloadExpr>(Tmp);
6236 }
6237 }
6238
Douglas Gregor064fdb22010-04-14 23:11:21 +00006239 // We expect a pointer or reference to function, or a function pointer.
6240 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6241 if (!FunctionType->isFunctionType()) {
6242 if (Complain)
6243 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6244 << OvlExpr->getName() << ToType;
6245
6246 return 0;
6247 }
6248
John McCall24d18942010-08-24 22:52:39 +00006249 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006250 // member, don't try to convert it to a pointer-to-member type.
6251 if (IsMember && !HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006252 if (!Complain) return 0;
6253
6254 // TODO: Should we condition this on whether any functions might
6255 // have matched, or is it more appropriate to do that in callers?
6256 // TODO: a fixit wouldn't hurt.
6257 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6258 << ToType << OvlExpr->getSourceRange();
6259 return 0;
6260 }
6261
6262 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6263 if (OvlExpr->hasExplicitTemplateArgs()) {
6264 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6265 ExplicitTemplateArgs = &ETABuffer;
6266 }
6267
Douglas Gregor064fdb22010-04-14 23:11:21 +00006268 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006269
Douglas Gregorcd695e52008-11-10 20:40:00 +00006270 // Look through all of the overloaded functions, searching for one
6271 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006272 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006273 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6274
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006275 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006276 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6277 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006278 // Look through any using declarations to find the underlying function.
6279 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6280
Douglas Gregorcd695e52008-11-10 20:40:00 +00006281 // C++ [over.over]p3:
6282 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006283 // targets of type "pointer-to-function" or "reference-to-function."
6284 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006285 // type "pointer-to-member-function."
6286 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006287
Mike Stump11289f42009-09-09 15:08:12 +00006288 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006289 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006290 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006291 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006292 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006293 // static when converting to member pointer.
6294 if (Method->isStatic() == IsMember)
6295 continue;
6296 } else if (IsMember)
6297 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006298
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006299 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006300 // If the name is a function template, template argument deduction is
6301 // done (14.8.2.2), and if the argument deduction succeeds, the
6302 // resulting template argument list is used to generate a single
6303 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006304 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006305 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006306 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006307 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006308 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006309 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006310 FunctionType, Specialization, Info)) {
6311 // FIXME: make a note of the failed deduction for diagnostics.
6312 (void)Result;
6313 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006314 // FIXME: If the match isn't exact, shouldn't we just drop this as
6315 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006316 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006317 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006318 Matches.push_back(std::make_pair(I.getPair(),
6319 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006320 }
John McCalld14a8642009-11-21 08:51:07 +00006321
6322 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006323 }
Mike Stump11289f42009-09-09 15:08:12 +00006324
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006325 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006326 // Skip non-static functions when converting to pointer, and static
6327 // when converting to member pointer.
6328 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006329 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006330
6331 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006332 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006333 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006334 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006335 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006336
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006337 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006338 QualType ResultTy;
6339 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6340 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6341 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006342 Matches.push_back(std::make_pair(I.getPair(),
6343 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006344 FoundNonTemplateFunction = true;
6345 }
Mike Stump11289f42009-09-09 15:08:12 +00006346 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006347 }
6348
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006349 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006350 if (Matches.empty()) {
6351 if (Complain) {
6352 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6353 << OvlExpr->getName() << FunctionType;
6354 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6355 E = OvlExpr->decls_end();
6356 I != E; ++I)
6357 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6358 NoteOverloadCandidate(F);
6359 }
6360
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006361 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006362 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006363 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006364 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006365 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006366 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006367 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006368 return Result;
6369 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006370
6371 // C++ [over.over]p4:
6372 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006373 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006374 // [...] and any given function template specialization F1 is
6375 // eliminated if the set contains a second function template
6376 // specialization whose function template is more specialized
6377 // than the function template of F1 according to the partial
6378 // ordering rules of 14.5.5.2.
6379
6380 // The algorithm specified above is quadratic. We instead use a
6381 // two-pass algorithm (similar to the one used to identify the
6382 // best viable function in an overload set) that identifies the
6383 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006384
6385 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6386 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6387 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006388
6389 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006390 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006391 TPOC_Other, From->getLocStart(),
6392 PDiag(),
6393 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006394 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006395 PDiag(diag::note_ovl_candidate)
6396 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006397 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006398 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006399 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006400 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006401 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006402 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6403 }
John McCall58cc69d2010-01-27 01:50:18 +00006404 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006405 }
Mike Stump11289f42009-09-09 15:08:12 +00006406
Douglas Gregorfae1d712009-09-26 03:56:17 +00006407 // [...] any function template specializations in the set are
6408 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006409 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006410 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006411 ++I;
6412 else {
John McCalla0296f72010-03-19 07:35:19 +00006413 Matches[I] = Matches[--N];
6414 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006415 }
6416 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006417
Mike Stump11289f42009-09-09 15:08:12 +00006418 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006419 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006420 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006421 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006422 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006423 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006424 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006425 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6426 }
John McCalla0296f72010-03-19 07:35:19 +00006427 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006428 }
Mike Stump11289f42009-09-09 15:08:12 +00006429
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006430 // FIXME: We should probably return the same thing that BestViableFunction
6431 // returns (even if we issue the diagnostics here).
6432 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006433 << Matches[0].second->getDeclName();
6434 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6435 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006436 return 0;
6437}
6438
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006439/// \brief Given an expression that refers to an overloaded function, try to
6440/// resolve that overloaded function expression down to a single function.
6441///
6442/// This routine can only resolve template-ids that refer to a single function
6443/// template, where that template-id refers to a single template whose template
6444/// arguments are either provided by the template-id or have defaults,
6445/// as described in C++0x [temp.arg.explicit]p3.
6446FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6447 // C++ [over.over]p1:
6448 // [...] [Note: any redundant set of parentheses surrounding the
6449 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006450 // C++ [over.over]p1:
6451 // [...] The overloaded function name can be preceded by the &
6452 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006453
6454 if (From->getType() != Context.OverloadTy)
6455 return 0;
6456
6457 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006458
6459 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006460 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006461 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006462
6463 TemplateArgumentListInfo ExplicitTemplateArgs;
6464 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006465
6466 // Look through all of the overloaded functions, searching for one
6467 // whose type matches exactly.
6468 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006469 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6470 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006471 // C++0x [temp.arg.explicit]p3:
6472 // [...] In contexts where deduction is done and fails, or in contexts
6473 // where deduction is not done, if a template argument list is
6474 // specified and it, along with any default template arguments,
6475 // identifies a single function template specialization, then the
6476 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006477 FunctionTemplateDecl *FunctionTemplate
6478 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006479
6480 // C++ [over.over]p2:
6481 // If the name is a function template, template argument deduction is
6482 // done (14.8.2.2), and if the argument deduction succeeds, the
6483 // resulting template argument list is used to generate a single
6484 // function template specialization, which is added to the set of
6485 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006486 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006487 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006488 if (TemplateDeductionResult Result
6489 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6490 Specialization, Info)) {
6491 // FIXME: make a note of the failed deduction for diagnostics.
6492 (void)Result;
6493 continue;
6494 }
6495
6496 // Multiple matches; we can't resolve to a single declaration.
6497 if (Matched)
6498 return 0;
6499
6500 Matched = Specialization;
6501 }
6502
6503 return Matched;
6504}
6505
Douglas Gregorcabea402009-09-22 15:41:20 +00006506/// \brief Add a single candidate to the overload set.
6507static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006508 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006509 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006510 Expr **Args, unsigned NumArgs,
6511 OverloadCandidateSet &CandidateSet,
6512 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006513 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006514 if (isa<UsingShadowDecl>(Callee))
6515 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6516
Douglas Gregorcabea402009-09-22 15:41:20 +00006517 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006518 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006519 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006520 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006521 return;
John McCalld14a8642009-11-21 08:51:07 +00006522 }
6523
6524 if (FunctionTemplateDecl *FuncTemplate
6525 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006526 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6527 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006528 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006529 return;
6530 }
6531
6532 assert(false && "unhandled case in overloaded call candidate");
6533
6534 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006535}
6536
6537/// \brief Add the overload candidates named by callee and/or found by argument
6538/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006539void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006540 Expr **Args, unsigned NumArgs,
6541 OverloadCandidateSet &CandidateSet,
6542 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006543
6544#ifndef NDEBUG
6545 // Verify that ArgumentDependentLookup is consistent with the rules
6546 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006547 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006548 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6549 // and let Y be the lookup set produced by argument dependent
6550 // lookup (defined as follows). If X contains
6551 //
6552 // -- a declaration of a class member, or
6553 //
6554 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006555 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006556 //
6557 // -- a declaration that is neither a function or a function
6558 // template
6559 //
6560 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006561
John McCall57500772009-12-16 12:17:52 +00006562 if (ULE->requiresADL()) {
6563 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6564 E = ULE->decls_end(); I != E; ++I) {
6565 assert(!(*I)->getDeclContext()->isRecord());
6566 assert(isa<UsingShadowDecl>(*I) ||
6567 !(*I)->getDeclContext()->isFunctionOrMethod());
6568 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006569 }
6570 }
6571#endif
6572
John McCall57500772009-12-16 12:17:52 +00006573 // It would be nice to avoid this copy.
6574 TemplateArgumentListInfo TABuffer;
6575 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6576 if (ULE->hasExplicitTemplateArgs()) {
6577 ULE->copyTemplateArgumentsInto(TABuffer);
6578 ExplicitTemplateArgs = &TABuffer;
6579 }
6580
6581 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6582 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006583 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006584 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006585 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006586
John McCall57500772009-12-16 12:17:52 +00006587 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006588 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6589 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006590 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006591 CandidateSet,
6592 PartialOverloading);
6593}
John McCalld681c392009-12-16 08:11:27 +00006594
6595/// Attempts to recover from a call where no functions were found.
6596///
6597/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006598static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006599BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006600 UnresolvedLookupExpr *ULE,
6601 SourceLocation LParenLoc,
6602 Expr **Args, unsigned NumArgs,
6603 SourceLocation *CommaLocs,
6604 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006605
6606 CXXScopeSpec SS;
6607 if (ULE->getQualifier()) {
6608 SS.setScopeRep(ULE->getQualifier());
6609 SS.setRange(ULE->getQualifierRange());
6610 }
6611
John McCall57500772009-12-16 12:17:52 +00006612 TemplateArgumentListInfo TABuffer;
6613 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6614 if (ULE->hasExplicitTemplateArgs()) {
6615 ULE->copyTemplateArgumentsInto(TABuffer);
6616 ExplicitTemplateArgs = &TABuffer;
6617 }
6618
John McCalld681c392009-12-16 08:11:27 +00006619 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6620 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006621 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006622 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006623
John McCall57500772009-12-16 12:17:52 +00006624 assert(!R.empty() && "lookup results empty despite recovery");
6625
6626 // Build an implicit member call if appropriate. Just drop the
6627 // casts and such from the call, we don't really care.
John McCalldadc5752010-08-24 06:29:42 +00006628 ExprResult NewFn = SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006629 if ((*R.begin())->isCXXClassMember())
6630 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6631 else if (ExplicitTemplateArgs)
6632 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6633 else
6634 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6635
6636 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006637 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006638
6639 // This shouldn't cause an infinite loop because we're giving it
6640 // an expression with non-empty lookup results, which should never
6641 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006642 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
John McCall37ad5512010-08-23 06:44:23 +00006643 Sema::MultiExprArg(SemaRef, Args, NumArgs),
John McCall57500772009-12-16 12:17:52 +00006644 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006645}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006646
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006647/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006648/// (which eventually refers to the declaration Func) and the call
6649/// arguments Args/NumArgs, attempt to resolve the function call down
6650/// to a specific function. If overload resolution succeeds, returns
6651/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006652/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006653/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006654ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006655Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006656 SourceLocation LParenLoc,
6657 Expr **Args, unsigned NumArgs,
6658 SourceLocation *CommaLocs,
6659 SourceLocation RParenLoc) {
6660#ifndef NDEBUG
6661 if (ULE->requiresADL()) {
6662 // To do ADL, we must have found an unqualified name.
6663 assert(!ULE->getQualifier() && "qualified name with ADL");
6664
6665 // We don't perform ADL for implicit declarations of builtins.
6666 // Verify that this was correctly set up.
6667 FunctionDecl *F;
6668 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6669 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6670 F->getBuiltinID() && F->isImplicit())
6671 assert(0 && "performing ADL for builtin");
6672
6673 // We don't perform ADL in C.
6674 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6675 }
6676#endif
6677
John McCallbc077cf2010-02-08 23:07:23 +00006678 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006679
John McCall57500772009-12-16 12:17:52 +00006680 // Add the functions denoted by the callee to the set of candidate
6681 // functions, including those from argument-dependent lookup.
6682 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006683
6684 // If we found nothing, try to recover.
6685 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6686 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006687 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006688 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006689 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006690
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006691 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006692 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006693 case OR_Success: {
6694 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006695 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006696 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006697 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006698 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6699 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006700
6701 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006702 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006703 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006704 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006705 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006706 break;
6707
6708 case OR_Ambiguous:
6709 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006710 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006711 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006712 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006713
6714 case OR_Deleted:
6715 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6716 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006717 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006718 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006720 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006721 }
6722
Douglas Gregorb412e172010-07-25 18:17:45 +00006723 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006724 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006725}
6726
John McCall4c4c1df2010-01-26 03:27:55 +00006727static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006728 return Functions.size() > 1 ||
6729 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6730}
6731
Douglas Gregor084d8552009-03-13 23:49:33 +00006732/// \brief Create a unary operation that may resolve to an overloaded
6733/// operator.
6734///
6735/// \param OpLoc The location of the operator itself (e.g., '*').
6736///
6737/// \param OpcIn The UnaryOperator::Opcode that describes this
6738/// operator.
6739///
6740/// \param Functions The set of non-member functions that will be
6741/// considered by overload resolution. The caller needs to build this
6742/// set based on the context using, e.g.,
6743/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6744/// set should not contain any member functions; those will be added
6745/// by CreateOverloadedUnaryOp().
6746///
6747/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00006748ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00006749Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6750 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00006751 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006752 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00006753
6754 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6755 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6756 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006757 // TODO: provide better source location info.
6758 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006759
6760 Expr *Args[2] = { Input, 0 };
6761 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006762
Douglas Gregor084d8552009-03-13 23:49:33 +00006763 // For post-increment and post-decrement, add the implicit '0' as
6764 // the second argument, so that we know this is a post-increment or
6765 // post-decrement.
6766 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6767 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006768 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006769 SourceLocation());
6770 NumArgs = 2;
6771 }
6772
6773 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006774 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00006775 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00006776 Opc,
6777 Context.DependentTy,
6778 OpLoc));
6779
John McCall58cc69d2010-01-27 01:50:18 +00006780 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006781 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006782 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006783 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006784 /*ADL*/ true, IsOverloaded(Fns),
6785 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006786 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6787 &Args[0], NumArgs,
6788 Context.DependentTy,
6789 OpLoc));
6790 }
6791
6792 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006793 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006794
6795 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006796 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006797
6798 // Add operator candidates that are member functions.
6799 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6800
John McCall4c4c1df2010-01-26 03:27:55 +00006801 // Add candidates from ADL.
6802 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006803 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006804 /*ExplicitTemplateArgs*/ 0,
6805 CandidateSet);
6806
Douglas Gregor084d8552009-03-13 23:49:33 +00006807 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006808 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006809
6810 // Perform overload resolution.
6811 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006812 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006813 case OR_Success: {
6814 // We found a built-in operator or an overloaded operator.
6815 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006816
Douglas Gregor084d8552009-03-13 23:49:33 +00006817 if (FnDecl) {
6818 // We matched an overloaded operator. Build a call to that
6819 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006820
Douglas Gregor084d8552009-03-13 23:49:33 +00006821 // Convert the arguments.
6822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006823 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006824
John McCall16df1e52010-03-30 21:47:33 +00006825 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6826 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006827 return ExprError();
6828 } else {
6829 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00006830 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00006831 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006832 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006833 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00006834 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00006835 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006836 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00006837 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00006838 }
6839
John McCall4fa0d5f2010-05-06 18:15:07 +00006840 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6841
Douglas Gregor084d8552009-03-13 23:49:33 +00006842 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006843 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006844
Douglas Gregor084d8552009-03-13 23:49:33 +00006845 // Build the actual expression node.
6846 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6847 SourceLocation());
6848 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006849
Eli Friedman030eee42009-11-18 03:58:17 +00006850 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00006851 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006852 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00006853 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00006854
John McCallb268a282010-08-23 23:25:46 +00006855 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006856 FnDecl))
6857 return ExprError();
6858
John McCallb268a282010-08-23 23:25:46 +00006859 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00006860 } else {
6861 // We matched a built-in operator. Convert the arguments, then
6862 // break out so that we will build the appropriate built-in
6863 // operator node.
6864 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006865 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006866 return ExprError();
6867
6868 break;
6869 }
6870 }
6871
6872 case OR_No_Viable_Function:
6873 // No viable function; fall through to handling this as a
6874 // built-in operator, which will produce an error message for us.
6875 break;
6876
6877 case OR_Ambiguous:
6878 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6879 << UnaryOperator::getOpcodeStr(Opc)
6880 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006881 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6882 Args, NumArgs,
6883 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006884 return ExprError();
6885
6886 case OR_Deleted:
6887 Diag(OpLoc, diag::err_ovl_deleted_oper)
6888 << Best->Function->isDeleted()
6889 << UnaryOperator::getOpcodeStr(Opc)
6890 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006891 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006892 return ExprError();
6893 }
6894
6895 // Either we found no viable overloaded operator or we matched a
6896 // built-in operator. In either case, fall through to trying to
6897 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00006898 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006899}
6900
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006901/// \brief Create a binary operation that may resolve to an overloaded
6902/// operator.
6903///
6904/// \param OpLoc The location of the operator itself (e.g., '+').
6905///
6906/// \param OpcIn The BinaryOperator::Opcode that describes this
6907/// operator.
6908///
6909/// \param Functions The set of non-member functions that will be
6910/// considered by overload resolution. The caller needs to build this
6911/// set based on the context using, e.g.,
6912/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6913/// set should not contain any member functions; those will be added
6914/// by CreateOverloadedBinOp().
6915///
6916/// \param LHS Left-hand argument.
6917/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00006918ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006919Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006920 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006921 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006922 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006923 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006924 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006925
6926 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6927 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6928 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6929
6930 // If either side is type-dependent, create an appropriate dependent
6931 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006932 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006933 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006934 // If there are no functions to store, just build a dependent
6935 // BinaryOperator or CompoundAssignment.
6936 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6937 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6938 Context.DependentTy, OpLoc));
6939
6940 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6941 Context.DependentTy,
6942 Context.DependentTy,
6943 Context.DependentTy,
6944 OpLoc));
6945 }
John McCall4c4c1df2010-01-26 03:27:55 +00006946
6947 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006948 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006949 // TODO: provide better source location info in DNLoc component.
6950 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006951 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006952 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006953 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006954 /*ADL*/ true, IsOverloaded(Fns),
6955 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006956 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006957 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006958 Context.DependentTy,
6959 OpLoc));
6960 }
6961
6962 // If this is the .* operator, which is not overloadable, just
6963 // create a built-in binary operator.
6964 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006965 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006966
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006967 // If this is the assignment operator, we only perform overload resolution
6968 // if the left-hand side is a class or enumeration type. This is actually
6969 // a hack. The standard requires that we do overload resolution between the
6970 // various built-in candidates, but as DR507 points out, this can lead to
6971 // problems. So we do it this way, which pretty much follows what GCC does.
6972 // Note that we go the traditional code path for compound assignment forms.
6973 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006974 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006975
Douglas Gregor084d8552009-03-13 23:49:33 +00006976 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006977 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006978
6979 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006980 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006981
6982 // Add operator candidates that are member functions.
6983 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6984
John McCall4c4c1df2010-01-26 03:27:55 +00006985 // Add candidates from ADL.
6986 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6987 Args, 2,
6988 /*ExplicitTemplateArgs*/ 0,
6989 CandidateSet);
6990
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006991 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006992 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006993
6994 // Perform overload resolution.
6995 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006996 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006997 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006998 // We found a built-in operator or an overloaded operator.
6999 FunctionDecl *FnDecl = Best->Function;
7000
7001 if (FnDecl) {
7002 // We matched an overloaded operator. Build a call to that
7003 // operator.
7004
7005 // Convert the arguments.
7006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007007 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007008 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007009
John McCalldadc5752010-08-24 06:29:42 +00007010 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007011 = PerformCopyInitialization(
7012 InitializedEntity::InitializeParameter(
7013 FnDecl->getParamDecl(0)),
7014 SourceLocation(),
7015 Owned(Args[1]));
7016 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007017 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007018
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007019 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007020 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007021 return ExprError();
7022
7023 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007024 } else {
7025 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007026 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007027 = PerformCopyInitialization(
7028 InitializedEntity::InitializeParameter(
7029 FnDecl->getParamDecl(0)),
7030 SourceLocation(),
7031 Owned(Args[0]));
7032 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007033 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007034
John McCalldadc5752010-08-24 06:29:42 +00007035 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007036 = PerformCopyInitialization(
7037 InitializedEntity::InitializeParameter(
7038 FnDecl->getParamDecl(1)),
7039 SourceLocation(),
7040 Owned(Args[1]));
7041 if (Arg1.isInvalid())
7042 return ExprError();
7043 Args[0] = LHS = Arg0.takeAs<Expr>();
7044 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007045 }
7046
John McCall4fa0d5f2010-05-06 18:15:07 +00007047 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7048
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007049 // Determine the result type
7050 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007051 = FnDecl->getType()->getAs<FunctionType>()
7052 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007053
7054 // Build the actual expression node.
7055 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00007056 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007057 UsualUnaryConversions(FnExpr);
7058
John McCallb268a282010-08-23 23:25:46 +00007059 CXXOperatorCallExpr *TheCall =
7060 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7061 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007062
John McCallb268a282010-08-23 23:25:46 +00007063 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007064 FnDecl))
7065 return ExprError();
7066
John McCallb268a282010-08-23 23:25:46 +00007067 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007068 } else {
7069 // We matched a built-in operator. Convert the arguments, then
7070 // break out so that we will build the appropriate built-in
7071 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007072 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007073 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007074 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007075 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007076 return ExprError();
7077
7078 break;
7079 }
7080 }
7081
Douglas Gregor66950a32009-09-30 21:46:01 +00007082 case OR_No_Viable_Function: {
7083 // C++ [over.match.oper]p9:
7084 // If the operator is the operator , [...] and there are no
7085 // viable functions, then the operator is assumed to be the
7086 // built-in operator and interpreted according to clause 5.
7087 if (Opc == BinaryOperator::Comma)
7088 break;
7089
Sebastian Redl027de2a2009-05-21 11:50:50 +00007090 // For class as left operand for assignment or compound assigment operator
7091 // do not fall through to handling in built-in, but report that no overloaded
7092 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007093 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007094 if (Args[0]->getType()->isRecordType() &&
7095 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007096 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7097 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007098 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007099 } else {
7100 // No viable function; try to create a built-in operation, which will
7101 // produce an error. Then, show the non-viable candidates.
7102 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007103 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007104 assert(Result.isInvalid() &&
7105 "C++ binary operator overloading is missing candidates!");
7106 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007107 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7108 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007109 return move(Result);
7110 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007111
7112 case OR_Ambiguous:
7113 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7114 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007115 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007116 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7117 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007118 return ExprError();
7119
7120 case OR_Deleted:
7121 Diag(OpLoc, diag::err_ovl_deleted_oper)
7122 << Best->Function->isDeleted()
7123 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007124 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007125 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007126 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007127 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007128
Douglas Gregor66950a32009-09-30 21:46:01 +00007129 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007130 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007131}
7132
John McCalldadc5752010-08-24 06:29:42 +00007133ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007134Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7135 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007136 Expr *Base, Expr *Idx) {
7137 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007138 DeclarationName OpName =
7139 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7140
7141 // If either side is type-dependent, create an appropriate dependent
7142 // expression.
7143 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7144
John McCall58cc69d2010-01-27 01:50:18 +00007145 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007146 // CHECKME: no 'operator' keyword?
7147 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7148 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007149 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007150 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007151 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007152 /*ADL*/ true, /*Overloaded*/ false,
7153 UnresolvedSetIterator(),
7154 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007155 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007156
Sebastian Redladba46e2009-10-29 20:17:01 +00007157 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7158 Args, 2,
7159 Context.DependentTy,
7160 RLoc));
7161 }
7162
7163 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007164 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007165
7166 // Subscript can only be overloaded as a member function.
7167
7168 // Add operator candidates that are member functions.
7169 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7170
7171 // Add builtin operator candidates.
7172 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7173
7174 // Perform overload resolution.
7175 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007176 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007177 case OR_Success: {
7178 // We found a built-in operator or an overloaded operator.
7179 FunctionDecl *FnDecl = Best->Function;
7180
7181 if (FnDecl) {
7182 // We matched an overloaded operator. Build a call to that
7183 // operator.
7184
John McCalla0296f72010-03-19 07:35:19 +00007185 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007186 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007187
Sebastian Redladba46e2009-10-29 20:17:01 +00007188 // Convert the arguments.
7189 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007190 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007191 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007192 return ExprError();
7193
Anders Carlssona68e51e2010-01-29 18:37:50 +00007194 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007195 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007196 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7197 FnDecl->getParamDecl(0)),
7198 SourceLocation(),
7199 Owned(Args[1]));
7200 if (InputInit.isInvalid())
7201 return ExprError();
7202
7203 Args[1] = InputInit.takeAs<Expr>();
7204
Sebastian Redladba46e2009-10-29 20:17:01 +00007205 // Determine the result type
7206 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007207 = FnDecl->getType()->getAs<FunctionType>()
7208 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007209
7210 // Build the actual expression node.
7211 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7212 LLoc);
7213 UsualUnaryConversions(FnExpr);
7214
John McCallb268a282010-08-23 23:25:46 +00007215 CXXOperatorCallExpr *TheCall =
7216 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7217 FnExpr, Args, 2,
7218 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007219
John McCallb268a282010-08-23 23:25:46 +00007220 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007221 FnDecl))
7222 return ExprError();
7223
John McCallb268a282010-08-23 23:25:46 +00007224 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007225 } else {
7226 // We matched a built-in operator. Convert the arguments, then
7227 // break out so that we will build the appropriate built-in
7228 // operator node.
7229 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007230 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007231 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007232 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007233 return ExprError();
7234
7235 break;
7236 }
7237 }
7238
7239 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007240 if (CandidateSet.empty())
7241 Diag(LLoc, diag::err_ovl_no_oper)
7242 << Args[0]->getType() << /*subscript*/ 0
7243 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7244 else
7245 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7246 << Args[0]->getType()
7247 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007248 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7249 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007250 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007251 }
7252
7253 case OR_Ambiguous:
7254 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7255 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007256 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7257 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007258 return ExprError();
7259
7260 case OR_Deleted:
7261 Diag(LLoc, diag::err_ovl_deleted_oper)
7262 << Best->Function->isDeleted() << "[]"
7263 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7265 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007266 return ExprError();
7267 }
7268
7269 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007270 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007271}
7272
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007273/// BuildCallToMemberFunction - Build a call to a member
7274/// function. MemExpr is the expression that refers to the member
7275/// function (and includes the object parameter), Args/NumArgs are the
7276/// arguments to the function call (not including the object
7277/// parameter). The caller needs to validate that the member
7278/// expression refers to a member function or an overloaded member
7279/// function.
John McCalldadc5752010-08-24 06:29:42 +00007280ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007281Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7282 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007283 unsigned NumArgs, SourceLocation *CommaLocs,
7284 SourceLocation RParenLoc) {
7285 // Dig out the member expression. This holds both the object
7286 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007287 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7288
John McCall10eae182009-11-30 22:42:35 +00007289 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007290 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007291 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007292 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007293 if (isa<MemberExpr>(NakedMemExpr)) {
7294 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007295 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007296 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007297 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007298 } else {
7299 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007300 Qualifier = UnresExpr->getQualifier();
7301
John McCall6e9f8f62009-12-03 04:06:58 +00007302 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007303
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007304 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007305 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007306
John McCall2d74de92009-12-01 22:10:20 +00007307 // FIXME: avoid copy.
7308 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7309 if (UnresExpr->hasExplicitTemplateArgs()) {
7310 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7311 TemplateArgs = &TemplateArgsBuffer;
7312 }
7313
John McCall10eae182009-11-30 22:42:35 +00007314 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7315 E = UnresExpr->decls_end(); I != E; ++I) {
7316
John McCall6e9f8f62009-12-03 04:06:58 +00007317 NamedDecl *Func = *I;
7318 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7319 if (isa<UsingShadowDecl>(Func))
7320 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7321
John McCall10eae182009-11-30 22:42:35 +00007322 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007323 // If explicit template arguments were provided, we can't call a
7324 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007325 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007326 continue;
7327
John McCalla0296f72010-03-19 07:35:19 +00007328 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007329 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007330 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007331 } else {
John McCall10eae182009-11-30 22:42:35 +00007332 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007333 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007334 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007335 CandidateSet,
7336 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007337 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007338 }
Mike Stump11289f42009-09-09 15:08:12 +00007339
John McCall10eae182009-11-30 22:42:35 +00007340 DeclarationName DeclName = UnresExpr->getMemberName();
7341
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007342 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007343 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7344 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007345 case OR_Success:
7346 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007347 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007348 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007349 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007350 break;
7351
7352 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007353 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007354 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007355 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007356 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007357 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007358 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007359
7360 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007361 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007362 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007363 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007364 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007365 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007366
7367 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007368 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007369 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007370 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007372 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007373 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007374 }
7375
John McCall16df1e52010-03-30 21:47:33 +00007376 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007377
John McCall2d74de92009-12-01 22:10:20 +00007378 // If overload resolution picked a static member, build a
7379 // non-member call based on that function.
7380 if (Method->isStatic()) {
7381 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7382 Args, NumArgs, RParenLoc);
7383 }
7384
John McCall10eae182009-11-30 22:42:35 +00007385 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007386 }
7387
7388 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007389 CXXMemberCallExpr *TheCall =
7390 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7391 Method->getCallResultType(),
7392 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007393
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007394 // Check for a valid return type.
7395 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007396 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007397 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007398
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007399 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007400 // We only need to do this if there was actually an overload; otherwise
7401 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007402 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007403 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007404 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7405 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007406 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007407 MemExpr->setBase(ObjectArg);
7408
7409 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007410 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007411 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007412 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007413 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007414
John McCallb268a282010-08-23 23:25:46 +00007415 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007416 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007417
John McCallb268a282010-08-23 23:25:46 +00007418 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007419}
7420
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007421/// BuildCallToObjectOfClassType - Build a call to an object of class
7422/// type (C++ [over.call.object]), which can end up invoking an
7423/// overloaded function call operator (@c operator()) or performing a
7424/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007425Sema::ExprResult
7426Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007427 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007428 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007429 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007430 SourceLocation RParenLoc) {
7431 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007432 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007433
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007434 // C++ [over.call.object]p1:
7435 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007436 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007437 // candidate functions includes at least the function call
7438 // operators of T. The function call operators of T are obtained by
7439 // ordinary lookup of the name operator() in the context of
7440 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007441 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007442 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007443
7444 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007445 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007446 << Object->getSourceRange()))
7447 return true;
7448
John McCall27b18f82009-11-17 02:14:36 +00007449 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7450 LookupQualifiedName(R, Record->getDecl());
7451 R.suppressDiagnostics();
7452
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007453 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007454 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007455 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007456 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007457 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007458 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007459
Douglas Gregorab7897a2008-11-19 22:57:39 +00007460 // C++ [over.call.object]p2:
7461 // In addition, for each conversion function declared in T of the
7462 // form
7463 //
7464 // operator conversion-type-id () cv-qualifier;
7465 //
7466 // where cv-qualifier is the same cv-qualification as, or a
7467 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007468 // denotes the type "pointer to function of (P1,...,Pn) returning
7469 // R", or the type "reference to pointer to function of
7470 // (P1,...,Pn) returning R", or the type "reference to function
7471 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007472 // is also considered as a candidate function. Similarly,
7473 // surrogate call functions are added to the set of candidate
7474 // functions for each conversion function declared in an
7475 // accessible base class provided the function is not hidden
7476 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007477 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007478 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007479 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007480 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007481 NamedDecl *D = *I;
7482 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7483 if (isa<UsingShadowDecl>(D))
7484 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7485
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007486 // Skip over templated conversion functions; they aren't
7487 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007488 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007489 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007490
John McCall6e9f8f62009-12-03 04:06:58 +00007491 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007492
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007493 // Strip the reference type (if any) and then the pointer type (if
7494 // any) to get down to what might be a function type.
7495 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7496 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7497 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007498
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007499 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007500 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007501 Object->getType(), Args, NumArgs,
7502 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007503 }
Mike Stump11289f42009-09-09 15:08:12 +00007504
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007505 // Perform overload resolution.
7506 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007507 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7508 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007509 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007510 // Overload resolution succeeded; we'll build the appropriate call
7511 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007512 break;
7513
7514 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007515 if (CandidateSet.empty())
7516 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7517 << Object->getType() << /*call*/ 1
7518 << Object->getSourceRange();
7519 else
7520 Diag(Object->getSourceRange().getBegin(),
7521 diag::err_ovl_no_viable_object_call)
7522 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007523 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007524 break;
7525
7526 case OR_Ambiguous:
7527 Diag(Object->getSourceRange().getBegin(),
7528 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007529 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007530 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007531 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007532
7533 case OR_Deleted:
7534 Diag(Object->getSourceRange().getBegin(),
7535 diag::err_ovl_deleted_object_call)
7536 << Best->Function->isDeleted()
7537 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007538 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007539 break;
Mike Stump11289f42009-09-09 15:08:12 +00007540 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007541
Douglas Gregorb412e172010-07-25 18:17:45 +00007542 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007543 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007544
Douglas Gregorab7897a2008-11-19 22:57:39 +00007545 if (Best->Function == 0) {
7546 // Since there is no function declaration, this is one of the
7547 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007548 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007549 = cast<CXXConversionDecl>(
7550 Best->Conversions[0].UserDefined.ConversionFunction);
7551
John McCalla0296f72010-03-19 07:35:19 +00007552 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007553 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007554
Douglas Gregorab7897a2008-11-19 22:57:39 +00007555 // We selected one of the surrogate functions that converts the
7556 // object parameter to a function pointer. Perform the conversion
7557 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007558
7559 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007560 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007561 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7562 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007563
John McCallb268a282010-08-23 23:25:46 +00007564 return ActOnCallExpr(S, CE, LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007565 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
John McCalle172be52010-08-24 06:09:16 +00007566 CommaLocs, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007567 }
7568
John McCalla0296f72010-03-19 07:35:19 +00007569 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007570 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007571
Douglas Gregorab7897a2008-11-19 22:57:39 +00007572 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7573 // that calls this method, using Object for the implicit object
7574 // parameter and passing along the remaining arguments.
7575 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007576 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007577
7578 unsigned NumArgsInProto = Proto->getNumArgs();
7579 unsigned NumArgsToCheck = NumArgs;
7580
7581 // Build the full argument list for the method call (the
7582 // implicit object parameter is placed at the beginning of the
7583 // list).
7584 Expr **MethodArgs;
7585 if (NumArgs < NumArgsInProto) {
7586 NumArgsToCheck = NumArgsInProto;
7587 MethodArgs = new Expr*[NumArgsInProto + 1];
7588 } else {
7589 MethodArgs = new Expr*[NumArgs + 1];
7590 }
7591 MethodArgs[0] = Object;
7592 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7593 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007594
7595 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007596 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007597 UsualUnaryConversions(NewFn);
7598
7599 // Once we've built TheCall, all of the expressions are properly
7600 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007601 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007602 CXXOperatorCallExpr *TheCall =
7603 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7604 MethodArgs, NumArgs + 1,
7605 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007606 delete [] MethodArgs;
7607
John McCallb268a282010-08-23 23:25:46 +00007608 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007609 Method))
7610 return true;
7611
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007612 // We may have default arguments. If so, we need to allocate more
7613 // slots in the call for them.
7614 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007615 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007616 else if (NumArgs > NumArgsInProto)
7617 NumArgsToCheck = NumArgsInProto;
7618
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007619 bool IsError = false;
7620
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007621 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007622 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007623 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007624 TheCall->setArg(0, Object);
7625
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007626
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007627 // Check the argument types.
7628 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007629 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007630 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007631 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007632
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007633 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007634
John McCalldadc5752010-08-24 06:29:42 +00007635 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007636 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7637 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007638 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007639
7640 IsError |= InputInit.isInvalid();
7641 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007642 } else {
John McCalldadc5752010-08-24 06:29:42 +00007643 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007644 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7645 if (DefArg.isInvalid()) {
7646 IsError = true;
7647 break;
7648 }
7649
7650 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007651 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007652
7653 TheCall->setArg(i + 1, Arg);
7654 }
7655
7656 // If this is a variadic call, handle args passed through "...".
7657 if (Proto->isVariadic()) {
7658 // Promote the arguments (C99 6.5.2.2p7).
7659 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7660 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007661 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007662 TheCall->setArg(i + 1, Arg);
7663 }
7664 }
7665
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007666 if (IsError) return true;
7667
John McCallb268a282010-08-23 23:25:46 +00007668 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007669 return true;
7670
John McCalle172be52010-08-24 06:09:16 +00007671 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007672}
7673
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007674/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007675/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007676/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007677ExprResult
John McCallb268a282010-08-23 23:25:46 +00007678Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007679 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007680
John McCallbc077cf2010-02-08 23:07:23 +00007681 SourceLocation Loc = Base->getExprLoc();
7682
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007683 // C++ [over.ref]p1:
7684 //
7685 // [...] An expression x->m is interpreted as (x.operator->())->m
7686 // for a class object x of type T if T::operator->() exists and if
7687 // the operator is selected as the best match function by the
7688 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007689 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007690 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007691 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007692
John McCallbc077cf2010-02-08 23:07:23 +00007693 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007694 PDiag(diag::err_typecheck_incomplete_tag)
7695 << Base->getSourceRange()))
7696 return ExprError();
7697
John McCall27b18f82009-11-17 02:14:36 +00007698 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7699 LookupQualifiedName(R, BaseRecord->getDecl());
7700 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007701
7702 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007703 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007704 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007705 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007706 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007707
7708 // Perform overload resolution.
7709 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007710 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007711 case OR_Success:
7712 // Overload resolution succeeded; we'll build the call below.
7713 break;
7714
7715 case OR_No_Viable_Function:
7716 if (CandidateSet.empty())
7717 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007718 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007719 else
7720 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007721 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007722 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007723 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007724
7725 case OR_Ambiguous:
7726 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007727 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007728 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007729 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007730
7731 case OR_Deleted:
7732 Diag(OpLoc, diag::err_ovl_deleted_oper)
7733 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007734 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007735 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007736 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007737 }
7738
John McCalla0296f72010-03-19 07:35:19 +00007739 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007740 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007741
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007742 // Convert the object parameter.
7743 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007744 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7745 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007746 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007747
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007748 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007749 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7750 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007751 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007752
Douglas Gregor603d81b2010-07-13 08:18:22 +00007753 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007754 CXXOperatorCallExpr *TheCall =
7755 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7756 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007757
John McCallb268a282010-08-23 23:25:46 +00007758 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007759 Method))
7760 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007761 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007762}
7763
Douglas Gregorcd695e52008-11-10 20:40:00 +00007764/// FixOverloadedFunctionReference - E is an expression that refers to
7765/// a C++ overloaded function (possibly with some parentheses and
7766/// perhaps a '&' around it). We have resolved the overloaded function
7767/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007768/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007769Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007770 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007771 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007772 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7773 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007774 if (SubExpr == PE->getSubExpr())
7775 return PE->Retain();
7776
7777 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7778 }
7779
7780 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007781 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7782 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007783 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007784 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007785 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007786 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007787 if (SubExpr == ICE->getSubExpr())
7788 return ICE->Retain();
7789
John McCallcf142162010-08-07 06:22:56 +00007790 return ImplicitCastExpr::Create(Context, ICE->getType(),
7791 ICE->getCastKind(),
7792 SubExpr, 0,
7793 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007794 }
7795
7796 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007797 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007798 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007799 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7800 if (Method->isStatic()) {
7801 // Do nothing: static member functions aren't any different
7802 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007803 } else {
John McCalle66edc12009-11-24 19:00:30 +00007804 // Fix the sub expression, which really has to be an
7805 // UnresolvedLookupExpr holding an overloaded member function
7806 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007807 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7808 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007809 if (SubExpr == UnOp->getSubExpr())
7810 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007811
John McCalld14a8642009-11-21 08:51:07 +00007812 assert(isa<DeclRefExpr>(SubExpr)
7813 && "fixed to something other than a decl ref");
7814 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7815 && "fixed to a member ref with no nested name qualifier");
7816
7817 // We have taken the address of a pointer to member
7818 // function. Perform the computation here so that we get the
7819 // appropriate pointer to member type.
7820 QualType ClassType
7821 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7822 QualType MemPtrType
7823 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7824
7825 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7826 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007827 }
7828 }
John McCall16df1e52010-03-30 21:47:33 +00007829 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7830 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007831 if (SubExpr == UnOp->getSubExpr())
7832 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007833
Douglas Gregor51c538b2009-11-20 19:42:02 +00007834 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7835 Context.getPointerType(SubExpr->getType()),
7836 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007837 }
John McCalld14a8642009-11-21 08:51:07 +00007838
7839 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007840 // FIXME: avoid copy.
7841 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007842 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007843 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7844 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007845 }
7846
John McCalld14a8642009-11-21 08:51:07 +00007847 return DeclRefExpr::Create(Context,
7848 ULE->getQualifier(),
7849 ULE->getQualifierRange(),
7850 Fn,
7851 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007852 Fn->getType(),
7853 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007854 }
7855
John McCall10eae182009-11-30 22:42:35 +00007856 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007857 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007858 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7859 if (MemExpr->hasExplicitTemplateArgs()) {
7860 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7861 TemplateArgs = &TemplateArgsBuffer;
7862 }
John McCall6b51f282009-11-23 01:53:49 +00007863
John McCall2d74de92009-12-01 22:10:20 +00007864 Expr *Base;
7865
7866 // If we're filling in
7867 if (MemExpr->isImplicitAccess()) {
7868 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7869 return DeclRefExpr::Create(Context,
7870 MemExpr->getQualifier(),
7871 MemExpr->getQualifierRange(),
7872 Fn,
7873 MemExpr->getMemberLoc(),
7874 Fn->getType(),
7875 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007876 } else {
7877 SourceLocation Loc = MemExpr->getMemberLoc();
7878 if (MemExpr->getQualifier())
7879 Loc = MemExpr->getQualifierRange().getBegin();
7880 Base = new (Context) CXXThisExpr(Loc,
7881 MemExpr->getBaseType(),
7882 /*isImplicit=*/true);
7883 }
John McCall2d74de92009-12-01 22:10:20 +00007884 } else
7885 Base = MemExpr->getBase()->Retain();
7886
7887 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007888 MemExpr->isArrow(),
7889 MemExpr->getQualifier(),
7890 MemExpr->getQualifierRange(),
7891 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007892 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007893 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007894 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007895 Fn->getType());
7896 }
7897
Douglas Gregor51c538b2009-11-20 19:42:02 +00007898 assert(false && "Invalid reference to overloaded function");
7899 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007900}
7901
John McCalldadc5752010-08-24 06:29:42 +00007902ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7903 DeclAccessPair Found,
7904 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007905 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007906}
7907
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007908} // end namespace clang