blob: 266da4e264264080d2afb3e800a4fedb13947244 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall5c32be02010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS);
50static OverloadingResult
51IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
52 UserDefinedConversionSequence& User,
53 OverloadCandidateSet& Conversions,
54 bool AllowExplicit);
55
56
57static ImplicitConversionSequence::CompareKind
58CompareStandardConversionSequences(Sema &S,
59 const StandardConversionSequence& SCS1,
60 const StandardConversionSequence& SCS2);
61
62static ImplicitConversionSequence::CompareKind
63CompareQualificationConversions(Sema &S,
64 const StandardConversionSequence& SCS1,
65 const StandardConversionSequence& SCS2);
66
67static ImplicitConversionSequence::CompareKind
68CompareDerivedToBaseConversions(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72
73
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074/// GetConversionCategory - Retrieve the implicit conversion
75/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000076ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077GetConversionCategory(ImplicitConversionKind Kind) {
78 static const ImplicitConversionCategory
79 Category[(int)ICK_Num_Conversion_Kinds] = {
80 ICC_Identity,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000084 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 ICC_Qualification_Adjustment,
86 ICC_Promotion,
87 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000088 ICC_Promotion,
89 ICC_Conversion,
90 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000096 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000097 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000098 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion
101 };
102 return Category[(int)Kind];
103}
104
105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
107ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000130 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000131 };
132 return Rank[(int)Kind];
133}
134
135/// GetImplicitConversionName - Return the name of this kind of
136/// implicit conversion.
137const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000138 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 "No conversion",
140 "Lvalue-to-rvalue",
141 "Array-to-pointer",
142 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000143 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 "Qualification",
145 "Integral promotion",
146 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000147 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 "Integral conversion",
149 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Floating-integral conversion",
152 "Pointer conversion",
153 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000154 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000155 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000156 "Derived-to-base conversion",
157 "Vector conversion",
158 "Vector splat",
159 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 };
161 return Name[Kind];
162}
163
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164/// StandardConversionSequence - Set the standard conversion
165/// sequence to the identity conversion.
166void StandardConversionSequence::setAsIdentityConversion() {
167 First = ICK_Identity;
168 Second = ICK_Identity;
169 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000170 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000171 ReferenceBinding = false;
172 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000173 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000174 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000175}
176
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000177/// getRank - Retrieve the rank of this standard conversion sequence
178/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
179/// implicit conversions.
180ImplicitConversionRank StandardConversionSequence::getRank() const {
181 ImplicitConversionRank Rank = ICR_Exact_Match;
182 if (GetConversionRank(First) > Rank)
183 Rank = GetConversionRank(First);
184 if (GetConversionRank(Second) > Rank)
185 Rank = GetConversionRank(Second);
186 if (GetConversionRank(Third) > Rank)
187 Rank = GetConversionRank(Third);
188 return Rank;
189}
190
191/// isPointerConversionToBool - Determines whether this conversion is
192/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000193/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000195bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000196 // Note that FromType has not necessarily been transformed by the
197 // array-to-pointer or function-to-pointer implicit conversions, so
198 // check for their presence as well as checking whether FromType is
199 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000200 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000201 (getFromType()->isPointerType() ||
202 getFromType()->isObjCObjectPointerType() ||
203 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000204 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
206 return true;
207
208 return false;
209}
210
Douglas Gregor5c407d92008-10-23 00:40:37 +0000211/// isPointerConversionToVoidPointer - Determines whether this
212/// conversion is a conversion of a pointer to a void pointer. This is
213/// used as part of the ranking of standard conversion sequences (C++
214/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000215bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000216StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000217isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000218 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000219 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000220
221 // Note that FromType has not necessarily been transformed by the
222 // array-to-pointer implicit conversion, so check for its presence
223 // and redo the conversion to get a pointer.
224 if (First == ICK_Array_To_Pointer)
225 FromType = Context.getArrayDecayedType(FromType);
226
John McCall75851b12010-10-26 06:40:27 +0000227 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000228 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000229 return ToPtrType->getPointeeType()->isVoidType();
230
231 return false;
232}
233
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234/// DebugPrint - Print this standard conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000237 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 bool PrintedSomething = false;
239 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000240 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000241 PrintedSomething = true;
242 }
243
244 if (Second != ICK_Identity) {
245 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000248 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000249
250 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000251 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000252 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000254 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000255 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000256 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Third != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000269 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000270 }
271}
272
273/// DebugPrint - Print this user-defined conversion sequence to standard
274/// error. Useful for debugging overloading issues.
275void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000276 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277 if (Before.First || Before.Second || Before.Third) {
278 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000280 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000281 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000282 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 After.DebugPrint();
285 }
286}
287
288/// DebugPrint - Print this implicit conversion sequence to standard
289/// error. Useful for debugging overloading issues.
290void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 switch (ConversionKind) {
293 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000294 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000295 Standard.DebugPrint();
296 break;
297 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000298 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299 UserDefined.DebugPrint();
300 break;
301 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000302 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000303 break;
John McCall0d1da222010-01-12 00:44:57 +0000304 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000305 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000306 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000308 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 break;
310 }
311
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000312 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000313}
314
John McCall0d1da222010-01-12 00:44:57 +0000315void AmbiguousConversionSequence::construct() {
316 new (&conversions()) ConversionSet();
317}
318
319void AmbiguousConversionSequence::destruct() {
320 conversions().~ConversionSet();
321}
322
323void
324AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
325 FromTypePtr = O.FromTypePtr;
326 ToTypePtr = O.ToTypePtr;
327 new (&conversions()) ConversionSet(O.conversions());
328}
329
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000330namespace {
331 // Structure used by OverloadCandidate::DeductionFailureInfo to store
332 // template parameter and template argument information.
333 struct DFIParamWithArguments {
334 TemplateParameter Param;
335 TemplateArgument FirstArg;
336 TemplateArgument SecondArg;
337 };
338}
339
340/// \brief Convert from Sema's representation of template deduction information
341/// to the form used in overload-candidate information.
342OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000343static MakeDeductionFailureInfo(ASTContext &Context,
344 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000345 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346 OverloadCandidate::DeductionFailureInfo Result;
347 Result.Result = static_cast<unsigned>(TDK);
348 Result.Data = 0;
349 switch (TDK) {
350 case Sema::TDK_Success:
351 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000352 case Sema::TDK_TooManyArguments:
353 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354 break;
355
356 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000357 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358 Result.Data = Info.Param.getOpaqueValue();
359 break;
360
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000361 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000362 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000363 // FIXME: Should allocate from normal heap so that we can free this later.
364 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 Saved->Param = Info.Param;
366 Saved->FirstArg = Info.FirstArg;
367 Saved->SecondArg = Info.SecondArg;
368 Result.Data = Saved;
369 break;
370 }
371
372 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000373 Result.Data = Info.take();
374 break;
375
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000377 case Sema::TDK_FailedOverloadResolution:
378 break;
379 }
380
381 return Result;
382}
John McCall0d1da222010-01-12 00:44:57 +0000383
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384void OverloadCandidate::DeductionFailureInfo::Destroy() {
385 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
386 case Sema::TDK_Success:
387 case Sema::TDK_InstantiationDepth:
388 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000389 case Sema::TDK_TooManyArguments:
390 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000391 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 break;
393
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000395 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000396 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000397 Data = 0;
398 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000399
400 case Sema::TDK_SubstitutionFailure:
401 // FIXME: Destroy the template arugment list?
402 Data = 0;
403 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000404
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
408 break;
409 }
410}
411
412TemplateParameter
413OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
414 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
415 case Sema::TDK_Success:
416 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000417 case Sema::TDK_TooManyArguments:
418 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000419 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 return TemplateParameter();
421
422 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000423 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 return TemplateParameter::getFromOpaqueValue(Data);
425
426 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000427 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000428 return static_cast<DFIParamWithArguments*>(Data)->Param;
429
430 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000432 case Sema::TDK_FailedOverloadResolution:
433 break;
434 }
435
436 return TemplateParameter();
437}
Douglas Gregord09efd42010-05-08 20:07:26 +0000438
439TemplateArgumentList *
440OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
441 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
442 case Sema::TDK_Success:
443 case Sema::TDK_InstantiationDepth:
444 case Sema::TDK_TooManyArguments:
445 case Sema::TDK_TooFewArguments:
446 case Sema::TDK_Incomplete:
447 case Sema::TDK_InvalidExplicitArguments:
448 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000449 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000450 return 0;
451
452 case Sema::TDK_SubstitutionFailure:
453 return static_cast<TemplateArgumentList*>(Data);
454
455 // Unhandled
456 case Sema::TDK_NonDeducedMismatch:
457 case Sema::TDK_FailedOverloadResolution:
458 break;
459 }
460
461 return 0;
462}
463
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000464const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000469 case Sema::TDK_TooManyArguments:
470 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000471 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000472 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000473 return 0;
474
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000475 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000476 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000477 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
478
Douglas Gregor461761d2010-05-08 18:20:53 +0000479 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000480 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
488const TemplateArgument *
489OverloadCandidate::DeductionFailureInfo::getSecondArg() {
490 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
491 case Sema::TDK_Success:
492 case Sema::TDK_InstantiationDepth:
493 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000494 case Sema::TDK_TooManyArguments:
495 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000496 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000497 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000498 return 0;
499
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000500 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000501 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
503
Douglas Gregor461761d2010-05-08 18:20:53 +0000504 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000506 case Sema::TDK_FailedOverloadResolution:
507 break;
508 }
509
510 return 0;
511}
512
513void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 inherited::clear();
515 Functions.clear();
516}
517
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000519// overload of the declarations in Old. This routine returns false if
520// New and Old cannot be overloaded, e.g., if New has the same
521// signature as some function in Old (C++ 1.3.10) or if the Old
522// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000523// it does return false, MatchedDecl will point to the decl that New
524// cannot be overloaded with. This decl may be a UsingShadowDecl on
525// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000526//
527// Example: Given the following input:
528//
529// void f(int, float); // #1
530// void f(int, int); // #2
531// int f(int, int); // #3
532//
533// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000534// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000535//
John McCall3d988d92009-12-02 08:47:38 +0000536// When we process #2, Old contains only the FunctionDecl for #1. By
537// comparing the parameter types, we see that #1 and #2 are overloaded
538// (since they have different signatures), so this routine returns
539// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540//
John McCall3d988d92009-12-02 08:47:38 +0000541// When we process #3, Old is an overload set containing #1 and #2. We
542// compare the signatures of #3 to #1 (they're overloaded, so we do
543// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
544// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545// signature), IsOverload returns false and MatchedDecl will be set to
546// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000547//
548// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
549// into a class by a using declaration. The rules for whether to hide
550// shadow declarations ignore some properties which otherwise figure
551// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000552Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000553Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
554 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000555 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000556 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000557 NamedDecl *OldD = *I;
558
559 bool OldIsUsingDecl = false;
560 if (isa<UsingShadowDecl>(OldD)) {
561 OldIsUsingDecl = true;
562
563 // We can always introduce two using declarations into the same
564 // context, even if they have identical signatures.
565 if (NewIsUsingDecl) continue;
566
567 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
568 }
569
570 // If either declaration was introduced by a using declaration,
571 // we'll need to use slightly different rules for matching.
572 // Essentially, these rules are the normal rules, except that
573 // function templates hide function templates with different
574 // return types or template parameter lists.
575 bool UseMemberUsingDeclRules =
576 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
577
John McCall3d988d92009-12-02 08:47:38 +0000578 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000579 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
580 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
581 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
582 continue;
583 }
584
John McCalldaa3d6b2009-12-09 03:35:25 +0000585 Match = *I;
586 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000587 }
John McCall3d988d92009-12-02 08:47:38 +0000588 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000589 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
590 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
591 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
592 continue;
593 }
594
John McCalldaa3d6b2009-12-09 03:35:25 +0000595 Match = *I;
596 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000597 }
John McCalla8987a2942010-11-10 03:01:53 +0000598 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000599 // We can overload with these, which can show up when doing
600 // redeclaration checks for UsingDecls.
601 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000602 } else if (isa<TagDecl>(OldD)) {
603 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000604 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
605 // Optimistically assume that an unresolved using decl will
606 // overload; if it doesn't, we'll have to diagnose during
607 // template instantiation.
608 } else {
John McCall1f82f242009-11-18 22:49:29 +0000609 // (C++ 13p1):
610 // Only function declarations can be overloaded; object and type
611 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000612 Match = *I;
613 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000614 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000615 }
John McCall1f82f242009-11-18 22:49:29 +0000616
John McCalldaa3d6b2009-12-09 03:35:25 +0000617 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000618}
619
John McCalle9cccd82010-06-16 08:42:20 +0000620bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
621 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000622 // If both of the functions are extern "C", then they are not
623 // overloads.
624 if (Old->isExternC() && New->isExternC())
625 return false;
626
John McCall1f82f242009-11-18 22:49:29 +0000627 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
628 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
629
630 // C++ [temp.fct]p2:
631 // A function template can be overloaded with other function templates
632 // and with normal (non-template) functions.
633 if ((OldTemplate == 0) != (NewTemplate == 0))
634 return true;
635
636 // Is the function New an overload of the function Old?
637 QualType OldQType = Context.getCanonicalType(Old->getType());
638 QualType NewQType = Context.getCanonicalType(New->getType());
639
640 // Compare the signatures (C++ 1.3.10) of the two functions to
641 // determine whether they are overloads. If we find any mismatch
642 // in the signature, they are overloads.
643
644 // If either of these functions is a K&R-style function (no
645 // prototype), then we consider them to have matching signatures.
646 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
647 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
648 return false;
649
650 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
651 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
652
653 // The signature of a function includes the types of its
654 // parameters (C++ 1.3.10), which includes the presence or absence
655 // of the ellipsis; see C++ DR 357).
656 if (OldQType != NewQType &&
657 (OldType->getNumArgs() != NewType->getNumArgs() ||
658 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000659 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000660 return true;
661
662 // C++ [temp.over.link]p4:
663 // The signature of a function template consists of its function
664 // signature, its return type and its template parameter list. The names
665 // of the template parameters are significant only for establishing the
666 // relationship between the template parameters and the rest of the
667 // signature.
668 //
669 // We check the return type and template parameter lists for function
670 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000671 //
672 // However, we don't consider either of these when deciding whether
673 // a member introduced by a shadow declaration is hidden.
674 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000675 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
676 OldTemplate->getTemplateParameters(),
677 false, TPL_TemplateMatch) ||
678 OldType->getResultType() != NewType->getResultType()))
679 return true;
680
681 // If the function is a class member, its signature includes the
682 // cv-qualifiers (if any) on the function itself.
683 //
684 // As part of this, also check whether one of the member functions
685 // is static, in which case they are not overloads (C++
686 // 13.1p2). While not part of the definition of the signature,
687 // this check is important to determine whether these functions
688 // can be overloaded.
689 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
690 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
691 if (OldMethod && NewMethod &&
692 !OldMethod->isStatic() && !NewMethod->isStatic() &&
693 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
694 return true;
695
696 // The signatures match; this is not an overload.
697 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000698}
699
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000700/// TryImplicitConversion - Attempt to perform an implicit conversion
701/// from the given expression (Expr) to the given type (ToType). This
702/// function returns an implicit conversion sequence that can be used
703/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000704///
705/// void f(float f);
706/// void g(int i) { f(i); }
707///
708/// this routine would produce an implicit conversion sequence to
709/// describe the initialization of f from i, which will be a standard
710/// conversion sequence containing an lvalue-to-rvalue conversion (C++
711/// 4.1) followed by a floating-integral conversion (C++ 4.9).
712//
713/// Note that this routine only determines how the conversion can be
714/// performed; it does not actually perform the conversion. As such,
715/// it will not produce any diagnostics if no conversion is available,
716/// but will instead return an implicit conversion sequence of kind
717/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000718///
719/// If @p SuppressUserConversions, then user-defined conversions are
720/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000721/// If @p AllowExplicit, then explicit user-defined conversions are
722/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000723static ImplicitConversionSequence
724TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
725 bool SuppressUserConversions,
726 bool AllowExplicit,
727 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000728 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000729 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
730 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000731 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000732 return ICS;
733 }
734
John McCall5c32be02010-08-24 20:38:10 +0000735 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000736 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000737 return ICS;
738 }
739
Douglas Gregor836a7e82010-08-11 02:15:33 +0000740 // C++ [over.ics.user]p4:
741 // A conversion of an expression of class type to the same class
742 // type is given Exact Match rank, and a conversion of an
743 // expression of class type to a base class of that type is
744 // given Conversion rank, in spite of the fact that a copy/move
745 // constructor (i.e., a user-defined conversion function) is
746 // called for those cases.
747 QualType FromType = From->getType();
748 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000749 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
750 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000751 ICS.setStandard();
752 ICS.Standard.setAsIdentityConversion();
753 ICS.Standard.setFromType(FromType);
754 ICS.Standard.setAllToTypes(ToType);
755
756 // We don't actually check at this point whether there is a valid
757 // copy/move constructor, since overloading just assumes that it
758 // exists. When we actually perform initialization, we'll find the
759 // appropriate constructor to copy the returned object, if needed.
760 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000761
Douglas Gregor5ab11652010-04-17 22:01:05 +0000762 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000763 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000764 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000765
766 return ICS;
767 }
768
769 if (SuppressUserConversions) {
770 // We're not in the case above, so there is no conversion that
771 // we can perform.
772 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000773 return ICS;
774 }
775
776 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000777 OverloadCandidateSet Conversions(From->getExprLoc());
778 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000779 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000780 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000781
782 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000783 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000784 // C++ [over.ics.user]p4:
785 // A conversion of an expression of class type to the same class
786 // type is given Exact Match rank, and a conversion of an
787 // expression of class type to a base class of that type is
788 // given Conversion rank, in spite of the fact that a copy
789 // constructor (i.e., a user-defined conversion function) is
790 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000791 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000792 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000793 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000794 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
795 QualType ToCanon
796 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000797 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000798 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000799 // Turn this into a "standard" conversion sequence, so that it
800 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000801 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000802 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000803 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000804 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000805 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000806 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000807 ICS.Standard.Second = ICK_Derived_To_Base;
808 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000809 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000810
811 // C++ [over.best.ics]p4:
812 // However, when considering the argument of a user-defined
813 // conversion function that is a candidate by 13.3.1.3 when
814 // invoked for the copying of the temporary in the second step
815 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
816 // 13.3.1.6 in all cases, only standard conversion sequences and
817 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000818 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000820 }
John McCalle8c8cd22010-01-13 22:30:33 +0000821 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000822 ICS.setAmbiguous();
823 ICS.Ambiguous.setFromType(From->getType());
824 ICS.Ambiguous.setToType(ToType);
825 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
826 Cand != Conversions.end(); ++Cand)
827 if (Cand->Viable)
828 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000829 } else {
John McCall65eb8792010-02-25 01:37:24 +0000830 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000831 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000832
833 return ICS;
834}
835
John McCall5c32be02010-08-24 20:38:10 +0000836bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
837 const InitializedEntity &Entity,
838 Expr *Initializer,
839 bool SuppressUserConversions,
840 bool AllowExplicitConversions,
841 bool InOverloadResolution) {
842 ImplicitConversionSequence ICS
843 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
844 SuppressUserConversions,
845 AllowExplicitConversions,
846 InOverloadResolution);
847 if (ICS.isBad()) return true;
848
849 // Perform the actual conversion.
850 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
851 return false;
852}
853
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000854/// PerformImplicitConversion - Perform an implicit conversion of the
855/// expression From to the type ToType. Returns true if there was an
856/// error, false otherwise. The expression From is replaced with the
857/// converted expression. Flavor is the kind of conversion we're
858/// performing, used in the error message. If @p AllowExplicit,
859/// explicit user-defined conversions are permitted.
860bool
861Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
862 AssignmentAction Action, bool AllowExplicit) {
863 ImplicitConversionSequence ICS;
864 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
865}
866
867bool
868Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
869 AssignmentAction Action, bool AllowExplicit,
870 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000871 ICS = clang::TryImplicitConversion(*this, From, ToType,
872 /*SuppressUserConversions=*/false,
873 AllowExplicit,
874 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000875 return PerformImplicitConversion(From, ToType, ICS, Action);
876}
877
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000878/// \brief Determine whether the conversion from FromType to ToType is a valid
879/// conversion that strips "noreturn" off the nested function type.
880static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
881 QualType ToType, QualType &ResultTy) {
882 if (Context.hasSameUnqualifiedType(FromType, ToType))
883 return false;
884
885 // Strip the noreturn off the type we're converting from; noreturn can
886 // safely be removed.
887 FromType = Context.getNoReturnType(FromType, false);
888 if (!Context.hasSameUnqualifiedType(FromType, ToType))
889 return false;
890
891 ResultTy = FromType;
892 return true;
893}
Douglas Gregor46188682010-05-18 22:42:18 +0000894
895/// \brief Determine whether the conversion from FromType to ToType is a valid
896/// vector conversion.
897///
898/// \param ICK Will be set to the vector conversion kind, if this is a vector
899/// conversion.
900static bool IsVectorConversion(ASTContext &Context, QualType FromType,
901 QualType ToType, ImplicitConversionKind &ICK) {
902 // We need at least one of these types to be a vector type to have a vector
903 // conversion.
904 if (!ToType->isVectorType() && !FromType->isVectorType())
905 return false;
906
907 // Identical types require no conversions.
908 if (Context.hasSameUnqualifiedType(FromType, ToType))
909 return false;
910
911 // There are no conversions between extended vector types, only identity.
912 if (ToType->isExtVectorType()) {
913 // There are no conversions between extended vector types other than the
914 // identity conversion.
915 if (FromType->isExtVectorType())
916 return false;
917
918 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000919 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000920 ICK = ICK_Vector_Splat;
921 return true;
922 }
923 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000924
925 // We can perform the conversion between vector types in the following cases:
926 // 1)vector types are equivalent AltiVec and GCC vector types
927 // 2)lax vector conversions are permitted and the vector types are of the
928 // same size
929 if (ToType->isVectorType() && FromType->isVectorType()) {
930 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000931 (Context.getLangOptions().LaxVectorConversions &&
932 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000933 ICK = ICK_Vector_Conversion;
934 return true;
935 }
Douglas Gregor46188682010-05-18 22:42:18 +0000936 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000937
Douglas Gregor46188682010-05-18 22:42:18 +0000938 return false;
939}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000940
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000941/// IsStandardConversion - Determines whether there is a standard
942/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
943/// expression From to the type ToType. Standard conversion sequences
944/// only consider non-class types; for conversions that involve class
945/// types, use TryImplicitConversion. If a conversion exists, SCS will
946/// contain the standard conversion sequence required to perform this
947/// conversion and this routine will return true. Otherwise, this
948/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000949static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
950 bool InOverloadResolution,
951 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000952 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000953
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000954 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000955 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000956 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000957 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000958 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000959 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000960
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000961 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000962 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000963 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000964 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000965 return false;
966
Mike Stump11289f42009-09-09 15:08:12 +0000967 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000968 }
969
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000970 // The first conversion can be an lvalue-to-rvalue conversion,
971 // array-to-pointer conversion, or function-to-pointer conversion
972 // (C++ 4p1).
973
John McCall5c32be02010-08-24 20:38:10 +0000974 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000975 DeclAccessPair AccessPair;
976 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000977 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
978 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000979 // We were able to resolve the address of the overloaded function,
980 // so we can convert to the type of that function.
981 FromType = Fn->getType();
982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
983 if (!Method->isStatic()) {
984 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000985 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
986 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000987 }
988 }
989
990 // If the "from" expression takes the address of the overloaded
991 // function, update the type of the resulting expression accordingly.
992 if (FromType->getAs<FunctionType>())
993 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000994 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000995 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000996
997 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000998 assert(S.Context.hasSameType(FromType,
999 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001000 } else {
1001 return false;
1002 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005 // An lvalue (3.10) of a non-function, non-array type T can be
1006 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001007 bool argIsLValue = From->isLValue();
1008 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001009 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001010 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001011 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012
1013 // If T is a non-class type, the type of the rvalue is the
1014 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001015 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1016 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001017 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001018 } else if (FromType->isArrayType()) {
1019 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001020 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001021
1022 // An lvalue or rvalue of type "array of N T" or "array of unknown
1023 // bound of T" can be converted to an rvalue of type "pointer to
1024 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001025 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001026
John McCall5c32be02010-08-24 20:38:10 +00001027 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001029 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001030
1031 // For the purpose of ranking in overload resolution
1032 // (13.3.3.1.1), this conversion is considered an
1033 // array-to-pointer conversion followed by a qualification
1034 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001035 SCS.Second = ICK_Identity;
1036 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001037 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001038 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039 }
John McCall086a4642010-11-24 05:12:34 +00001040 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001041 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001042 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043
1044 // An lvalue of function type T can be converted to an rvalue of
1045 // type "pointer to T." The result is a pointer to the
1046 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001047 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001048 } else {
1049 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001050 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001052 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001053
1054 // The second conversion can be an integral promotion, floating
1055 // point promotion, integral conversion, floating point conversion,
1056 // floating-integral conversion, pointer conversion,
1057 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 // For overloading in C, this can also be a "compatible-type"
1059 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001060 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001061 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001062 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 // The unqualified versions of the types are the same: there's no
1064 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001065 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001066 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001067 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001068 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001070 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001071 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001072 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001074 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001075 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001076 SCS.Second = ICK_Complex_Promotion;
1077 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001078 } else if (ToType->isBooleanType() &&
1079 (FromType->isArithmeticType() ||
1080 FromType->isAnyPointerType() ||
1081 FromType->isBlockPointerType() ||
1082 FromType->isMemberPointerType() ||
1083 FromType->isNullPtrType())) {
1084 // Boolean conversions (C++ 4.12).
1085 SCS.Second = ICK_Boolean_Conversion;
1086 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001087 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001088 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001089 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001090 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001091 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001092 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001093 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001094 SCS.Second = ICK_Complex_Conversion;
1095 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001096 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1097 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001098 // Complex-real conversions (C99 6.3.1.7)
1099 SCS.Second = ICK_Complex_Real;
1100 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001101 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001102 // Floating point conversions (C++ 4.8).
1103 SCS.Second = ICK_Floating_Conversion;
1104 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001105 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001106 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001107 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001108 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001109 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001110 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001112 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1113 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001114 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001115 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001116 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001117 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1118 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001119 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001120 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001121 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001122 SCS.Second = SecondICK;
1123 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001124 } else if (!S.getLangOptions().CPlusPlus &&
1125 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001126 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001127 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001128 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001129 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001130 // Treat a conversion that strips "noreturn" as an identity conversion.
1131 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 } else {
1133 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001134 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001136 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001138 QualType CanonFrom;
1139 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001141 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001142 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001143 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001144 CanonFrom = S.Context.getCanonicalType(FromType);
1145 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001146 } else {
1147 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001148 SCS.Third = ICK_Identity;
1149
Mike Stump11289f42009-09-09 15:08:12 +00001150 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 // [...] Any difference in top-level cv-qualification is
1152 // subsumed by the initialization itself and does not constitute
1153 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001154 CanonFrom = S.Context.getCanonicalType(FromType);
1155 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001156 if (CanonFrom.getLocalUnqualifiedType()
1157 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001158 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1159 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001160 FromType = ToType;
1161 CanonFrom = CanonTo;
1162 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001164 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165
1166 // If we have not converted the argument type to the parameter type,
1167 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001168 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001169 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001171 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001172}
1173
1174/// IsIntegralPromotion - Determines whether the conversion from the
1175/// expression From (whose potentially-adjusted type is FromType) to
1176/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1177/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001178bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001179 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001180 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001181 if (!To) {
1182 return false;
1183 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184
1185 // An rvalue of type char, signed char, unsigned char, short int, or
1186 // unsigned short int can be converted to an rvalue of type int if
1187 // int can represent all the values of the source type; otherwise,
1188 // the source rvalue can be converted to an rvalue of type unsigned
1189 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001190 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1191 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001192 if (// We can promote any signed, promotable integer type to an int
1193 (FromType->isSignedIntegerType() ||
1194 // We can promote any unsigned integer type whose size is
1195 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001196 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001197 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001198 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001199 }
1200
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001201 return To->getKind() == BuiltinType::UInt;
1202 }
1203
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001204 // C++0x [conv.prom]p3:
1205 // A prvalue of an unscoped enumeration type whose underlying type is not
1206 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1207 // following types that can represent all the values of the enumeration
1208 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1209 // unsigned int, long int, unsigned long int, long long int, or unsigned
1210 // long long int. If none of the types in that list can represent all the
1211 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1212 // type can be converted to an rvalue a prvalue of the extended integer type
1213 // with lowest integer conversion rank (4.13) greater than the rank of long
1214 // long in which all the values of the enumeration can be represented. If
1215 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001216 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1217 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1218 // provided for a scoped enumeration.
1219 if (FromEnumType->getDecl()->isScoped())
1220 return false;
1221
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001222 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001223 if (ToType->isIntegerType() &&
1224 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001225 return Context.hasSameUnqualifiedType(ToType,
1226 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001227 }
John McCall56774992009-12-09 09:09:27 +00001228
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001229 // C++0x [conv.prom]p2:
1230 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1231 // to an rvalue a prvalue of the first of the following types that can
1232 // represent all the values of its underlying type: int, unsigned int,
1233 // long int, unsigned long int, long long int, or unsigned long long int.
1234 // If none of the types in that list can represent all the values of its
1235 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1236 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1237 // type.
1238 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1239 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 // Determine whether the type we're converting from is signed or
1241 // unsigned.
1242 bool FromIsSigned;
1243 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001244
1245 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1246 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001247
1248 // The types we'll try to promote to, in the appropriate
1249 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001250 QualType PromoteTypes[6] = {
1251 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001252 Context.LongTy, Context.UnsignedLongTy ,
1253 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001255 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001256 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1257 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001258 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1260 // We found the type that we can promote to. If this is the
1261 // type we wanted, we have a promotion. Otherwise, no
1262 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001263 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264 }
1265 }
1266 }
1267
1268 // An rvalue for an integral bit-field (9.6) can be converted to an
1269 // rvalue of type int if int can represent all the values of the
1270 // bit-field; otherwise, it can be converted to unsigned int if
1271 // unsigned int can represent all the values of the bit-field. If
1272 // the bit-field is larger yet, no integral promotion applies to
1273 // it. If the bit-field has an enumerated type, it is treated as any
1274 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001275 // FIXME: We should delay checking of bit-fields until we actually perform the
1276 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001277 using llvm::APSInt;
1278 if (From)
1279 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001280 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001281 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001282 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1283 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1284 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001285
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001286 // Are we promoting to an int from a bitfield that fits in an int?
1287 if (BitWidth < ToSize ||
1288 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1289 return To->getKind() == BuiltinType::Int;
1290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001292 // Are we promoting to an unsigned int from an unsigned bitfield
1293 // that fits into an unsigned int?
1294 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1295 return To->getKind() == BuiltinType::UInt;
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001298 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 // An rvalue of type bool can be converted to an rvalue of type int,
1303 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001304 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001306 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001307
1308 return false;
1309}
1310
1311/// IsFloatingPointPromotion - Determines whether the conversion from
1312/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1313/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001314bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001315 /// An rvalue of type float can be converted to an rvalue of type
1316 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001317 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1318 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 if (FromBuiltin->getKind() == BuiltinType::Float &&
1320 ToBuiltin->getKind() == BuiltinType::Double)
1321 return true;
1322
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001323 // C99 6.3.1.5p1:
1324 // When a float is promoted to double or long double, or a
1325 // double is promoted to long double [...].
1326 if (!getLangOptions().CPlusPlus &&
1327 (FromBuiltin->getKind() == BuiltinType::Float ||
1328 FromBuiltin->getKind() == BuiltinType::Double) &&
1329 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1330 return true;
1331 }
1332
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333 return false;
1334}
1335
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001336/// \brief Determine if a conversion is a complex promotion.
1337///
1338/// A complex promotion is defined as a complex -> complex conversion
1339/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001340/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001341bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001342 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001343 if (!FromComplex)
1344 return false;
1345
John McCall9dd450b2009-09-21 23:43:11 +00001346 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001347 if (!ToComplex)
1348 return false;
1349
1350 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001351 ToComplex->getElementType()) ||
1352 IsIntegralPromotion(0, FromComplex->getElementType(),
1353 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001354}
1355
Douglas Gregor237f96c2008-11-26 23:31:11 +00001356/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1357/// the pointer type FromPtr to a pointer to type ToPointee, with the
1358/// same type qualifiers as FromPtr has on its pointee type. ToType,
1359/// if non-empty, will be a pointer to ToType that may or may not have
1360/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001361static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001362BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001363 QualType ToPointee, QualType ToType,
1364 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001365 assert((FromPtr->getTypeClass() == Type::Pointer ||
1366 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1367 "Invalid similarly-qualified pointer type");
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001368
1369 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1370 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1371 return ToType.getUnqualifiedType();
1372
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001373 QualType CanonFromPointee
1374 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001375 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001376 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001377
1378 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001379 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001380 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001381 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001382 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001383
1384 // Build a pointer to ToPointee. It has the right qualifiers
1385 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001386 if (isa<ObjCObjectPointerType>(ToType))
1387 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001388 return Context.getPointerType(ToPointee);
1389 }
1390
1391 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001392 QualType QualifiedCanonToPointee
1393 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001394
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001395 if (isa<ObjCObjectPointerType>(ToType))
1396 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1397 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001398}
1399
Mike Stump11289f42009-09-09 15:08:12 +00001400static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001401 bool InOverloadResolution,
1402 ASTContext &Context) {
1403 // Handle value-dependent integral null pointer constants correctly.
1404 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1405 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001406 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001407 return !InOverloadResolution;
1408
Douglas Gregor56751b52009-09-25 04:25:58 +00001409 return Expr->isNullPointerConstant(Context,
1410 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1411 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001412}
Mike Stump11289f42009-09-09 15:08:12 +00001413
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001414/// IsPointerConversion - Determines whether the conversion of the
1415/// expression From, which has the (possibly adjusted) type FromType,
1416/// can be converted to the type ToType via a pointer conversion (C++
1417/// 4.10). If so, returns true and places the converted type (that
1418/// might differ from ToType in its cv-qualifiers at some level) into
1419/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001420///
Douglas Gregora29dc052008-11-27 01:19:21 +00001421/// This routine also supports conversions to and from block pointers
1422/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1423/// pointers to interfaces. FIXME: Once we've determined the
1424/// appropriate overloading rules for Objective-C, we may want to
1425/// split the Objective-C checks into a different routine; however,
1426/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001427/// conversions, so for now they live here. IncompatibleObjC will be
1428/// set if the conversion is an allowed Objective-C conversion that
1429/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001430bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001431 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001432 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001433 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001434 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001435 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1436 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001437
Mike Stump11289f42009-09-09 15:08:12 +00001438 // Conversion from a null pointer constant to any Objective-C pointer type.
1439 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001440 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001441 ConvertedType = ToType;
1442 return true;
1443 }
1444
Douglas Gregor231d1c62008-11-27 00:15:41 +00001445 // Blocks: Block pointers can be converted to void*.
1446 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001447 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001448 ConvertedType = ToType;
1449 return true;
1450 }
1451 // Blocks: A null pointer constant can be converted to a block
1452 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001453 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001454 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001455 ConvertedType = ToType;
1456 return true;
1457 }
1458
Sebastian Redl576fd422009-05-10 18:38:11 +00001459 // If the left-hand-side is nullptr_t, the right side can be a null
1460 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001461 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001462 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001463 ConvertedType = ToType;
1464 return true;
1465 }
1466
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001467 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001468 if (!ToTypePtr)
1469 return false;
1470
1471 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001472 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473 ConvertedType = ToType;
1474 return true;
1475 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001476
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001477 // Beyond this point, both types need to be pointers
1478 // , including objective-c pointers.
1479 QualType ToPointeeType = ToTypePtr->getPointeeType();
1480 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001481 ConvertedType = BuildSimilarlyQualifiedPointerType(
1482 FromType->getAs<ObjCObjectPointerType>(),
1483 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001484 ToType, Context);
1485 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001486 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001487 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001488 if (!FromTypePtr)
1489 return false;
1490
1491 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001492
Douglas Gregorfb640862010-08-18 21:25:30 +00001493 // If the unqualified pointee types are the same, this can't be a
1494 // pointer conversion, so don't do all of the work below.
1495 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1496 return false;
1497
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001498 // An rvalue of type "pointer to cv T," where T is an object type,
1499 // can be converted to an rvalue of type "pointer to cv void" (C++
1500 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001501 if (FromPointeeType->isIncompleteOrObjectType() &&
1502 ToPointeeType->isVoidType()) {
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);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001506 return true;
1507 }
1508
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001509 // When we're overloading in C, we allow a special kind of pointer
1510 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001511 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001512 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001513 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001514 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001515 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001516 return true;
1517 }
1518
Douglas Gregor5c407d92008-10-23 00:40:37 +00001519 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001520 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001521 // An rvalue of type "pointer to cv D," where D is a class type,
1522 // can be converted to an rvalue of type "pointer to cv B," where
1523 // B is a base class (clause 10) of D. If B is an inaccessible
1524 // (clause 11) or ambiguous (10.2) base class of D, a program that
1525 // necessitates this conversion is ill-formed. The result of the
1526 // conversion is a pointer to the base class sub-object of the
1527 // derived class object. The null pointer value is converted to
1528 // the null pointer value of the destination type.
1529 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001530 // Note that we do not check for ambiguity or inaccessibility
1531 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001532 if (getLangOptions().CPlusPlus &&
1533 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001534 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001535 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001536 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001537 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001538 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539 ToType, Context);
1540 return true;
1541 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001542
Douglas Gregora119f102008-12-19 19:13:09 +00001543 return false;
1544}
1545
1546/// isObjCPointerConversion - Determines whether this is an
1547/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1548/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001549bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001550 QualType& ConvertedType,
1551 bool &IncompatibleObjC) {
1552 if (!getLangOptions().ObjC1)
1553 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001554
Steve Naroff7cae42b2009-07-10 23:34:53 +00001555 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001556 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001557 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001558 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001559
Steve Naroff7cae42b2009-07-10 23:34:53 +00001560 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001561 // If the pointee types are the same (ignoring qualifications),
1562 // then this is not a pointer conversion.
1563 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1564 FromObjCPtr->getPointeeType()))
1565 return false;
1566
Steve Naroff1329fa02009-07-15 18:40:39 +00001567 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001568 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001569 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001570 ConvertedType = ToType;
1571 return true;
1572 }
1573 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001574 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001575 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001576 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001577 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001578 ConvertedType = ToType;
1579 return true;
1580 }
1581 // Objective C++: We're able to convert from a pointer to an
1582 // interface to a pointer to a different interface.
1583 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001584 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1585 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1586 if (getLangOptions().CPlusPlus && LHS && RHS &&
1587 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1588 FromObjCPtr->getPointeeType()))
1589 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001590 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1591 ToObjCPtr->getPointeeType(),
1592 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001593 return true;
1594 }
1595
1596 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1597 // Okay: this is some kind of implicit downcast of Objective-C
1598 // interfaces, which is permitted. However, we're going to
1599 // complain about it.
1600 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001601 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1602 ToObjCPtr->getPointeeType(),
1603 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001604 return true;
1605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001607 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001608 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001609 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001610 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001611 else if (const BlockPointerType *ToBlockPtr =
1612 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001613 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001614 // to a block pointer type.
1615 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1616 ConvertedType = ToType;
1617 return true;
1618 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001619 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001620 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001621 else if (FromType->getAs<BlockPointerType>() &&
1622 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1623 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001624 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001625 ConvertedType = ToType;
1626 return true;
1627 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001628 else
Douglas Gregora119f102008-12-19 19:13:09 +00001629 return false;
1630
Douglas Gregor033f56d2008-12-23 00:53:59 +00001631 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001632 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001633 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001634 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001635 FromPointeeType = FromBlockPtr->getPointeeType();
1636 else
Douglas Gregora119f102008-12-19 19:13:09 +00001637 return false;
1638
Douglas Gregora119f102008-12-19 19:13:09 +00001639 // If we have pointers to pointers, recursively check whether this
1640 // is an Objective-C conversion.
1641 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1642 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1643 IncompatibleObjC)) {
1644 // We always complain about this conversion.
1645 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001646 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001647 return true;
1648 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001649 // Allow conversion of pointee being objective-c pointer to another one;
1650 // as in I* to id.
1651 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1652 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1653 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1654 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001655 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001656 return true;
1657 }
1658
Douglas Gregor033f56d2008-12-23 00:53:59 +00001659 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001660 // differences in the argument and result types are in Objective-C
1661 // pointer conversions. If so, we permit the conversion (but
1662 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001663 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001664 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001665 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001666 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001667 if (FromFunctionType && ToFunctionType) {
1668 // If the function types are exactly the same, this isn't an
1669 // Objective-C pointer conversion.
1670 if (Context.getCanonicalType(FromPointeeType)
1671 == Context.getCanonicalType(ToPointeeType))
1672 return false;
1673
1674 // Perform the quick checks that will tell us whether these
1675 // function types are obviously different.
1676 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1677 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1678 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1679 return false;
1680
1681 bool HasObjCConversion = false;
1682 if (Context.getCanonicalType(FromFunctionType->getResultType())
1683 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1684 // Okay, the types match exactly. Nothing to do.
1685 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1686 ToFunctionType->getResultType(),
1687 ConvertedType, IncompatibleObjC)) {
1688 // Okay, we have an Objective-C pointer conversion.
1689 HasObjCConversion = true;
1690 } else {
1691 // Function types are too different. Abort.
1692 return false;
1693 }
Mike Stump11289f42009-09-09 15:08:12 +00001694
Douglas Gregora119f102008-12-19 19:13:09 +00001695 // Check argument types.
1696 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1697 ArgIdx != NumArgs; ++ArgIdx) {
1698 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1699 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1700 if (Context.getCanonicalType(FromArgType)
1701 == Context.getCanonicalType(ToArgType)) {
1702 // Okay, the types match exactly. Nothing to do.
1703 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1704 ConvertedType, IncompatibleObjC)) {
1705 // Okay, we have an Objective-C pointer conversion.
1706 HasObjCConversion = true;
1707 } else {
1708 // Argument types are too different. Abort.
1709 return false;
1710 }
1711 }
1712
1713 if (HasObjCConversion) {
1714 // We had an Objective-C conversion. Allow this pointer
1715 // conversion, but complain about it.
1716 ConvertedType = ToType;
1717 IncompatibleObjC = true;
1718 return true;
1719 }
1720 }
1721
Sebastian Redl72b597d2009-01-25 19:43:20 +00001722 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001724
1725/// FunctionArgTypesAreEqual - This routine checks two function proto types
1726/// for equlity of their argument types. Caller has already checked that
1727/// they have same number of arguments. This routine assumes that Objective-C
1728/// pointer types which only differ in their protocol qualifiers are equal.
1729bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1730 FunctionProtoType* NewType){
1731 if (!getLangOptions().ObjC1)
1732 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1733 NewType->arg_type_begin());
1734
1735 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1736 N = NewType->arg_type_begin(),
1737 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1738 QualType ToType = (*O);
1739 QualType FromType = (*N);
1740 if (ToType != FromType) {
1741 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1742 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001743 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1744 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1745 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1746 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001747 continue;
1748 }
John McCall8b07ec22010-05-15 11:32:37 +00001749 else if (const ObjCObjectPointerType *PTTo =
1750 ToType->getAs<ObjCObjectPointerType>()) {
1751 if (const ObjCObjectPointerType *PTFr =
1752 FromType->getAs<ObjCObjectPointerType>())
1753 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1754 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001755 }
1756 return false;
1757 }
1758 }
1759 return true;
1760}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001761
Douglas Gregor39c16d42008-10-24 04:54:22 +00001762/// CheckPointerConversion - Check the pointer conversion from the
1763/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001764/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001765/// conversions for which IsPointerConversion has already returned
1766/// true. It returns true and produces a diagnostic if there was an
1767/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001768bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001769 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001770 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001771 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001772 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001773 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001774
John McCall8cb679e2010-11-15 09:13:47 +00001775 Kind = CK_BitCast;
1776
Douglas Gregor4038cf42010-06-08 17:35:15 +00001777 if (CXXBoolLiteralExpr* LitBool
1778 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001779 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001780 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1781 << ToType;
1782
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001783 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1784 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001785 QualType FromPointeeType = FromPtrType->getPointeeType(),
1786 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001787
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001788 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1789 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001790 // We must have a derived-to-base conversion. Check an
1791 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001792 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1793 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001794 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001795 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001796 return true;
1797
1798 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001799 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001800 }
1801 }
Mike Stump11289f42009-09-09 15:08:12 +00001802 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001803 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001804 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001805 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001806 // Objective-C++ conversions are always okay.
1807 // FIXME: We should have a different class of conversions for the
1808 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001809 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001810 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001811 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001812 }
John McCall8cb679e2010-11-15 09:13:47 +00001813
1814 // We shouldn't fall into this case unless it's valid for other
1815 // reasons.
1816 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1817 Kind = CK_NullToPointer;
1818
Douglas Gregor39c16d42008-10-24 04:54:22 +00001819 return false;
1820}
1821
Sebastian Redl72b597d2009-01-25 19:43:20 +00001822/// IsMemberPointerConversion - Determines whether the conversion of the
1823/// expression From, which has the (possibly adjusted) type FromType, can be
1824/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1825/// If so, returns true and places the converted type (that might differ from
1826/// ToType in its cv-qualifiers at some level) into ConvertedType.
1827bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001828 QualType ToType,
1829 bool InOverloadResolution,
1830 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001831 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001832 if (!ToTypePtr)
1833 return false;
1834
1835 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001836 if (From->isNullPointerConstant(Context,
1837 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1838 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001839 ConvertedType = ToType;
1840 return true;
1841 }
1842
1843 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001844 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001845 if (!FromTypePtr)
1846 return false;
1847
1848 // A pointer to member of B can be converted to a pointer to member of D,
1849 // where D is derived from B (C++ 4.11p2).
1850 QualType FromClass(FromTypePtr->getClass(), 0);
1851 QualType ToClass(ToTypePtr->getClass(), 0);
1852 // FIXME: What happens when these are dependent? Is this function even called?
1853
1854 if (IsDerivedFrom(ToClass, FromClass)) {
1855 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1856 ToClass.getTypePtr());
1857 return true;
1858 }
1859
1860 return false;
1861}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001862
Sebastian Redl72b597d2009-01-25 19:43:20 +00001863/// CheckMemberPointerConversion - Check the member pointer conversion from the
1864/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001865/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001866/// for which IsMemberPointerConversion has already returned true. It returns
1867/// true and produces a diagnostic if there was an error, or returns false
1868/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001869bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001870 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001871 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001872 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001873 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001874 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001875 if (!FromPtrType) {
1876 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001877 assert(From->isNullPointerConstant(Context,
1878 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001879 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001880 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001881 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001882 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001883
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001884 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001885 assert(ToPtrType && "No member pointer cast has a target type "
1886 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001887
Sebastian Redled8f2002009-01-28 18:33:18 +00001888 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1889 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001890
Sebastian Redled8f2002009-01-28 18:33:18 +00001891 // FIXME: What about dependent types?
1892 assert(FromClass->isRecordType() && "Pointer into non-class.");
1893 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001894
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001895 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001896 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001897 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1898 assert(DerivationOkay &&
1899 "Should not have been called if derivation isn't OK.");
1900 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001901
Sebastian Redled8f2002009-01-28 18:33:18 +00001902 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1903 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001904 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1905 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1906 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1907 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001908 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001909
Douglas Gregor89ee6822009-02-28 01:32:25 +00001910 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001911 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1912 << FromClass << ToClass << QualType(VBase, 0)
1913 << From->getSourceRange();
1914 return true;
1915 }
1916
John McCall5b0829a2010-02-10 09:31:12 +00001917 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001918 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1919 Paths.front(),
1920 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001921
Anders Carlssond7923c62009-08-22 23:33:40 +00001922 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001923 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001924 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001925 return false;
1926}
1927
Douglas Gregor9a657932008-10-21 23:43:52 +00001928/// IsQualificationConversion - Determines whether the conversion from
1929/// an rvalue of type FromType to ToType is a qualification conversion
1930/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001931bool
1932Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001933 FromType = Context.getCanonicalType(FromType);
1934 ToType = Context.getCanonicalType(ToType);
1935
1936 // If FromType and ToType are the same type, this is not a
1937 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001938 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001939 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001940
Douglas Gregor9a657932008-10-21 23:43:52 +00001941 // (C++ 4.4p4):
1942 // A conversion can add cv-qualifiers at levels other than the first
1943 // in multi-level pointers, subject to the following rules: [...]
1944 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001945 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001946 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001947 // Within each iteration of the loop, we check the qualifiers to
1948 // determine if this still looks like a qualification
1949 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001950 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001951 // until there are no more pointers or pointers-to-members left to
1952 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001953 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001954
1955 // -- for every j > 0, if const is in cv 1,j then const is in cv
1956 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001957 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001958 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor9a657932008-10-21 23:43:52 +00001960 // -- if the cv 1,j and cv 2,j are different, then const is in
1961 // every cv for 0 < k < j.
1962 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001963 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001964 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001965
Douglas Gregor9a657932008-10-21 23:43:52 +00001966 // Keep track of whether all prior cv-qualifiers in the "to" type
1967 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001968 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001969 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001970 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001971
1972 // We are left with FromType and ToType being the pointee types
1973 // after unwrapping the original FromType and ToType the same number
1974 // of types. If we unwrapped any pointers, and if FromType and
1975 // ToType have the same unqualified type (since we checked
1976 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001977 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001978}
1979
Douglas Gregor576e98c2009-01-30 23:27:23 +00001980/// Determines whether there is a user-defined conversion sequence
1981/// (C++ [over.ics.user]) that converts expression From to the type
1982/// ToType. If such a conversion exists, User will contain the
1983/// user-defined conversion sequence that performs such a conversion
1984/// and this routine will return true. Otherwise, this routine returns
1985/// false and User is unspecified.
1986///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001987/// \param AllowExplicit true if the conversion should consider C++0x
1988/// "explicit" conversion functions as well as non-explicit conversion
1989/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001990static OverloadingResult
1991IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1992 UserDefinedConversionSequence& User,
1993 OverloadCandidateSet& CandidateSet,
1994 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001995 // Whether we will only visit constructors.
1996 bool ConstructorsOnly = false;
1997
1998 // If the type we are conversion to is a class type, enumerate its
1999 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002000 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002001 // C++ [over.match.ctor]p1:
2002 // When objects of class type are direct-initialized (8.5), or
2003 // copy-initialized from an expression of the same or a
2004 // derived class type (8.5), overload resolution selects the
2005 // constructor. [...] For copy-initialization, the candidate
2006 // functions are all the converting constructors (12.3.1) of
2007 // that class. The argument list is the expression-list within
2008 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002009 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002010 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002011 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002012 ConstructorsOnly = true;
2013
John McCall5c32be02010-08-24 20:38:10 +00002014 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002015 // We're not going to find any constructors.
2016 } else if (CXXRecordDecl *ToRecordDecl
2017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002018 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002019 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002020 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002021 NamedDecl *D = *Con;
2022 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2023
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002024 // Find the constructor (which may be a template).
2025 CXXConstructorDecl *Constructor = 0;
2026 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002027 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002028 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002029 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002030 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2031 else
John McCalla0296f72010-03-19 07:35:19 +00002032 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002033
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002034 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002035 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002036 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002037 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2038 /*ExplicitArgs*/ 0,
2039 &From, 1, CandidateSet,
2040 /*SuppressUserConversions=*/
2041 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002042 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002043 // Allow one user-defined conversion when user specifies a
2044 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002045 S.AddOverloadCandidate(Constructor, FoundDecl,
2046 &From, 1, CandidateSet,
2047 /*SuppressUserConversions=*/
2048 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002049 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002050 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002051 }
2052 }
2053
Douglas Gregor5ab11652010-04-17 22:01:05 +00002054 // Enumerate conversion functions, if we're allowed to.
2055 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002056 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2057 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002058 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002059 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002060 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002061 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002062 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2063 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002064 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002065 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002066 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002067 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002068 DeclAccessPair FoundDecl = I.getPair();
2069 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002070 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2071 if (isa<UsingShadowDecl>(D))
2072 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2073
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002074 CXXConversionDecl *Conv;
2075 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002076 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2077 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002078 else
John McCallda4458e2010-03-31 01:36:47 +00002079 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002080
2081 if (AllowExplicit || !Conv->isExplicit()) {
2082 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002083 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2084 ActingContext, From, ToType,
2085 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002086 else
John McCall5c32be02010-08-24 20:38:10 +00002087 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2088 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002089 }
2090 }
2091 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002092 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002093
2094 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002095 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002096 case OR_Success:
2097 // Record the standard conversion we used and the conversion function.
2098 if (CXXConstructorDecl *Constructor
2099 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2100 // C++ [over.ics.user]p1:
2101 // If the user-defined conversion is specified by a
2102 // constructor (12.3.1), the initial standard conversion
2103 // sequence converts the source type to the type required by
2104 // the argument of the constructor.
2105 //
2106 QualType ThisType = Constructor->getThisType(S.Context);
2107 if (Best->Conversions[0].isEllipsis())
2108 User.EllipsisConversion = true;
2109 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002110 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002111 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002112 }
John McCall5c32be02010-08-24 20:38:10 +00002113 User.ConversionFunction = Constructor;
2114 User.After.setAsIdentityConversion();
2115 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2116 User.After.setAllToTypes(ToType);
2117 return OR_Success;
2118 } else if (CXXConversionDecl *Conversion
2119 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2120 // C++ [over.ics.user]p1:
2121 //
2122 // [...] If the user-defined conversion is specified by a
2123 // conversion function (12.3.2), the initial standard
2124 // conversion sequence converts the source type to the
2125 // implicit object parameter of the conversion function.
2126 User.Before = Best->Conversions[0].Standard;
2127 User.ConversionFunction = Conversion;
2128 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002129
John McCall5c32be02010-08-24 20:38:10 +00002130 // C++ [over.ics.user]p2:
2131 // The second standard conversion sequence converts the
2132 // result of the user-defined conversion to the target type
2133 // for the sequence. Since an implicit conversion sequence
2134 // is an initialization, the special rules for
2135 // initialization by user-defined conversion apply when
2136 // selecting the best user-defined conversion for a
2137 // user-defined conversion sequence (see 13.3.3 and
2138 // 13.3.3.1).
2139 User.After = Best->FinalConversion;
2140 return OR_Success;
2141 } else {
2142 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002143 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002144 }
2145
John McCall5c32be02010-08-24 20:38:10 +00002146 case OR_No_Viable_Function:
2147 return OR_No_Viable_Function;
2148 case OR_Deleted:
2149 // No conversion here! We're done.
2150 return OR_Deleted;
2151
2152 case OR_Ambiguous:
2153 return OR_Ambiguous;
2154 }
2155
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002156 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002157}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002158
2159bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002160Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002161 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002162 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002163 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002164 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002165 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002166 if (OvResult == OR_Ambiguous)
2167 Diag(From->getSourceRange().getBegin(),
2168 diag::err_typecheck_ambiguous_condition)
2169 << From->getType() << ToType << From->getSourceRange();
2170 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2171 Diag(From->getSourceRange().getBegin(),
2172 diag::err_typecheck_nonviable_condition)
2173 << From->getType() << ToType << From->getSourceRange();
2174 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002175 return false;
John McCall5c32be02010-08-24 20:38:10 +00002176 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002177 return true;
2178}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002179
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002180/// CompareImplicitConversionSequences - Compare two implicit
2181/// conversion sequences to determine whether one is better than the
2182/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002183static ImplicitConversionSequence::CompareKind
2184CompareImplicitConversionSequences(Sema &S,
2185 const ImplicitConversionSequence& ICS1,
2186 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187{
2188 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2189 // conversion sequences (as defined in 13.3.3.1)
2190 // -- a standard conversion sequence (13.3.3.1.1) is a better
2191 // conversion sequence than a user-defined conversion sequence or
2192 // an ellipsis conversion sequence, and
2193 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2194 // conversion sequence than an ellipsis conversion sequence
2195 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002196 //
John McCall0d1da222010-01-12 00:44:57 +00002197 // C++0x [over.best.ics]p10:
2198 // For the purpose of ranking implicit conversion sequences as
2199 // described in 13.3.3.2, the ambiguous conversion sequence is
2200 // treated as a user-defined sequence that is indistinguishable
2201 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002202 if (ICS1.getKindRank() < ICS2.getKindRank())
2203 return ImplicitConversionSequence::Better;
2204 else if (ICS2.getKindRank() < ICS1.getKindRank())
2205 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002206
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002207 // The following checks require both conversion sequences to be of
2208 // the same kind.
2209 if (ICS1.getKind() != ICS2.getKind())
2210 return ImplicitConversionSequence::Indistinguishable;
2211
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002212 // Two implicit conversion sequences of the same form are
2213 // indistinguishable conversion sequences unless one of the
2214 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002215 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002216 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002217 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002218 // User-defined conversion sequence U1 is a better conversion
2219 // sequence than another user-defined conversion sequence U2 if
2220 // they contain the same user-defined conversion function or
2221 // constructor and if the second standard conversion sequence of
2222 // U1 is better than the second standard conversion sequence of
2223 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002224 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002225 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002226 return CompareStandardConversionSequences(S,
2227 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002228 ICS2.UserDefined.After);
2229 }
2230
2231 return ImplicitConversionSequence::Indistinguishable;
2232}
2233
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002234static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2235 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2236 Qualifiers Quals;
2237 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2238 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2239 }
2240
2241 return Context.hasSameUnqualifiedType(T1, T2);
2242}
2243
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002244// Per 13.3.3.2p3, compare the given standard conversion sequences to
2245// determine if one is a proper subset of the other.
2246static ImplicitConversionSequence::CompareKind
2247compareStandardConversionSubsets(ASTContext &Context,
2248 const StandardConversionSequence& SCS1,
2249 const StandardConversionSequence& SCS2) {
2250 ImplicitConversionSequence::CompareKind Result
2251 = ImplicitConversionSequence::Indistinguishable;
2252
Douglas Gregore87561a2010-05-23 22:10:15 +00002253 // the identity conversion sequence is considered to be a subsequence of
2254 // any non-identity conversion sequence
2255 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2256 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2257 return ImplicitConversionSequence::Better;
2258 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2259 return ImplicitConversionSequence::Worse;
2260 }
2261
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002262 if (SCS1.Second != SCS2.Second) {
2263 if (SCS1.Second == ICK_Identity)
2264 Result = ImplicitConversionSequence::Better;
2265 else if (SCS2.Second == ICK_Identity)
2266 Result = ImplicitConversionSequence::Worse;
2267 else
2268 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002269 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002270 return ImplicitConversionSequence::Indistinguishable;
2271
2272 if (SCS1.Third == SCS2.Third) {
2273 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2274 : ImplicitConversionSequence::Indistinguishable;
2275 }
2276
2277 if (SCS1.Third == ICK_Identity)
2278 return Result == ImplicitConversionSequence::Worse
2279 ? ImplicitConversionSequence::Indistinguishable
2280 : ImplicitConversionSequence::Better;
2281
2282 if (SCS2.Third == ICK_Identity)
2283 return Result == ImplicitConversionSequence::Better
2284 ? ImplicitConversionSequence::Indistinguishable
2285 : ImplicitConversionSequence::Worse;
2286
2287 return ImplicitConversionSequence::Indistinguishable;
2288}
2289
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002290/// CompareStandardConversionSequences - Compare two standard
2291/// conversion sequences to determine whether one is better than the
2292/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002293static ImplicitConversionSequence::CompareKind
2294CompareStandardConversionSequences(Sema &S,
2295 const StandardConversionSequence& SCS1,
2296 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002297{
2298 // Standard conversion sequence S1 is a better conversion sequence
2299 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2300
2301 // -- S1 is a proper subsequence of S2 (comparing the conversion
2302 // sequences in the canonical form defined by 13.3.3.1.1,
2303 // excluding any Lvalue Transformation; the identity conversion
2304 // sequence is considered to be a subsequence of any
2305 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002306 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002307 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002308 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002309
2310 // -- the rank of S1 is better than the rank of S2 (by the rules
2311 // defined below), or, if not that,
2312 ImplicitConversionRank Rank1 = SCS1.getRank();
2313 ImplicitConversionRank Rank2 = SCS2.getRank();
2314 if (Rank1 < Rank2)
2315 return ImplicitConversionSequence::Better;
2316 else if (Rank2 < Rank1)
2317 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002318
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002319 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2320 // are indistinguishable unless one of the following rules
2321 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002322
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002323 // A conversion that is not a conversion of a pointer, or
2324 // pointer to member, to bool is better than another conversion
2325 // that is such a conversion.
2326 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2327 return SCS2.isPointerConversionToBool()
2328 ? ImplicitConversionSequence::Better
2329 : ImplicitConversionSequence::Worse;
2330
Douglas Gregor5c407d92008-10-23 00:40:37 +00002331 // C++ [over.ics.rank]p4b2:
2332 //
2333 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002334 // conversion of B* to A* is better than conversion of B* to
2335 // void*, and conversion of A* to void* is better than conversion
2336 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002337 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002338 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002339 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002340 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002341 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2342 // Exactly one of the conversion sequences is a conversion to
2343 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002344 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2345 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002346 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2347 // Neither conversion sequence converts to a void pointer; compare
2348 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002349 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002350 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002351 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002352 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2353 // Both conversion sequences are conversions to void
2354 // pointers. Compare the source types to determine if there's an
2355 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002356 QualType FromType1 = SCS1.getFromType();
2357 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002358
2359 // Adjust the types we're converting from via the array-to-pointer
2360 // conversion, if we need to.
2361 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002362 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002363 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002364 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002365
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002366 QualType FromPointee1
2367 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2368 QualType FromPointee2
2369 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002370
John McCall5c32be02010-08-24 20:38:10 +00002371 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002372 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002373 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002374 return ImplicitConversionSequence::Worse;
2375
2376 // Objective-C++: If one interface is more specific than the
2377 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002378 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2379 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002380 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002381 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002382 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002383 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002384 return ImplicitConversionSequence::Worse;
2385 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002386 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002387
2388 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2389 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002390 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002391 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002392 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002393
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002394 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002395 // C++0x [over.ics.rank]p3b4:
2396 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2397 // implicit object parameter of a non-static member function declared
2398 // without a ref-qualifier, and S1 binds an rvalue reference to an
2399 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002400 // FIXME: We don't know if we're dealing with the implicit object parameter,
2401 // or if the member function in this case has a ref qualifier.
2402 // (Of course, we don't have ref qualifiers yet.)
2403 if (SCS1.RRefBinding != SCS2.RRefBinding)
2404 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2405 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002406
2407 // C++ [over.ics.rank]p3b4:
2408 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2409 // which the references refer are the same type except for
2410 // top-level cv-qualifiers, and the type to which the reference
2411 // initialized by S2 refers is more cv-qualified than the type
2412 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002413 QualType T1 = SCS1.getToType(2);
2414 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002415 T1 = S.Context.getCanonicalType(T1);
2416 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002417 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002418 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2419 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002420 if (UnqualT1 == UnqualT2) {
2421 // If the type is an array type, promote the element qualifiers to the type
2422 // for comparison.
2423 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002424 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002425 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002426 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002427 if (T2.isMoreQualifiedThan(T1))
2428 return ImplicitConversionSequence::Better;
2429 else if (T1.isMoreQualifiedThan(T2))
2430 return ImplicitConversionSequence::Worse;
2431 }
2432 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002433
2434 return ImplicitConversionSequence::Indistinguishable;
2435}
2436
2437/// CompareQualificationConversions - Compares two standard conversion
2438/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002439/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2440ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002441CompareQualificationConversions(Sema &S,
2442 const StandardConversionSequence& SCS1,
2443 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002444 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002445 // -- S1 and S2 differ only in their qualification conversion and
2446 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2447 // cv-qualification signature of type T1 is a proper subset of
2448 // the cv-qualification signature of type T2, and S1 is not the
2449 // deprecated string literal array-to-pointer conversion (4.2).
2450 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2451 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2452 return ImplicitConversionSequence::Indistinguishable;
2453
2454 // FIXME: the example in the standard doesn't use a qualification
2455 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002456 QualType T1 = SCS1.getToType(2);
2457 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002458 T1 = S.Context.getCanonicalType(T1);
2459 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002460 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002461 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2462 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002463
2464 // If the types are the same, we won't learn anything by unwrapped
2465 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002466 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002467 return ImplicitConversionSequence::Indistinguishable;
2468
Chandler Carruth607f38e2009-12-29 07:16:59 +00002469 // If the type is an array type, promote the element qualifiers to the type
2470 // for comparison.
2471 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002472 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002473 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002474 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002475
Mike Stump11289f42009-09-09 15:08:12 +00002476 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002477 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002478 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002479 // Within each iteration of the loop, we check the qualifiers to
2480 // determine if this still looks like a qualification
2481 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002482 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002483 // until there are no more pointers or pointers-to-members left
2484 // to unwrap. This essentially mimics what
2485 // IsQualificationConversion does, but here we're checking for a
2486 // strict subset of qualifiers.
2487 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2488 // The qualifiers are the same, so this doesn't tell us anything
2489 // about how the sequences rank.
2490 ;
2491 else if (T2.isMoreQualifiedThan(T1)) {
2492 // T1 has fewer qualifiers, so it could be the better sequence.
2493 if (Result == ImplicitConversionSequence::Worse)
2494 // Neither has qualifiers that are a subset of the other's
2495 // qualifiers.
2496 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002497
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002498 Result = ImplicitConversionSequence::Better;
2499 } else if (T1.isMoreQualifiedThan(T2)) {
2500 // T2 has fewer qualifiers, so it could be the better sequence.
2501 if (Result == ImplicitConversionSequence::Better)
2502 // Neither has qualifiers that are a subset of the other's
2503 // qualifiers.
2504 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002506 Result = ImplicitConversionSequence::Worse;
2507 } else {
2508 // Qualifiers are disjoint.
2509 return ImplicitConversionSequence::Indistinguishable;
2510 }
2511
2512 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002513 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002514 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002515 }
2516
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002517 // Check that the winning standard conversion sequence isn't using
2518 // the deprecated string literal array to pointer conversion.
2519 switch (Result) {
2520 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002521 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002522 Result = ImplicitConversionSequence::Indistinguishable;
2523 break;
2524
2525 case ImplicitConversionSequence::Indistinguishable:
2526 break;
2527
2528 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002529 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002530 Result = ImplicitConversionSequence::Indistinguishable;
2531 break;
2532 }
2533
2534 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002535}
2536
Douglas Gregor5c407d92008-10-23 00:40:37 +00002537/// CompareDerivedToBaseConversions - Compares two standard conversion
2538/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002539/// various kinds of derived-to-base conversions (C++
2540/// [over.ics.rank]p4b3). As part of these checks, we also look at
2541/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002542ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002543CompareDerivedToBaseConversions(Sema &S,
2544 const StandardConversionSequence& SCS1,
2545 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002546 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002547 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002548 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002549 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002550
2551 // Adjust the types we're converting from via the array-to-pointer
2552 // conversion, if we need to.
2553 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002554 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002555 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002556 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002557
2558 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002559 FromType1 = S.Context.getCanonicalType(FromType1);
2560 ToType1 = S.Context.getCanonicalType(ToType1);
2561 FromType2 = S.Context.getCanonicalType(FromType2);
2562 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002563
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002564 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002565 //
2566 // If class B is derived directly or indirectly from class A and
2567 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002568 //
2569 // For Objective-C, we let A, B, and C also be Objective-C
2570 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002571
2572 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002573 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002574 SCS2.Second == ICK_Pointer_Conversion &&
2575 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2576 FromType1->isPointerType() && FromType2->isPointerType() &&
2577 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002578 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002579 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002580 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002581 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002582 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002583 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002584 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002585 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002586
John McCall8b07ec22010-05-15 11:32:37 +00002587 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2588 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2589 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2590 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002591
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002592 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002593 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002594 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002595 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002596 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002597 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002598
2599 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002600 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002601 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002602 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002603 return ImplicitConversionSequence::Worse;
2604 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002605 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002606
2607 // -- conversion of B* to A* is better than conversion of C* to A*,
2608 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002609 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002610 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002611 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002612 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002613
Douglas Gregor237f96c2008-11-26 23:31:11 +00002614 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002615 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002616 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002617 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002618 return ImplicitConversionSequence::Worse;
2619 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002620 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002621 }
2622
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002623 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002624 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2625 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2626 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2627 const MemberPointerType * FromMemPointer1 =
2628 FromType1->getAs<MemberPointerType>();
2629 const MemberPointerType * ToMemPointer1 =
2630 ToType1->getAs<MemberPointerType>();
2631 const MemberPointerType * FromMemPointer2 =
2632 FromType2->getAs<MemberPointerType>();
2633 const MemberPointerType * ToMemPointer2 =
2634 ToType2->getAs<MemberPointerType>();
2635 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2636 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2637 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2638 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2639 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2640 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2641 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2642 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002643 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002644 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002645 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002646 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002647 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002648 return ImplicitConversionSequence::Better;
2649 }
2650 // conversion of B::* to C::* is better than conversion of A::* to C::*
2651 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002652 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002653 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002654 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002655 return ImplicitConversionSequence::Worse;
2656 }
2657 }
2658
Douglas Gregor5ab11652010-04-17 22:01:05 +00002659 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002660 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002661 // -- binding of an expression of type C to a reference of type
2662 // B& is better than binding an expression of type C to a
2663 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002664 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2665 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2666 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002667 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002668 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002669 return ImplicitConversionSequence::Worse;
2670 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002671
Douglas Gregor2fe98832008-11-03 19:09:14 +00002672 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002673 // -- binding of an expression of type B to a reference of type
2674 // A& is better than binding an expression of type C to a
2675 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002676 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2677 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2678 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002679 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002680 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002681 return ImplicitConversionSequence::Worse;
2682 }
2683 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002684
Douglas Gregor5c407d92008-10-23 00:40:37 +00002685 return ImplicitConversionSequence::Indistinguishable;
2686}
2687
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002688/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2689/// determine whether they are reference-related,
2690/// reference-compatible, reference-compatible with added
2691/// qualification, or incompatible, for use in C++ initialization by
2692/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2693/// type, and the first type (T1) is the pointee type of the reference
2694/// type being initialized.
2695Sema::ReferenceCompareResult
2696Sema::CompareReferenceRelationship(SourceLocation Loc,
2697 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002698 bool &DerivedToBase,
2699 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002700 assert(!OrigT1->isReferenceType() &&
2701 "T1 must be the pointee type of the reference type");
2702 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2703
2704 QualType T1 = Context.getCanonicalType(OrigT1);
2705 QualType T2 = Context.getCanonicalType(OrigT2);
2706 Qualifiers T1Quals, T2Quals;
2707 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2708 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2709
2710 // C++ [dcl.init.ref]p4:
2711 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2712 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2713 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002714 DerivedToBase = false;
2715 ObjCConversion = false;
2716 if (UnqualT1 == UnqualT2) {
2717 // Nothing to do.
2718 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002719 IsDerivedFrom(UnqualT2, UnqualT1))
2720 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002721 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2722 UnqualT2->isObjCObjectOrInterfaceType() &&
2723 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2724 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002725 else
2726 return Ref_Incompatible;
2727
2728 // At this point, we know that T1 and T2 are reference-related (at
2729 // least).
2730
2731 // If the type is an array type, promote the element qualifiers to the type
2732 // for comparison.
2733 if (isa<ArrayType>(T1) && T1Quals)
2734 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2735 if (isa<ArrayType>(T2) && T2Quals)
2736 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2737
2738 // C++ [dcl.init.ref]p4:
2739 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2740 // reference-related to T2 and cv1 is the same cv-qualification
2741 // as, or greater cv-qualification than, cv2. For purposes of
2742 // overload resolution, cases for which cv1 is greater
2743 // cv-qualification than cv2 are identified as
2744 // reference-compatible with added qualification (see 13.3.3.2).
2745 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2746 return Ref_Compatible;
2747 else if (T1.isMoreQualifiedThan(T2))
2748 return Ref_Compatible_With_Added_Qualification;
2749 else
2750 return Ref_Related;
2751}
2752
Douglas Gregor836a7e82010-08-11 02:15:33 +00002753/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002754/// with DeclType. Return true if something definite is found.
2755static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002756FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2757 QualType DeclType, SourceLocation DeclLoc,
2758 Expr *Init, QualType T2, bool AllowRvalues,
2759 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002760 assert(T2->isRecordType() && "Can only find conversions of record types.");
2761 CXXRecordDecl *T2RecordDecl
2762 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2763
Douglas Gregor836a7e82010-08-11 02:15:33 +00002764 QualType ToType
2765 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2766 : DeclType;
2767
Sebastian Redld92badf2010-06-30 18:13:39 +00002768 OverloadCandidateSet CandidateSet(DeclLoc);
2769 const UnresolvedSetImpl *Conversions
2770 = T2RecordDecl->getVisibleConversionFunctions();
2771 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2772 E = Conversions->end(); I != E; ++I) {
2773 NamedDecl *D = *I;
2774 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2775 if (isa<UsingShadowDecl>(D))
2776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2777
2778 FunctionTemplateDecl *ConvTemplate
2779 = dyn_cast<FunctionTemplateDecl>(D);
2780 CXXConversionDecl *Conv;
2781 if (ConvTemplate)
2782 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2783 else
2784 Conv = cast<CXXConversionDecl>(D);
2785
Douglas Gregor836a7e82010-08-11 02:15:33 +00002786 // If this is an explicit conversion, and we're not allowed to consider
2787 // explicit conversions, skip it.
2788 if (!AllowExplicit && Conv->isExplicit())
2789 continue;
2790
2791 if (AllowRvalues) {
2792 bool DerivedToBase = false;
2793 bool ObjCConversion = false;
2794 if (!ConvTemplate &&
2795 S.CompareReferenceRelationship(DeclLoc,
2796 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2797 DeclType.getNonReferenceType().getUnqualifiedType(),
2798 DerivedToBase, ObjCConversion)
2799 == Sema::Ref_Incompatible)
2800 continue;
2801 } else {
2802 // If the conversion function doesn't return a reference type,
2803 // it can't be considered for this conversion. An rvalue reference
2804 // is only acceptable if its referencee is a function type.
2805
2806 const ReferenceType *RefType =
2807 Conv->getConversionType()->getAs<ReferenceType>();
2808 if (!RefType ||
2809 (!RefType->isLValueReferenceType() &&
2810 !RefType->getPointeeType()->isFunctionType()))
2811 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002812 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002813
2814 if (ConvTemplate)
2815 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2816 Init, ToType, CandidateSet);
2817 else
2818 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2819 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002820 }
2821
2822 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002823 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002824 case OR_Success:
2825 // C++ [over.ics.ref]p1:
2826 //
2827 // [...] If the parameter binds directly to the result of
2828 // applying a conversion function to the argument
2829 // expression, the implicit conversion sequence is a
2830 // user-defined conversion sequence (13.3.3.1.2), with the
2831 // second standard conversion sequence either an identity
2832 // conversion or, if the conversion function returns an
2833 // entity of a type that is a derived class of the parameter
2834 // type, a derived-to-base Conversion.
2835 if (!Best->FinalConversion.DirectBinding)
2836 return false;
2837
2838 ICS.setUserDefined();
2839 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2840 ICS.UserDefined.After = Best->FinalConversion;
2841 ICS.UserDefined.ConversionFunction = Best->Function;
2842 ICS.UserDefined.EllipsisConversion = false;
2843 assert(ICS.UserDefined.After.ReferenceBinding &&
2844 ICS.UserDefined.After.DirectBinding &&
2845 "Expected a direct reference binding!");
2846 return true;
2847
2848 case OR_Ambiguous:
2849 ICS.setAmbiguous();
2850 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2851 Cand != CandidateSet.end(); ++Cand)
2852 if (Cand->Viable)
2853 ICS.Ambiguous.addConversion(Cand->Function);
2854 return true;
2855
2856 case OR_No_Viable_Function:
2857 case OR_Deleted:
2858 // There was no suitable conversion, or we found a deleted
2859 // conversion; continue with other checks.
2860 return false;
2861 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002862
2863 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002864}
2865
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002866/// \brief Compute an implicit conversion sequence for reference
2867/// initialization.
2868static ImplicitConversionSequence
2869TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2870 SourceLocation DeclLoc,
2871 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002872 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002873 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2874
2875 // Most paths end in a failed conversion.
2876 ImplicitConversionSequence ICS;
2877 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2878
2879 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2880 QualType T2 = Init->getType();
2881
2882 // If the initializer is the address of an overloaded function, try
2883 // to resolve the overloaded function. If all goes well, T2 is the
2884 // type of the resulting function.
2885 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2886 DeclAccessPair Found;
2887 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2888 false, Found))
2889 T2 = Fn->getType();
2890 }
2891
2892 // Compute some basic properties of the types and the initializer.
2893 bool isRValRef = DeclType->isRValueReferenceType();
2894 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002895 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002896 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002897 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002898 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2899 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002900
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002901
Sebastian Redld92badf2010-06-30 18:13:39 +00002902 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002903 // A reference to type "cv1 T1" is initialized by an expression
2904 // of type "cv2 T2" as follows:
2905
Sebastian Redld92badf2010-06-30 18:13:39 +00002906 // -- If reference is an lvalue reference and the initializer expression
2907 // The next bullet point (T1 is a function) is pretty much equivalent to this
2908 // one, so it's handled here.
2909 if (!isRValRef || T1->isFunctionType()) {
2910 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2911 // reference-compatible with "cv2 T2," or
2912 //
2913 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2914 if (InitCategory.isLValue() &&
2915 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002916 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002917 // When a parameter of reference type binds directly (8.5.3)
2918 // to an argument expression, the implicit conversion sequence
2919 // is the identity conversion, unless the argument expression
2920 // has a type that is a derived class of the parameter type,
2921 // in which case the implicit conversion sequence is a
2922 // derived-to-base Conversion (13.3.3.1).
2923 ICS.setStandard();
2924 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002925 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2926 : ObjCConversion? ICK_Compatible_Conversion
2927 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002928 ICS.Standard.Third = ICK_Identity;
2929 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2930 ICS.Standard.setToType(0, T2);
2931 ICS.Standard.setToType(1, T1);
2932 ICS.Standard.setToType(2, T1);
2933 ICS.Standard.ReferenceBinding = true;
2934 ICS.Standard.DirectBinding = true;
2935 ICS.Standard.RRefBinding = isRValRef;
2936 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002937
Sebastian Redld92badf2010-06-30 18:13:39 +00002938 // Nothing more to do: the inaccessibility/ambiguity check for
2939 // derived-to-base conversions is suppressed when we're
2940 // computing the implicit conversion sequence (C++
2941 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002942 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002943 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002944
Sebastian Redld92badf2010-06-30 18:13:39 +00002945 // -- has a class type (i.e., T2 is a class type), where T1 is
2946 // not reference-related to T2, and can be implicitly
2947 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2948 // is reference-compatible with "cv3 T3" 92) (this
2949 // conversion is selected by enumerating the applicable
2950 // conversion functions (13.3.1.6) and choosing the best
2951 // one through overload resolution (13.3)),
2952 if (!SuppressUserConversions && T2->isRecordType() &&
2953 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2954 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002955 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2956 Init, T2, /*AllowRvalues=*/false,
2957 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002958 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002959 }
2960 }
2961
Sebastian Redld92badf2010-06-30 18:13:39 +00002962 // -- Otherwise, the reference shall be an lvalue reference to a
2963 // non-volatile const type (i.e., cv1 shall be const), or the reference
2964 // shall be an rvalue reference and the initializer expression shall be
2965 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002966 //
2967 // We actually handle one oddity of C++ [over.ics.ref] at this
2968 // point, which is that, due to p2 (which short-circuits reference
2969 // binding by only attempting a simple conversion for non-direct
2970 // bindings) and p3's strange wording, we allow a const volatile
2971 // reference to bind to an rvalue. Hence the check for the presence
2972 // of "const" rather than checking for "const" being the only
2973 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002974 // This is also the point where rvalue references and lvalue inits no longer
2975 // go together.
2976 if ((!isRValRef && !T1.isConstQualified()) ||
2977 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002978 return ICS;
2979
Sebastian Redld92badf2010-06-30 18:13:39 +00002980 // -- If T1 is a function type, then
2981 // -- if T2 is the same type as T1, the reference is bound to the
2982 // initializer expression lvalue;
2983 // -- if T2 is a class type and the initializer expression can be
2984 // implicitly converted to an lvalue of type T1 [...], the
2985 // reference is bound to the function lvalue that is the result
2986 // of the conversion;
2987 // This is the same as for the lvalue case above, so it was handled there.
2988 // -- otherwise, the program is ill-formed.
2989 // This is the one difference to the lvalue case.
2990 if (T1->isFunctionType())
2991 return ICS;
2992
2993 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002994 // -- the initializer expression is an rvalue and "cv1 T1"
2995 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002996 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002997 // -- T1 is not reference-related to T2 and the initializer
2998 // expression can be implicitly converted to an rvalue
2999 // of type "cv3 T3" (this conversion is selected by
3000 // enumerating the applicable conversion functions
3001 // (13.3.1.6) and choosing the best one through overload
3002 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003003 //
Douglas Gregorf93df192010-04-18 08:46:23 +00003004 // then the reference is bound to the initializer
3005 // expression rvalue in the first case and to the object
3006 // that is the result of the conversion in the second case
3007 // (or, in either case, to the appropriate base class
3008 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00003009 if (T2->isRecordType()) {
3010 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3011 // direct binding in C++0x but not in C++03.
3012 if (InitCategory.isRValue() &&
3013 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3014 ICS.setStandard();
3015 ICS.Standard.First = ICK_Identity;
3016 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3017 : ObjCConversion? ICK_Compatible_Conversion
3018 : ICK_Identity;
3019 ICS.Standard.Third = ICK_Identity;
3020 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3021 ICS.Standard.setToType(0, T2);
3022 ICS.Standard.setToType(1, T1);
3023 ICS.Standard.setToType(2, T1);
3024 ICS.Standard.ReferenceBinding = true;
3025 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3026 ICS.Standard.RRefBinding = isRValRef;
3027 ICS.Standard.CopyConstructor = 0;
3028 return ICS;
3029 }
3030
3031 // Second case: not reference-related.
3032 if (RefRelationship == Sema::Ref_Incompatible &&
3033 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3034 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3035 Init, T2, /*AllowRvalues=*/true,
3036 AllowExplicit))
3037 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003038 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003039
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003040 // -- Otherwise, a temporary of type "cv1 T1" is created and
3041 // initialized from the initializer expression using the
3042 // rules for a non-reference copy initialization (8.5). The
3043 // reference is then bound to the temporary. If T1 is
3044 // reference-related to T2, cv1 must be the same
3045 // cv-qualification as, or greater cv-qualification than,
3046 // cv2; otherwise, the program is ill-formed.
3047 if (RefRelationship == Sema::Ref_Related) {
3048 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3049 // we would be reference-compatible or reference-compatible with
3050 // added qualification. But that wasn't the case, so the reference
3051 // initialization fails.
3052 return ICS;
3053 }
3054
3055 // If at least one of the types is a class type, the types are not
3056 // related, and we aren't allowed any user conversions, the
3057 // reference binding fails. This case is important for breaking
3058 // recursion, since TryImplicitConversion below will attempt to
3059 // create a temporary through the use of a copy constructor.
3060 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3061 (T1->isRecordType() || T2->isRecordType()))
3062 return ICS;
3063
3064 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003065 // When a parameter of reference type is not bound directly to
3066 // an argument expression, the conversion sequence is the one
3067 // required to convert the argument expression to the
3068 // underlying type of the reference according to
3069 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3070 // to copy-initializing a temporary of the underlying type with
3071 // the argument expression. Any difference in top-level
3072 // cv-qualification is subsumed by the initialization itself
3073 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003074 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3075 /*AllowExplicit=*/false,
3076 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003077
3078 // Of course, that's still a reference binding.
3079 if (ICS.isStandard()) {
3080 ICS.Standard.ReferenceBinding = true;
3081 ICS.Standard.RRefBinding = isRValRef;
3082 } else if (ICS.isUserDefined()) {
3083 ICS.UserDefined.After.ReferenceBinding = true;
3084 ICS.UserDefined.After.RRefBinding = isRValRef;
3085 }
3086 return ICS;
3087}
3088
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003089/// TryCopyInitialization - Try to copy-initialize a value of type
3090/// ToType from the expression From. Return the implicit conversion
3091/// sequence required to pass this argument, which may be a bad
3092/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003093/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003094/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003095static ImplicitConversionSequence
3096TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003097 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003098 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003099 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003100 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003101 /*FIXME:*/From->getLocStart(),
3102 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003103 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003104
John McCall5c32be02010-08-24 20:38:10 +00003105 return TryImplicitConversion(S, From, ToType,
3106 SuppressUserConversions,
3107 /*AllowExplicit=*/false,
3108 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003109}
3110
Douglas Gregor436424c2008-11-18 23:14:02 +00003111/// TryObjectArgumentInitialization - Try to initialize the object
3112/// parameter of the given member function (@c Method) from the
3113/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003114static ImplicitConversionSequence
3115TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3116 CXXMethodDecl *Method,
3117 CXXRecordDecl *ActingContext) {
3118 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003119 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3120 // const volatile object.
3121 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3122 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003123 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003124
3125 // Set up the conversion sequence as a "bad" conversion, to allow us
3126 // to exit early.
3127 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003128
3129 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003130 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003131 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003132 FromType = PT->getPointeeType();
3133
3134 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003135
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003136 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003137 // where X is the class of which the function is a member
3138 // (C++ [over.match.funcs]p4). However, when finding an implicit
3139 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003140 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003141 // (C++ [over.match.funcs]p5). We perform a simplified version of
3142 // reference binding here, that allows class rvalues to bind to
3143 // non-constant references.
3144
3145 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3146 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003147 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003148 if (ImplicitParamType.getCVRQualifiers()
3149 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003150 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003151 ICS.setBad(BadConversionSequence::bad_qualifiers,
3152 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003153 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003154 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003155
3156 // Check that we have either the same type or a derived type. It
3157 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003158 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003159 ImplicitConversionKind SecondKind;
3160 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3161 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003162 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003163 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003164 else {
John McCall65eb8792010-02-25 01:37:24 +00003165 ICS.setBad(BadConversionSequence::unrelated_class,
3166 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003167 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003168 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003169
3170 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003171 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003172 ICS.Standard.setAsIdentityConversion();
3173 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003174 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003175 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003176 ICS.Standard.ReferenceBinding = true;
3177 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003178 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003179 return ICS;
3180}
3181
3182/// PerformObjectArgumentInitialization - Perform initialization of
3183/// the implicit object parameter for the given Method with the given
3184/// expression.
3185bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003186Sema::PerformObjectArgumentInitialization(Expr *&From,
3187 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003188 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003189 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003190 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003191 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003192 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003193
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003194 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003195 FromRecordType = PT->getPointeeType();
3196 DestType = Method->getThisType(Context);
3197 } else {
3198 FromRecordType = From->getType();
3199 DestType = ImplicitParamRecordType;
3200 }
3201
John McCall6e9f8f62009-12-03 04:06:58 +00003202 // Note that we always use the true parent context when performing
3203 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003204 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003205 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003206 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003207 if (ICS.isBad()) {
3208 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3209 Qualifiers FromQs = FromRecordType.getQualifiers();
3210 Qualifiers ToQs = DestType.getQualifiers();
3211 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3212 if (CVR) {
3213 Diag(From->getSourceRange().getBegin(),
3214 diag::err_member_function_call_bad_cvr)
3215 << Method->getDeclName() << FromRecordType << (CVR - 1)
3216 << From->getSourceRange();
3217 Diag(Method->getLocation(), diag::note_previous_decl)
3218 << Method->getDeclName();
3219 return true;
3220 }
3221 }
3222
Douglas Gregor436424c2008-11-18 23:14:02 +00003223 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003224 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003225 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003226 }
Mike Stump11289f42009-09-09 15:08:12 +00003227
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003228 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003229 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003230
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003231 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003232 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003233 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003234 return false;
3235}
3236
Douglas Gregor5fb53972009-01-14 15:45:31 +00003237/// TryContextuallyConvertToBool - Attempt to contextually convert the
3238/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003239static ImplicitConversionSequence
3240TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003241 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003242 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003243 // FIXME: Are these flags correct?
3244 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003245 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003246 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003247}
3248
3249/// PerformContextuallyConvertToBool - Perform a contextual conversion
3250/// of the expression From to bool (C++0x [conv]p3).
3251bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003252 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003253 if (!ICS.isBad())
3254 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003255
Fariborz Jahanian76197412009-11-18 18:26:29 +00003256 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003257 return Diag(From->getSourceRange().getBegin(),
3258 diag::err_typecheck_bool_condition)
3259 << From->getType() << From->getSourceRange();
3260 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003261}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003262
3263/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3264/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003265static ImplicitConversionSequence
3266TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3267 QualType Ty = S.Context.getObjCIdType();
3268 return TryImplicitConversion(S, From, Ty,
3269 // FIXME: Are these flags correct?
3270 /*SuppressUserConversions=*/false,
3271 /*AllowExplicit=*/true,
3272 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003273}
John McCall5c32be02010-08-24 20:38:10 +00003274
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003275/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3276/// of the expression From to 'id'.
3277bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003278 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003279 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003280 if (!ICS.isBad())
3281 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3282 return true;
3283}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003284
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003285/// \brief Attempt to convert the given expression to an integral or
3286/// enumeration type.
3287///
3288/// This routine will attempt to convert an expression of class type to an
3289/// integral or enumeration type, if that class type only has a single
3290/// conversion to an integral or enumeration type.
3291///
Douglas Gregor4799d032010-06-30 00:20:43 +00003292/// \param Loc The source location of the construct that requires the
3293/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003294///
Douglas Gregor4799d032010-06-30 00:20:43 +00003295/// \param FromE The expression we're converting from.
3296///
3297/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3298/// have integral or enumeration type.
3299///
3300/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3301/// incomplete class type.
3302///
3303/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3304/// explicit conversion function (because no implicit conversion functions
3305/// were available). This is a recovery mode.
3306///
3307/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3308/// showing which conversion was picked.
3309///
3310/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3311/// conversion function that could convert to integral or enumeration type.
3312///
3313/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3314/// usable conversion function.
3315///
3316/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3317/// function, which may be an extension in this case.
3318///
3319/// \returns The expression, converted to an integral or enumeration type if
3320/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003321ExprResult
John McCallb268a282010-08-23 23:25:46 +00003322Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003323 const PartialDiagnostic &NotIntDiag,
3324 const PartialDiagnostic &IncompleteDiag,
3325 const PartialDiagnostic &ExplicitConvDiag,
3326 const PartialDiagnostic &ExplicitConvNote,
3327 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003328 const PartialDiagnostic &AmbigNote,
3329 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003330 // We can't perform any more checking for type-dependent expressions.
3331 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003332 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003333
3334 // If the expression already has integral or enumeration type, we're golden.
3335 QualType T = From->getType();
3336 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003337 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003338
3339 // FIXME: Check for missing '()' if T is a function type?
3340
3341 // If we don't have a class type in C++, there's no way we can get an
3342 // expression of integral or enumeration type.
3343 const RecordType *RecordTy = T->getAs<RecordType>();
3344 if (!RecordTy || !getLangOptions().CPlusPlus) {
3345 Diag(Loc, NotIntDiag)
3346 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003347 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003348 }
3349
3350 // We must have a complete class type.
3351 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003352 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003353
3354 // Look for a conversion to an integral or enumeration type.
3355 UnresolvedSet<4> ViableConversions;
3356 UnresolvedSet<4> ExplicitConversions;
3357 const UnresolvedSetImpl *Conversions
3358 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3359
3360 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3361 E = Conversions->end();
3362 I != E;
3363 ++I) {
3364 if (CXXConversionDecl *Conversion
3365 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3366 if (Conversion->getConversionType().getNonReferenceType()
3367 ->isIntegralOrEnumerationType()) {
3368 if (Conversion->isExplicit())
3369 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3370 else
3371 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3372 }
3373 }
3374
3375 switch (ViableConversions.size()) {
3376 case 0:
3377 if (ExplicitConversions.size() == 1) {
3378 DeclAccessPair Found = ExplicitConversions[0];
3379 CXXConversionDecl *Conversion
3380 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3381
3382 // The user probably meant to invoke the given explicit
3383 // conversion; use it.
3384 QualType ConvTy
3385 = Conversion->getConversionType().getNonReferenceType();
3386 std::string TypeStr;
3387 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3388
3389 Diag(Loc, ExplicitConvDiag)
3390 << T << ConvTy
3391 << FixItHint::CreateInsertion(From->getLocStart(),
3392 "static_cast<" + TypeStr + ">(")
3393 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3394 ")");
3395 Diag(Conversion->getLocation(), ExplicitConvNote)
3396 << ConvTy->isEnumeralType() << ConvTy;
3397
3398 // If we aren't in a SFINAE context, build a call to the
3399 // explicit conversion function.
3400 if (isSFINAEContext())
3401 return ExprError();
3402
3403 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003404 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003405 }
3406
3407 // We'll complain below about a non-integral condition type.
3408 break;
3409
3410 case 1: {
3411 // Apply this conversion.
3412 DeclAccessPair Found = ViableConversions[0];
3413 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003414
3415 CXXConversionDecl *Conversion
3416 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3417 QualType ConvTy
3418 = Conversion->getConversionType().getNonReferenceType();
3419 if (ConvDiag.getDiagID()) {
3420 if (isSFINAEContext())
3421 return ExprError();
3422
3423 Diag(Loc, ConvDiag)
3424 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3425 }
3426
John McCallb268a282010-08-23 23:25:46 +00003427 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003428 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003429 break;
3430 }
3431
3432 default:
3433 Diag(Loc, AmbigDiag)
3434 << T << From->getSourceRange();
3435 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3436 CXXConversionDecl *Conv
3437 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3438 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3439 Diag(Conv->getLocation(), AmbigNote)
3440 << ConvTy->isEnumeralType() << ConvTy;
3441 }
John McCallb268a282010-08-23 23:25:46 +00003442 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003443 }
3444
Douglas Gregor5823da32010-06-29 23:25:20 +00003445 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003446 Diag(Loc, NotIntDiag)
3447 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003448
John McCallb268a282010-08-23 23:25:46 +00003449 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003450}
3451
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003452/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003453/// candidate functions, using the given function call arguments. If
3454/// @p SuppressUserConversions, then don't allow user-defined
3455/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003456///
3457/// \para PartialOverloading true if we are performing "partial" overloading
3458/// based on an incomplete set of function arguments. This feature is used by
3459/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003460void
3461Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003462 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003463 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003464 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003465 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003466 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003467 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003468 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003469 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003470 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003471 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003472
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003473 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003474 if (!isa<CXXConstructorDecl>(Method)) {
3475 // If we get here, it's because we're calling a member function
3476 // that is named without a member access expression (e.g.,
3477 // "this->f") that was either written explicitly or created
3478 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003479 // function, e.g., X::f(). We use an empty type for the implied
3480 // object argument (C++ [over.call.func]p3), and the acting context
3481 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003482 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003483 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003484 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003485 return;
3486 }
3487 // We treat a constructor like a non-member function, since its object
3488 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003489 }
3490
Douglas Gregorff7028a2009-11-13 23:59:09 +00003491 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003492 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003493
Douglas Gregor27381f32009-11-23 12:27:39 +00003494 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003495 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003496
Douglas Gregorffe14e32009-11-14 01:20:54 +00003497 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3498 // C++ [class.copy]p3:
3499 // A member function template is never instantiated to perform the copy
3500 // of a class object to an object of its class type.
3501 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3502 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003503 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003504 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3505 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003506 return;
3507 }
3508
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003509 // Add this candidate
3510 CandidateSet.push_back(OverloadCandidate());
3511 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003512 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003513 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003514 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003515 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003516 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003517
3518 unsigned NumArgsInProto = Proto->getNumArgs();
3519
3520 // (C++ 13.3.2p2): A candidate function having fewer than m
3521 // parameters is viable only if it has an ellipsis in its parameter
3522 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003523 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3524 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003525 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003526 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003527 return;
3528 }
3529
3530 // (C++ 13.3.2p2): A candidate function having more than m parameters
3531 // is viable only if the (m+1)st parameter has a default argument
3532 // (8.3.6). For the purposes of overload resolution, the
3533 // parameter list is truncated on the right, so that there are
3534 // exactly m parameters.
3535 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003536 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003537 // Not enough arguments.
3538 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003539 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003540 return;
3541 }
3542
3543 // Determine the implicit conversion sequences for each of the
3544 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003545 Candidate.Conversions.resize(NumArgs);
3546 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3547 if (ArgIdx < NumArgsInProto) {
3548 // (C++ 13.3.2p3): for F to be a viable function, there shall
3549 // exist for each argument an implicit conversion sequence
3550 // (13.3.3.1) that converts that argument to the corresponding
3551 // parameter of F.
3552 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003553 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003554 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003555 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003556 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003557 if (Candidate.Conversions[ArgIdx].isBad()) {
3558 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003559 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003560 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003561 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003562 } else {
3563 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3564 // argument for which there is no corresponding parameter is
3565 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003566 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003567 }
3568 }
3569}
3570
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003571/// \brief Add all of the function declarations in the given function set to
3572/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003573void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003574 Expr **Args, unsigned NumArgs,
3575 OverloadCandidateSet& CandidateSet,
3576 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003577 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003578 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3579 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003580 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003581 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003582 cast<CXXMethodDecl>(FD)->getParent(),
3583 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003584 CandidateSet, SuppressUserConversions);
3585 else
John McCalla0296f72010-03-19 07:35:19 +00003586 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003587 SuppressUserConversions);
3588 } else {
John McCalla0296f72010-03-19 07:35:19 +00003589 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003590 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3591 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003592 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003593 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003594 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003595 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003596 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003597 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003598 else
John McCalla0296f72010-03-19 07:35:19 +00003599 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003600 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003601 Args, NumArgs, CandidateSet,
3602 SuppressUserConversions);
3603 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003604 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003605}
3606
John McCallf0f1cf02009-11-17 07:50:12 +00003607/// AddMethodCandidate - Adds a named decl (which is some kind of
3608/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003609void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003610 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003611 Expr **Args, unsigned NumArgs,
3612 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003613 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003614 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003615 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003616
3617 if (isa<UsingShadowDecl>(Decl))
3618 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3619
3620 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3621 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3622 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003623 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3624 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003625 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003626 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003627 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003628 } else {
John McCalla0296f72010-03-19 07:35:19 +00003629 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003630 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003631 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003632 }
3633}
3634
Douglas Gregor436424c2008-11-18 23:14:02 +00003635/// AddMethodCandidate - Adds the given C++ member function to the set
3636/// of candidate functions, using the given function call arguments
3637/// and the object argument (@c Object). For example, in a call
3638/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3639/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3640/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003641/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003642void
John McCalla0296f72010-03-19 07:35:19 +00003643Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003644 CXXRecordDecl *ActingContext, QualType ObjectType,
3645 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003646 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003647 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003648 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003649 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003650 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003651 assert(!isa<CXXConstructorDecl>(Method) &&
3652 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003653
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003654 if (!CandidateSet.isNewCandidate(Method))
3655 return;
3656
Douglas Gregor27381f32009-11-23 12:27:39 +00003657 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003658 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003659
Douglas Gregor436424c2008-11-18 23:14:02 +00003660 // Add this candidate
3661 CandidateSet.push_back(OverloadCandidate());
3662 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003663 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003664 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003665 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003666 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003667
3668 unsigned NumArgsInProto = Proto->getNumArgs();
3669
3670 // (C++ 13.3.2p2): A candidate function having fewer than m
3671 // parameters is viable only if it has an ellipsis in its parameter
3672 // list (8.3.5).
3673 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3674 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003675 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003676 return;
3677 }
3678
3679 // (C++ 13.3.2p2): A candidate function having more than m parameters
3680 // is viable only if the (m+1)st parameter has a default argument
3681 // (8.3.6). For the purposes of overload resolution, the
3682 // parameter list is truncated on the right, so that there are
3683 // exactly m parameters.
3684 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3685 if (NumArgs < MinRequiredArgs) {
3686 // Not enough arguments.
3687 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003688 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003689 return;
3690 }
3691
3692 Candidate.Viable = true;
3693 Candidate.Conversions.resize(NumArgs + 1);
3694
John McCall6e9f8f62009-12-03 04:06:58 +00003695 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003696 // The implicit object argument is ignored.
3697 Candidate.IgnoreObjectArgument = true;
3698 else {
3699 // Determine the implicit conversion sequence for the object
3700 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003701 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003702 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3703 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003704 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003705 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003706 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003707 return;
3708 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003709 }
3710
3711 // Determine the implicit conversion sequences for each of the
3712 // arguments.
3713 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3714 if (ArgIdx < NumArgsInProto) {
3715 // (C++ 13.3.2p3): for F to be a viable function, there shall
3716 // exist for each argument an implicit conversion sequence
3717 // (13.3.3.1) that converts that argument to the corresponding
3718 // parameter of F.
3719 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003720 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003721 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003722 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003723 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003724 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003725 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003726 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003727 break;
3728 }
3729 } else {
3730 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3731 // argument for which there is no corresponding parameter is
3732 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003733 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003734 }
3735 }
3736}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003737
Douglas Gregor97628d62009-08-21 00:16:32 +00003738/// \brief Add a C++ member function template as a candidate to the candidate
3739/// set, using template argument deduction to produce an appropriate member
3740/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003741void
Douglas Gregor97628d62009-08-21 00:16:32 +00003742Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003743 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003744 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003745 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003746 QualType ObjectType,
3747 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003748 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003749 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003750 if (!CandidateSet.isNewCandidate(MethodTmpl))
3751 return;
3752
Douglas Gregor97628d62009-08-21 00:16:32 +00003753 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003754 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003755 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003756 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003757 // candidate functions in the usual way.113) A given name can refer to one
3758 // or more function templates and also to a set of overloaded non-template
3759 // functions. In such a case, the candidate functions generated from each
3760 // function template are combined with the set of non-template candidate
3761 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003762 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003763 FunctionDecl *Specialization = 0;
3764 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003765 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003766 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003767 CandidateSet.push_back(OverloadCandidate());
3768 OverloadCandidate &Candidate = CandidateSet.back();
3769 Candidate.FoundDecl = FoundDecl;
3770 Candidate.Function = MethodTmpl->getTemplatedDecl();
3771 Candidate.Viable = false;
3772 Candidate.FailureKind = ovl_fail_bad_deduction;
3773 Candidate.IsSurrogate = false;
3774 Candidate.IgnoreObjectArgument = false;
3775 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3776 Info);
3777 return;
3778 }
Mike Stump11289f42009-09-09 15:08:12 +00003779
Douglas Gregor97628d62009-08-21 00:16:32 +00003780 // Add the function template specialization produced by template argument
3781 // deduction as a candidate.
3782 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003783 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003784 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003785 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003786 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003787 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003788}
3789
Douglas Gregor05155d82009-08-21 23:19:43 +00003790/// \brief Add a C++ function template specialization as a candidate
3791/// in the candidate set, using template argument deduction to produce
3792/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003793void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003794Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003795 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003796 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003797 Expr **Args, unsigned NumArgs,
3798 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003799 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003800 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3801 return;
3802
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003803 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003804 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003805 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003806 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003807 // candidate functions in the usual way.113) A given name can refer to one
3808 // or more function templates and also to a set of overloaded non-template
3809 // functions. In such a case, the candidate functions generated from each
3810 // function template are combined with the set of non-template candidate
3811 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003812 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003813 FunctionDecl *Specialization = 0;
3814 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003815 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003816 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003817 CandidateSet.push_back(OverloadCandidate());
3818 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003819 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003820 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3821 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003822 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003823 Candidate.IsSurrogate = false;
3824 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003825 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3826 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003827 return;
3828 }
Mike Stump11289f42009-09-09 15:08:12 +00003829
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003830 // Add the function template specialization produced by template argument
3831 // deduction as a candidate.
3832 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003833 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003834 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003835}
Mike Stump11289f42009-09-09 15:08:12 +00003836
Douglas Gregora1f013e2008-11-07 22:36:19 +00003837/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003838/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003839/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003840/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003841/// (which may or may not be the same type as the type that the
3842/// conversion function produces).
3843void
3844Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003845 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003846 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003847 Expr *From, QualType ToType,
3848 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003849 assert(!Conversion->getDescribedFunctionTemplate() &&
3850 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003851 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003852 if (!CandidateSet.isNewCandidate(Conversion))
3853 return;
3854
Douglas Gregor27381f32009-11-23 12:27:39 +00003855 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003856 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003857
Douglas Gregora1f013e2008-11-07 22:36:19 +00003858 // Add this candidate
3859 CandidateSet.push_back(OverloadCandidate());
3860 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003861 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003862 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003863 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003864 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003865 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003866 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003867 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003868 Candidate.Viable = true;
3869 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003870
Douglas Gregor6affc782010-08-19 15:37:02 +00003871 // C++ [over.match.funcs]p4:
3872 // For conversion functions, the function is considered to be a member of
3873 // the class of the implicit implied object argument for the purpose of
3874 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003875 //
3876 // Determine the implicit conversion sequence for the implicit
3877 // object parameter.
3878 QualType ImplicitParamType = From->getType();
3879 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3880 ImplicitParamType = FromPtrType->getPointeeType();
3881 CXXRecordDecl *ConversionContext
3882 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3883
3884 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003885 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003886 ConversionContext);
3887
John McCall0d1da222010-01-12 00:44:57 +00003888 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003889 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003890 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003891 return;
3892 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003893
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003894 // We won't go through a user-define type conversion function to convert a
3895 // derived to base as such conversions are given Conversion Rank. They only
3896 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3897 QualType FromCanon
3898 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3899 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3900 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3901 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003902 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003903 return;
3904 }
3905
Douglas Gregora1f013e2008-11-07 22:36:19 +00003906 // To determine what the conversion from the result of calling the
3907 // conversion function to the type we're eventually trying to
3908 // convert to (ToType), we need to synthesize a call to the
3909 // conversion function and attempt copy initialization from it. This
3910 // makes sure that we get the right semantics with respect to
3911 // lvalues/rvalues and the type. Fortunately, we can allocate this
3912 // call on the stack and we don't need its arguments to be
3913 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003914 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003915 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003916 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3917 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003918 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003919 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003920
Douglas Gregor72ebdab2010-11-13 19:36:57 +00003921 QualType CallResultType
3922 = Conversion->getConversionType().getNonLValueExprType(Context);
3923 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3924 Candidate.Viable = false;
3925 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3926 return;
3927 }
3928
John McCall7decc9e2010-11-18 06:31:45 +00003929 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3930
Mike Stump11289f42009-09-09 15:08:12 +00003931 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003932 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3933 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00003934 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00003935 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003936 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003937 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003938 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003939 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003940
John McCall0d1da222010-01-12 00:44:57 +00003941 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003942 case ImplicitConversionSequence::StandardConversion:
3943 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003944
3945 // C++ [over.ics.user]p3:
3946 // If the user-defined conversion is specified by a specialization of a
3947 // conversion function template, the second standard conversion sequence
3948 // shall have exact match rank.
3949 if (Conversion->getPrimaryTemplate() &&
3950 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3951 Candidate.Viable = false;
3952 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3953 }
3954
Douglas Gregora1f013e2008-11-07 22:36:19 +00003955 break;
3956
3957 case ImplicitConversionSequence::BadConversion:
3958 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003959 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003960 break;
3961
3962 default:
Mike Stump11289f42009-09-09 15:08:12 +00003963 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003964 "Can only end up with a standard conversion sequence or failure");
3965 }
3966}
3967
Douglas Gregor05155d82009-08-21 23:19:43 +00003968/// \brief Adds a conversion function template specialization
3969/// candidate to the overload set, using template argument deduction
3970/// to deduce the template arguments of the conversion function
3971/// template from the type that we are converting to (C++
3972/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003973void
Douglas Gregor05155d82009-08-21 23:19:43 +00003974Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003975 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003976 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003977 Expr *From, QualType ToType,
3978 OverloadCandidateSet &CandidateSet) {
3979 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3980 "Only conversion function templates permitted here");
3981
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003982 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3983 return;
3984
John McCallbc077cf2010-02-08 23:07:23 +00003985 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003986 CXXConversionDecl *Specialization = 0;
3987 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003988 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003989 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003990 CandidateSet.push_back(OverloadCandidate());
3991 OverloadCandidate &Candidate = CandidateSet.back();
3992 Candidate.FoundDecl = FoundDecl;
3993 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3994 Candidate.Viable = false;
3995 Candidate.FailureKind = ovl_fail_bad_deduction;
3996 Candidate.IsSurrogate = false;
3997 Candidate.IgnoreObjectArgument = false;
3998 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3999 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004000 return;
4001 }
Mike Stump11289f42009-09-09 15:08:12 +00004002
Douglas Gregor05155d82009-08-21 23:19:43 +00004003 // Add the conversion function template specialization produced by
4004 // template argument deduction as a candidate.
4005 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004006 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004007 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004008}
4009
Douglas Gregorab7897a2008-11-19 22:57:39 +00004010/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4011/// converts the given @c Object to a function pointer via the
4012/// conversion function @c Conversion, and then attempts to call it
4013/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4014/// the type of function that we'll eventually be calling.
4015void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004016 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004017 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004018 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00004019 QualType ObjectType,
4020 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004021 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004022 if (!CandidateSet.isNewCandidate(Conversion))
4023 return;
4024
Douglas Gregor27381f32009-11-23 12:27:39 +00004025 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004026 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004027
Douglas Gregorab7897a2008-11-19 22:57:39 +00004028 CandidateSet.push_back(OverloadCandidate());
4029 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004030 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004031 Candidate.Function = 0;
4032 Candidate.Surrogate = Conversion;
4033 Candidate.Viable = true;
4034 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004035 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004036 Candidate.Conversions.resize(NumArgs + 1);
4037
4038 // Determine the implicit conversion sequence for the implicit
4039 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004040 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004041 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4042 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004043 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004044 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004045 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004046 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004047 return;
4048 }
4049
4050 // The first conversion is actually a user-defined conversion whose
4051 // first conversion is ObjectInit's standard conversion (which is
4052 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004053 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004054 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004055 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004056 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00004057 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004058 = Candidate.Conversions[0].UserDefined.Before;
4059 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4060
Mike Stump11289f42009-09-09 15:08:12 +00004061 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004062 unsigned NumArgsInProto = Proto->getNumArgs();
4063
4064 // (C++ 13.3.2p2): A candidate function having fewer than m
4065 // parameters is viable only if it has an ellipsis in its parameter
4066 // list (8.3.5).
4067 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4068 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004069 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004070 return;
4071 }
4072
4073 // Function types don't have any default arguments, so just check if
4074 // we have enough arguments.
4075 if (NumArgs < NumArgsInProto) {
4076 // Not enough arguments.
4077 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004078 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004079 return;
4080 }
4081
4082 // Determine the implicit conversion sequences for each of the
4083 // arguments.
4084 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4085 if (ArgIdx < NumArgsInProto) {
4086 // (C++ 13.3.2p3): for F to be a viable function, there shall
4087 // exist for each argument an implicit conversion sequence
4088 // (13.3.3.1) that converts that argument to the corresponding
4089 // parameter of F.
4090 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004091 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004092 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004093 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004094 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004095 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004096 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004097 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004098 break;
4099 }
4100 } else {
4101 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4102 // argument for which there is no corresponding parameter is
4103 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004104 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004105 }
4106 }
4107}
4108
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004109/// \brief Add overload candidates for overloaded operators that are
4110/// member functions.
4111///
4112/// Add the overloaded operator candidates that are member functions
4113/// for the operator Op that was used in an operator expression such
4114/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4115/// CandidateSet will store the added overload candidates. (C++
4116/// [over.match.oper]).
4117void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4118 SourceLocation OpLoc,
4119 Expr **Args, unsigned NumArgs,
4120 OverloadCandidateSet& CandidateSet,
4121 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004122 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4123
4124 // C++ [over.match.oper]p3:
4125 // For a unary operator @ with an operand of a type whose
4126 // cv-unqualified version is T1, and for a binary operator @ with
4127 // a left operand of a type whose cv-unqualified version is T1 and
4128 // a right operand of a type whose cv-unqualified version is T2,
4129 // three sets of candidate functions, designated member
4130 // candidates, non-member candidates and built-in candidates, are
4131 // constructed as follows:
4132 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004133
4134 // -- If T1 is a class type, the set of member candidates is the
4135 // result of the qualified lookup of T1::operator@
4136 // (13.3.1.1.1); otherwise, the set of member candidates is
4137 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004138 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004139 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004140 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004141 return;
Mike Stump11289f42009-09-09 15:08:12 +00004142
John McCall27b18f82009-11-17 02:14:36 +00004143 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4144 LookupQualifiedName(Operators, T1Rec->getDecl());
4145 Operators.suppressDiagnostics();
4146
Mike Stump11289f42009-09-09 15:08:12 +00004147 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004148 OperEnd = Operators.end();
4149 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004150 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004151 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004152 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004153 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004154 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004155}
4156
Douglas Gregora11693b2008-11-12 17:17:38 +00004157/// AddBuiltinCandidate - Add a candidate for a built-in
4158/// operator. ResultTy and ParamTys are the result and parameter types
4159/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004160/// arguments being passed to the candidate. IsAssignmentOperator
4161/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004162/// operator. NumContextualBoolArguments is the number of arguments
4163/// (at the beginning of the argument list) that will be contextually
4164/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004165void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004166 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004167 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004168 bool IsAssignmentOperator,
4169 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004170 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004171 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004172
Douglas Gregora11693b2008-11-12 17:17:38 +00004173 // Add this candidate
4174 CandidateSet.push_back(OverloadCandidate());
4175 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004176 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004177 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004178 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004179 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004180 Candidate.BuiltinTypes.ResultTy = ResultTy;
4181 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4182 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4183
4184 // Determine the implicit conversion sequences for each of the
4185 // arguments.
4186 Candidate.Viable = true;
4187 Candidate.Conversions.resize(NumArgs);
4188 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004189 // C++ [over.match.oper]p4:
4190 // For the built-in assignment operators, conversions of the
4191 // left operand are restricted as follows:
4192 // -- no temporaries are introduced to hold the left operand, and
4193 // -- no user-defined conversions are applied to the left
4194 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004195 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004196 //
4197 // We block these conversions by turning off user-defined
4198 // conversions, since that is the only way that initialization of
4199 // a reference to a non-class type can occur from something that
4200 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004201 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004202 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004203 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004204 Candidate.Conversions[ArgIdx]
4205 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004206 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004207 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004208 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004209 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004210 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004211 }
John McCall0d1da222010-01-12 00:44:57 +00004212 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004213 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004214 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004215 break;
4216 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004217 }
4218}
4219
4220/// BuiltinCandidateTypeSet - A set of types that will be used for the
4221/// candidate operator functions for built-in operators (C++
4222/// [over.built]). The types are separated into pointer types and
4223/// enumeration types.
4224class BuiltinCandidateTypeSet {
4225 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004226 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004227
4228 /// PointerTypes - The set of pointer types that will be used in the
4229 /// built-in candidates.
4230 TypeSet PointerTypes;
4231
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004232 /// MemberPointerTypes - The set of member pointer types that will be
4233 /// used in the built-in candidates.
4234 TypeSet MemberPointerTypes;
4235
Douglas Gregora11693b2008-11-12 17:17:38 +00004236 /// EnumerationTypes - The set of enumeration types that will be
4237 /// used in the built-in candidates.
4238 TypeSet EnumerationTypes;
4239
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004240 /// \brief The set of vector types that will be used in the built-in
4241 /// candidates.
4242 TypeSet VectorTypes;
4243
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004244 /// Sema - The semantic analysis instance where we are building the
4245 /// candidate type set.
4246 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004247
Douglas Gregora11693b2008-11-12 17:17:38 +00004248 /// Context - The AST context in which we will build the type sets.
4249 ASTContext &Context;
4250
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004251 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4252 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004253 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004254
4255public:
4256 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004257 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004258
Mike Stump11289f42009-09-09 15:08:12 +00004259 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004260 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004261
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004262 void AddTypesConvertedFrom(QualType Ty,
4263 SourceLocation Loc,
4264 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004265 bool AllowExplicitConversions,
4266 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004267
4268 /// pointer_begin - First pointer type found;
4269 iterator pointer_begin() { return PointerTypes.begin(); }
4270
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004271 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004272 iterator pointer_end() { return PointerTypes.end(); }
4273
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004274 /// member_pointer_begin - First member pointer type found;
4275 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4276
4277 /// member_pointer_end - Past the last member pointer type found;
4278 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4279
Douglas Gregora11693b2008-11-12 17:17:38 +00004280 /// enumeration_begin - First enumeration type found;
4281 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4282
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004283 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004284 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004285
4286 iterator vector_begin() { return VectorTypes.begin(); }
4287 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004288};
4289
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004290/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004291/// the set of pointer types along with any more-qualified variants of
4292/// that type. For example, if @p Ty is "int const *", this routine
4293/// will add "int const *", "int const volatile *", "int const
4294/// restrict *", and "int const volatile restrict *" to the set of
4295/// pointer types. Returns true if the add of @p Ty itself succeeded,
4296/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004297///
4298/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004299bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004300BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4301 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004302
Douglas Gregora11693b2008-11-12 17:17:38 +00004303 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004304 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004305 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004306
4307 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004308 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004309 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004310 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004311 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004312 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004313 buildObjCPtr = true;
4314 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004315 else
4316 assert(false && "type was not a pointer type!");
4317 }
4318 else
4319 PointeeTy = PointerTy->getPointeeType();
4320
Sebastian Redl4990a632009-11-18 20:39:26 +00004321 // Don't add qualified variants of arrays. For one, they're not allowed
4322 // (the qualifier would sink to the element type), and for another, the
4323 // only overload situation where it matters is subscript or pointer +- int,
4324 // and those shouldn't have qualifier variants anyway.
4325 if (PointeeTy->isArrayType())
4326 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004327 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004328 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004329 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004330 bool hasVolatile = VisibleQuals.hasVolatile();
4331 bool hasRestrict = VisibleQuals.hasRestrict();
4332
John McCall8ccfcb52009-09-24 19:53:00 +00004333 // Iterate through all strict supersets of BaseCVR.
4334 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4335 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004336 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4337 // in the types.
4338 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4339 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004340 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004341 if (!buildObjCPtr)
4342 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4343 else
4344 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004345 }
4346
4347 return true;
4348}
4349
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004350/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4351/// to the set of pointer types along with any more-qualified variants of
4352/// that type. For example, if @p Ty is "int const *", this routine
4353/// will add "int const *", "int const volatile *", "int const
4354/// restrict *", and "int const volatile restrict *" to the set of
4355/// pointer types. Returns true if the add of @p Ty itself succeeded,
4356/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004357///
4358/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004359bool
4360BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4361 QualType Ty) {
4362 // Insert this type.
4363 if (!MemberPointerTypes.insert(Ty))
4364 return false;
4365
John McCall8ccfcb52009-09-24 19:53:00 +00004366 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4367 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004368
John McCall8ccfcb52009-09-24 19:53:00 +00004369 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004370 // Don't add qualified variants of arrays. For one, they're not allowed
4371 // (the qualifier would sink to the element type), and for another, the
4372 // only overload situation where it matters is subscript or pointer +- int,
4373 // and those shouldn't have qualifier variants anyway.
4374 if (PointeeTy->isArrayType())
4375 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004376 const Type *ClassTy = PointerTy->getClass();
4377
4378 // Iterate through all strict supersets of the pointee type's CVR
4379 // qualifiers.
4380 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4381 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4382 if ((CVR | BaseCVR) != CVR) continue;
4383
4384 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4385 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004386 }
4387
4388 return true;
4389}
4390
Douglas Gregora11693b2008-11-12 17:17:38 +00004391/// AddTypesConvertedFrom - Add each of the types to which the type @p
4392/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004393/// primarily interested in pointer types and enumeration types. We also
4394/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004395/// AllowUserConversions is true if we should look at the conversion
4396/// functions of a class type, and AllowExplicitConversions if we
4397/// should also include the explicit conversion functions of a class
4398/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004399void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004400BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004401 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004402 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004403 bool AllowExplicitConversions,
4404 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004405 // Only deal with canonical types.
4406 Ty = Context.getCanonicalType(Ty);
4407
4408 // Look through reference types; they aren't part of the type of an
4409 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004410 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004411 Ty = RefTy->getPointeeType();
4412
4413 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004414 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004415
Sebastian Redl65ae2002009-11-05 16:36:20 +00004416 // If we're dealing with an array type, decay to the pointer.
4417 if (Ty->isArrayType())
4418 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004419 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4420 PointerTypes.insert(Ty);
4421 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004422 // Insert our type, and its more-qualified variants, into the set
4423 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004424 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004425 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004426 } else if (Ty->isMemberPointerType()) {
4427 // Member pointers are far easier, since the pointee can't be converted.
4428 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4429 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004430 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004431 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004432 } else if (Ty->isVectorType()) {
4433 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004434 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004435 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004436 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004437 // No conversion functions in incomplete types.
4438 return;
4439 }
Mike Stump11289f42009-09-09 15:08:12 +00004440
Douglas Gregora11693b2008-11-12 17:17:38 +00004441 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004442 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004443 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004444 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004445 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004446 NamedDecl *D = I.getDecl();
4447 if (isa<UsingShadowDecl>(D))
4448 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004449
Mike Stump11289f42009-09-09 15:08:12 +00004450 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004451 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004452 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004453 continue;
4454
John McCallda4458e2010-03-31 01:36:47 +00004455 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004456 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004457 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004458 VisibleQuals);
4459 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004460 }
4461 }
4462 }
4463}
4464
Douglas Gregor84605ae2009-08-24 13:43:27 +00004465/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4466/// the volatile- and non-volatile-qualified assignment operators for the
4467/// given type to the candidate set.
4468static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4469 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004470 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004471 unsigned NumArgs,
4472 OverloadCandidateSet &CandidateSet) {
4473 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004474
Douglas Gregor84605ae2009-08-24 13:43:27 +00004475 // T& operator=(T&, T)
4476 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4477 ParamTypes[1] = T;
4478 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4479 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregor84605ae2009-08-24 13:43:27 +00004481 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4482 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004483 ParamTypes[0]
4484 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004485 ParamTypes[1] = T;
4486 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004487 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004488 }
4489}
Mike Stump11289f42009-09-09 15:08:12 +00004490
Sebastian Redl1054fae2009-10-25 17:03:50 +00004491/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4492/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004493static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4494 Qualifiers VRQuals;
4495 const RecordType *TyRec;
4496 if (const MemberPointerType *RHSMPType =
4497 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004498 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004499 else
4500 TyRec = ArgExpr->getType()->getAs<RecordType>();
4501 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004502 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004503 VRQuals.addVolatile();
4504 VRQuals.addRestrict();
4505 return VRQuals;
4506 }
4507
4508 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004509 if (!ClassDecl->hasDefinition())
4510 return VRQuals;
4511
John McCallad371252010-01-20 00:46:10 +00004512 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004513 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004514
John McCallad371252010-01-20 00:46:10 +00004515 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004516 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004517 NamedDecl *D = I.getDecl();
4518 if (isa<UsingShadowDecl>(D))
4519 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4520 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004521 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4522 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4523 CanTy = ResTypeRef->getPointeeType();
4524 // Need to go down the pointer/mempointer chain and add qualifiers
4525 // as see them.
4526 bool done = false;
4527 while (!done) {
4528 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4529 CanTy = ResTypePtr->getPointeeType();
4530 else if (const MemberPointerType *ResTypeMPtr =
4531 CanTy->getAs<MemberPointerType>())
4532 CanTy = ResTypeMPtr->getPointeeType();
4533 else
4534 done = true;
4535 if (CanTy.isVolatileQualified())
4536 VRQuals.addVolatile();
4537 if (CanTy.isRestrictQualified())
4538 VRQuals.addRestrict();
4539 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4540 return VRQuals;
4541 }
4542 }
4543 }
4544 return VRQuals;
4545}
John McCall52872982010-11-13 05:51:15 +00004546
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004547namespace {
John McCall52872982010-11-13 05:51:15 +00004548
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004549/// \brief Helper class to manage the addition of builtin operator overload
4550/// candidates. It provides shared state and utility methods used throughout
4551/// the process, as well as a helper method to add each group of builtin
4552/// operator overloads from the standard to a candidate set.
4553class BuiltinOperatorOverloadBuilder {
4554
4555 // FIXME: Clean up and document the static helpers for arithmetic types here.
John McCall52872982010-11-13 05:51:15 +00004556 // The "promoted arithmetic types" are the arithmetic
4557 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004558 static const unsigned FirstIntegralType = 3;
4559 static const unsigned LastIntegralType = 18;
4560 static const unsigned FirstPromotedIntegralType = 3,
4561 LastPromotedIntegralType = 9;
4562 static const unsigned FirstPromotedArithmeticType = 0,
4563 LastPromotedArithmeticType = 9;
4564 static const unsigned NumArithmeticTypes = 18;
4565
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004566 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes];
John McCall52872982010-11-13 05:51:15 +00004567
4568 // Accelerator table for performing the usual arithmetic conversions.
4569 // The rules are basically:
4570 // - if either is floating-point, use the wider floating-point
4571 // - if same signedness, use the higher rank
4572 // - if same size, use unsigned of the higher rank
4573 // - use the larger type
4574 // These rules, together with the axiom that higher ranks are
4575 // never smaller, are sufficient to precompute all of these results
4576 // *except* when dealing with signed types of higher rank.
4577 // (we could precompute SLL x UI for all known platforms, but it's
4578 // better not to make any assumptions).
4579 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4580 static PromT UsualArithmeticConversionsTypes
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004581 [LastPromotedArithmeticType][LastPromotedArithmeticType];
John McCall52872982010-11-13 05:51:15 +00004582 struct UsualArithmeticConversionsType {
4583 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4584 assert(L < LastPromotedArithmeticType);
4585 assert(R < LastPromotedArithmeticType);
4586 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4587
4588 // Fast path: the table gives us a concrete answer.
4589 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4590
4591 // Slow path: we need to compare widths.
4592 // An invariant is that the signed type has higher rank.
4593 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4594 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4595
4596 // If they're different widths, use the signed type.
4597 if (LW > RW) return LT;
4598 else if (LW > RW) return RT;
4599
4600 // Otherwise, use the unsigned type of the signed type's rank.
4601 if (L == SL || R == SL) return C.UnsignedLongTy;
4602 assert(L == SLL || R == SLL);
4603 return C.UnsignedLongLongTy;
4604 }
4605 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004606
4607 // Common instance state available to all overload candidate addition methods.
4608 Sema &S;
4609 Expr **Args;
4610 unsigned NumArgs;
4611 Qualifiers VisibleTypeConversionsQuals;
4612 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4613 OverloadCandidateSet &CandidateSet;
4614
4615 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4616 bool HasVolatile) {
4617 QualType ParamTypes[2] = {
4618 S.Context.getLValueReferenceType(CandidateTy),
4619 S.Context.IntTy
4620 };
4621
4622 // Non-volatile version.
4623 if (NumArgs == 1)
4624 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4625 else
4626 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4627
4628 // Use a heuristic to reduce number of builtin candidates in the set:
4629 // add volatile version only if there are conversions to a volatile type.
4630 if (HasVolatile) {
4631 ParamTypes[0] =
4632 S.Context.getLValueReferenceType(
4633 S.Context.getVolatileType(CandidateTy));
4634 if (NumArgs == 1)
4635 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4636 else
4637 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4638 }
4639 }
4640
4641public:
4642 BuiltinOperatorOverloadBuilder(
4643 Sema &S, Expr **Args, unsigned NumArgs,
4644 Qualifiers VisibleTypeConversionsQuals,
4645 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4646 OverloadCandidateSet &CandidateSet)
4647 : S(S), Args(Args), NumArgs(NumArgs),
4648 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
4649 CandidateTypes(CandidateTypes),
4650 CandidateSet(CandidateSet) {
4651 // Validate some of our static helper constants in debug builds.
4652 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
4653 "Invalid first promoted integral type");
4654 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4655 == &ASTContext::UnsignedLongLongTy &&
4656 "Invalid last promoted integral type");
4657 assert(ArithmeticTypes[FirstPromotedArithmeticType]
4658 == &ASTContext::FloatTy &&
4659 "Invalid first promoted arithmetic type");
4660 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4661 == &ASTContext::UnsignedLongLongTy &&
4662 "Invalid last promoted arithmetic type");
4663 }
4664
4665 // C++ [over.built]p3:
4666 //
4667 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4668 // is either volatile or empty, there exist candidate operator
4669 // functions of the form
4670 //
4671 // VQ T& operator++(VQ T&);
4672 // T operator++(VQ T&, int);
4673 //
4674 // C++ [over.built]p4:
4675 //
4676 // For every pair (T, VQ), where T is an arithmetic type other
4677 // than bool, and VQ is either volatile or empty, there exist
4678 // candidate operator functions of the form
4679 //
4680 // VQ T& operator--(VQ T&);
4681 // T operator--(VQ T&, int);
4682 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
4683 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4684 Arith < NumArithmeticTypes; ++Arith) {
4685 addPlusPlusMinusMinusStyleOverloads(
4686 S.Context.*ArithmeticTypes[Arith],
4687 VisibleTypeConversionsQuals.hasVolatile());
4688 }
4689 }
4690
4691 // C++ [over.built]p5:
4692 //
4693 // For every pair (T, VQ), where T is a cv-qualified or
4694 // cv-unqualified object type, and VQ is either volatile or
4695 // empty, there exist candidate operator functions of the form
4696 //
4697 // T*VQ& operator++(T*VQ&);
4698 // T*VQ& operator--(T*VQ&);
4699 // T* operator++(T*VQ&, int);
4700 // T* operator--(T*VQ&, int);
4701 void addPlusPlusMinusMinusPointerOverloads() {
4702 for (BuiltinCandidateTypeSet::iterator
4703 Ptr = CandidateTypes[0].pointer_begin(),
4704 PtrEnd = CandidateTypes[0].pointer_end();
4705 Ptr != PtrEnd; ++Ptr) {
4706 // Skip pointer types that aren't pointers to object types.
4707 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
4708 continue;
4709
4710 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4711 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4712 VisibleTypeConversionsQuals.hasVolatile()));
4713 }
4714 }
4715
4716 // C++ [over.built]p6:
4717 // For every cv-qualified or cv-unqualified object type T, there
4718 // exist candidate operator functions of the form
4719 //
4720 // T& operator*(T*);
4721 //
4722 // C++ [over.built]p7:
4723 // For every function type T, there exist candidate operator
4724 // functions of the form
4725 // T& operator*(T*);
4726 void addUnaryStarPointerOverloads() {
4727 for (BuiltinCandidateTypeSet::iterator
4728 Ptr = CandidateTypes[0].pointer_begin(),
4729 PtrEnd = CandidateTypes[0].pointer_end();
4730 Ptr != PtrEnd; ++Ptr) {
4731 QualType ParamTy = *Ptr;
4732 QualType PointeeTy = ParamTy->getPointeeType();
4733 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4734 &ParamTy, Args, 1, CandidateSet);
4735 }
4736 }
4737
4738 // C++ [over.built]p9:
4739 // For every promoted arithmetic type T, there exist candidate
4740 // operator functions of the form
4741 //
4742 // T operator+(T);
4743 // T operator-(T);
4744 void addUnaryPlusOrMinusArithmeticOverloads() {
4745 for (unsigned Arith = FirstPromotedArithmeticType;
4746 Arith < LastPromotedArithmeticType; ++Arith) {
4747 QualType ArithTy = S.Context.*ArithmeticTypes[Arith];
4748 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4749 }
4750
4751 // Extension: We also add these operators for vector types.
4752 for (BuiltinCandidateTypeSet::iterator
4753 Vec = CandidateTypes[0].vector_begin(),
4754 VecEnd = CandidateTypes[0].vector_end();
4755 Vec != VecEnd; ++Vec) {
4756 QualType VecTy = *Vec;
4757 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4758 }
4759 }
4760
4761 // C++ [over.built]p8:
4762 // For every type T, there exist candidate operator functions of
4763 // the form
4764 //
4765 // T* operator+(T*);
4766 void addUnaryPlusPointerOverloads() {
4767 for (BuiltinCandidateTypeSet::iterator
4768 Ptr = CandidateTypes[0].pointer_begin(),
4769 PtrEnd = CandidateTypes[0].pointer_end();
4770 Ptr != PtrEnd; ++Ptr) {
4771 QualType ParamTy = *Ptr;
4772 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4773 }
4774 }
4775
4776 // C++ [over.built]p10:
4777 // For every promoted integral type T, there exist candidate
4778 // operator functions of the form
4779 //
4780 // T operator~(T);
4781 void addUnaryTildePromotedIntegralOverloads() {
4782 for (unsigned Int = FirstPromotedIntegralType;
4783 Int < LastPromotedIntegralType; ++Int) {
4784 QualType IntTy = S.Context.*ArithmeticTypes[Int];
4785 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4786 }
4787
4788 // Extension: We also add this operator for vector types.
4789 for (BuiltinCandidateTypeSet::iterator
4790 Vec = CandidateTypes[0].vector_begin(),
4791 VecEnd = CandidateTypes[0].vector_end();
4792 Vec != VecEnd; ++Vec) {
4793 QualType VecTy = *Vec;
4794 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4795 }
4796 }
4797
4798 // C++ [over.match.oper]p16:
4799 // For every pointer to member type T, there exist candidate operator
4800 // functions of the form
4801 //
4802 // bool operator==(T,T);
4803 // bool operator!=(T,T);
4804 void addEqualEqualOrNotEqualMemberPointerOverloads() {
4805 /// Set of (canonical) types that we've already handled.
4806 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4807
4808 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4809 for (BuiltinCandidateTypeSet::iterator
4810 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4811 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4812 MemPtr != MemPtrEnd;
4813 ++MemPtr) {
4814 // Don't add the same builtin candidate twice.
4815 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
4816 continue;
4817
4818 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4819 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4820 CandidateSet);
4821 }
4822 }
4823 }
4824
4825 // C++ [over.built]p15:
4826 //
4827 // For every pointer or enumeration type T, there exist
4828 // candidate operator functions of the form
4829 //
4830 // bool operator<(T, T);
4831 // bool operator>(T, T);
4832 // bool operator<=(T, T);
4833 // bool operator>=(T, T);
4834 // bool operator==(T, T);
4835 // bool operator!=(T, T);
4836 void addRelationalPointerOrEnumeralOverloads(
4837 const llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4838 &UserDefinedBinaryOperators) {
4839 /// Set of (canonical) types that we've already handled.
4840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4841
4842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4843 for (BuiltinCandidateTypeSet::iterator
4844 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4845 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4846 Ptr != PtrEnd; ++Ptr) {
4847 // Don't add the same builtin candidate twice.
4848 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
4849 continue;
4850
4851 QualType ParamTypes[2] = { *Ptr, *Ptr };
4852 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4853 CandidateSet);
4854 }
4855 for (BuiltinCandidateTypeSet::iterator
4856 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4857 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4858 Enum != EnumEnd; ++Enum) {
4859 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
4860
4861 // Don't add the same builtin candidate twice.
4862 if (!AddedTypes.insert(CanonType))
4863 continue;
4864
4865 QualType ParamTypes[2] = { *Enum, *Enum };
4866 if (!UserDefinedBinaryOperators.count(
4867 std::make_pair(CanonType, CanonType)))
4868 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4869 CandidateSet);
4870 }
4871 }
4872 }
4873
4874 // C++ [over.built]p13:
4875 //
4876 // For every cv-qualified or cv-unqualified object type T
4877 // there exist candidate operator functions of the form
4878 //
4879 // T* operator+(T*, ptrdiff_t);
4880 // T& operator[](T*, ptrdiff_t); [BELOW]
4881 // T* operator-(T*, ptrdiff_t);
4882 // T* operator+(ptrdiff_t, T*);
4883 // T& operator[](ptrdiff_t, T*); [BELOW]
4884 //
4885 // C++ [over.built]p14:
4886 //
4887 // For every T, where T is a pointer to object type, there
4888 // exist candidate operator functions of the form
4889 //
4890 // ptrdiff_t operator-(T, T);
4891 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
4892 /// Set of (canonical) types that we've already handled.
4893 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4894
4895 for (int Arg = 0; Arg < 2; ++Arg) {
4896 QualType AsymetricParamTypes[2] = {
4897 S.Context.getPointerDiffType(),
4898 S.Context.getPointerDiffType(),
4899 };
4900 for (BuiltinCandidateTypeSet::iterator
4901 Ptr = CandidateTypes[Arg].pointer_begin(),
4902 PtrEnd = CandidateTypes[Arg].pointer_end();
4903 Ptr != PtrEnd; ++Ptr) {
4904 AsymetricParamTypes[Arg] = *Ptr;
4905 if (Arg == 0 || Op == OO_Plus) {
4906 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4907 // T* operator+(ptrdiff_t, T*);
4908 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
4909 CandidateSet);
4910 }
4911 if (Op == OO_Minus) {
4912 // ptrdiff_t operator-(T, T);
4913 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
4914 continue;
4915
4916 QualType ParamTypes[2] = { *Ptr, *Ptr };
4917 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
4918 Args, 2, CandidateSet);
4919 }
4920 }
4921 }
4922 }
4923
4924 // C++ [over.built]p12:
4925 //
4926 // For every pair of promoted arithmetic types L and R, there
4927 // exist candidate operator functions of the form
4928 //
4929 // LR operator*(L, R);
4930 // LR operator/(L, R);
4931 // LR operator+(L, R);
4932 // LR operator-(L, R);
4933 // bool operator<(L, R);
4934 // bool operator>(L, R);
4935 // bool operator<=(L, R);
4936 // bool operator>=(L, R);
4937 // bool operator==(L, R);
4938 // bool operator!=(L, R);
4939 //
4940 // where LR is the result of the usual arithmetic conversions
4941 // between types L and R.
4942 //
4943 // C++ [over.built]p24:
4944 //
4945 // For every pair of promoted arithmetic types L and R, there exist
4946 // candidate operator functions of the form
4947 //
4948 // LR operator?(bool, L, R);
4949 //
4950 // where LR is the result of the usual arithmetic conversions
4951 // between types L and R.
4952 // Our candidates ignore the first parameter.
4953 void addGenericBinaryArithmeticOverloads(bool isComparison) {
4954 for (unsigned Left = FirstPromotedArithmeticType;
4955 Left < LastPromotedArithmeticType; ++Left) {
4956 for (unsigned Right = FirstPromotedArithmeticType;
4957 Right < LastPromotedArithmeticType; ++Right) {
4958 QualType LandR[2] = { S.Context.*ArithmeticTypes[Left],
4959 S.Context.*ArithmeticTypes[Right] };
4960 QualType Result =
4961 isComparison ? S.Context.BoolTy
4962 : UsualArithmeticConversionsType::find(S.Context, Left,
4963 Right);
4964 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4965 }
4966 }
4967
4968 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4969 // conditional operator for vector types.
4970 for (BuiltinCandidateTypeSet::iterator
4971 Vec1 = CandidateTypes[0].vector_begin(),
4972 Vec1End = CandidateTypes[0].vector_end();
4973 Vec1 != Vec1End; ++Vec1) {
4974 for (BuiltinCandidateTypeSet::iterator
4975 Vec2 = CandidateTypes[1].vector_begin(),
4976 Vec2End = CandidateTypes[1].vector_end();
4977 Vec2 != Vec2End; ++Vec2) {
4978 QualType LandR[2] = { *Vec1, *Vec2 };
4979 QualType Result = S.Context.BoolTy;
4980 if (!isComparison) {
4981 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4982 Result = *Vec1;
4983 else
4984 Result = *Vec2;
4985 }
4986
4987 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4988 }
4989 }
4990 }
4991
4992 // C++ [over.built]p17:
4993 //
4994 // For every pair of promoted integral types L and R, there
4995 // exist candidate operator functions of the form
4996 //
4997 // LR operator%(L, R);
4998 // LR operator&(L, R);
4999 // LR operator^(L, R);
5000 // LR operator|(L, R);
5001 // L operator<<(L, R);
5002 // L operator>>(L, R);
5003 //
5004 // where LR is the result of the usual arithmetic conversions
5005 // between types L and R.
5006 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
5007 for (unsigned Left = FirstPromotedIntegralType;
5008 Left < LastPromotedIntegralType; ++Left) {
5009 for (unsigned Right = FirstPromotedIntegralType;
5010 Right < LastPromotedIntegralType; ++Right) {
5011 QualType LandR[2] = { S.Context.*ArithmeticTypes[Left],
5012 S.Context.*ArithmeticTypes[Right] };
5013 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5014 ? LandR[0]
5015 : UsualArithmeticConversionsType::find(S.Context, Left, Right);
5016 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5017 }
5018 }
5019 }
5020
5021 // C++ [over.built]p20:
5022 //
5023 // For every pair (T, VQ), where T is an enumeration or
5024 // pointer to member type and VQ is either volatile or
5025 // empty, there exist candidate operator functions of the form
5026 //
5027 // VQ T& operator=(VQ T&, T);
5028 void addAssignmentMemberPointerOrEnumeralOverloads() {
5029 /// Set of (canonical) types that we've already handled.
5030 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5031
5032 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5033 for (BuiltinCandidateTypeSet::iterator
5034 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5035 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5036 Enum != EnumEnd; ++Enum) {
5037 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5038 continue;
5039
5040 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5041 CandidateSet);
5042 }
5043
5044 for (BuiltinCandidateTypeSet::iterator
5045 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5046 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5047 MemPtr != MemPtrEnd; ++MemPtr) {
5048 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5049 continue;
5050
5051 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5052 CandidateSet);
5053 }
5054 }
5055 }
5056
5057 // C++ [over.built]p19:
5058 //
5059 // For every pair (T, VQ), where T is any type and VQ is either
5060 // volatile or empty, there exist candidate operator functions
5061 // of the form
5062 //
5063 // T*VQ& operator=(T*VQ&, T*);
5064 //
5065 // C++ [over.built]p21:
5066 //
5067 // For every pair (T, VQ), where T is a cv-qualified or
5068 // cv-unqualified object type and VQ is either volatile or
5069 // empty, there exist candidate operator functions of the form
5070 //
5071 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5072 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5073 void addAssignmentPointerOverloads(bool isEqualOp) {
5074 /// Set of (canonical) types that we've already handled.
5075 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5076
5077 for (BuiltinCandidateTypeSet::iterator
5078 Ptr = CandidateTypes[0].pointer_begin(),
5079 PtrEnd = CandidateTypes[0].pointer_end();
5080 Ptr != PtrEnd; ++Ptr) {
5081 // If this is operator=, keep track of the builtin candidates we added.
5082 if (isEqualOp)
5083 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
5084
5085 // non-volatile version
5086 QualType ParamTypes[2] = {
5087 S.Context.getLValueReferenceType(*Ptr),
5088 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5089 };
5090 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5091 /*IsAssigmentOperator=*/ isEqualOp);
5092
5093 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5094 VisibleTypeConversionsQuals.hasVolatile()) {
5095 // volatile version
5096 ParamTypes[0] =
5097 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5098 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5099 /*IsAssigmentOperator=*/isEqualOp);
5100 }
5101 }
5102
5103 if (isEqualOp) {
5104 for (BuiltinCandidateTypeSet::iterator
5105 Ptr = CandidateTypes[1].pointer_begin(),
5106 PtrEnd = CandidateTypes[1].pointer_end();
5107 Ptr != PtrEnd; ++Ptr) {
5108 // Make sure we don't add the same candidate twice.
5109 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5110 continue;
5111
5112 QualType ParamTypes[2] = { S.Context.getLValueReferenceType(*Ptr), *Ptr };
5113
5114 // non-volatile version
5115 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5116 /*IsAssigmentOperator=*/true);
5117
5118 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5119 VisibleTypeConversionsQuals.hasVolatile()) {
5120 // volatile version
5121 ParamTypes[0] =
5122 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5123 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5124 /*IsAssigmentOperator=*/true);
5125 }
5126 }
5127 }
5128 }
5129
5130 // C++ [over.built]p18:
5131 //
5132 // For every triple (L, VQ, R), where L is an arithmetic type,
5133 // VQ is either volatile or empty, and R is a promoted
5134 // arithmetic type, there exist candidate operator functions of
5135 // the form
5136 //
5137 // VQ L& operator=(VQ L&, R);
5138 // VQ L& operator*=(VQ L&, R);
5139 // VQ L& operator/=(VQ L&, R);
5140 // VQ L& operator+=(VQ L&, R);
5141 // VQ L& operator-=(VQ L&, R);
5142 void addAssignmentArithmeticOverloads(bool isEqualOp) {
5143 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5144 for (unsigned Right = FirstPromotedArithmeticType;
5145 Right < LastPromotedArithmeticType; ++Right) {
5146 QualType ParamTypes[2];
5147 ParamTypes[1] = S.Context.*ArithmeticTypes[Right];
5148
5149 // Add this built-in operator as a candidate (VQ is empty).
5150 ParamTypes[0] =
5151 S.Context.getLValueReferenceType(S.Context.*ArithmeticTypes[Left]);
5152 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5153 /*IsAssigmentOperator=*/isEqualOp);
5154
5155 // Add this built-in operator as a candidate (VQ is 'volatile').
5156 if (VisibleTypeConversionsQuals.hasVolatile()) {
5157 ParamTypes[0] =
5158 S.Context.getVolatileType(S.Context.*ArithmeticTypes[Left]);
5159 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5160 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5161 /*IsAssigmentOperator=*/isEqualOp);
5162 }
5163 }
5164 }
5165
5166 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5167 for (BuiltinCandidateTypeSet::iterator
5168 Vec1 = CandidateTypes[0].vector_begin(),
5169 Vec1End = CandidateTypes[0].vector_end();
5170 Vec1 != Vec1End; ++Vec1) {
5171 for (BuiltinCandidateTypeSet::iterator
5172 Vec2 = CandidateTypes[1].vector_begin(),
5173 Vec2End = CandidateTypes[1].vector_end();
5174 Vec2 != Vec2End; ++Vec2) {
5175 QualType ParamTypes[2];
5176 ParamTypes[1] = *Vec2;
5177 // Add this built-in operator as a candidate (VQ is empty).
5178 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5179 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5180 /*IsAssigmentOperator=*/isEqualOp);
5181
5182 // Add this built-in operator as a candidate (VQ is 'volatile').
5183 if (VisibleTypeConversionsQuals.hasVolatile()) {
5184 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5185 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5186 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5187 /*IsAssigmentOperator=*/isEqualOp);
5188 }
5189 }
5190 }
5191 }
5192
5193 // C++ [over.built]p22:
5194 //
5195 // For every triple (L, VQ, R), where L is an integral type, VQ
5196 // is either volatile or empty, and R is a promoted integral
5197 // type, there exist candidate operator functions of the form
5198 //
5199 // VQ L& operator%=(VQ L&, R);
5200 // VQ L& operator<<=(VQ L&, R);
5201 // VQ L& operator>>=(VQ L&, R);
5202 // VQ L& operator&=(VQ L&, R);
5203 // VQ L& operator^=(VQ L&, R);
5204 // VQ L& operator|=(VQ L&, R);
5205 void addAssignmentIntegralOverloads() {
5206 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5207 for (unsigned Right = FirstPromotedIntegralType;
5208 Right < LastPromotedIntegralType; ++Right) {
5209 QualType ParamTypes[2];
5210 ParamTypes[1] = S.Context.*ArithmeticTypes[Right];
5211
5212 // Add this built-in operator as a candidate (VQ is empty).
5213 ParamTypes[0] =
5214 S.Context.getLValueReferenceType(S.Context.*ArithmeticTypes[Left]);
5215 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5216 if (VisibleTypeConversionsQuals.hasVolatile()) {
5217 // Add this built-in operator as a candidate (VQ is 'volatile').
5218 ParamTypes[0] = S.Context.*ArithmeticTypes[Left];
5219 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5220 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5221 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5222 CandidateSet);
5223 }
5224 }
5225 }
5226 }
5227
5228 // C++ [over.operator]p23:
5229 //
5230 // There also exist candidate operator functions of the form
5231 //
5232 // bool operator!(bool);
5233 // bool operator&&(bool, bool);
5234 // bool operator||(bool, bool);
5235 void addExclaimOverload() {
5236 QualType ParamTy = S.Context.BoolTy;
5237 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5238 /*IsAssignmentOperator=*/false,
5239 /*NumContextualBoolArguments=*/1);
5240 }
5241 void addAmpAmpOrPipePipeOverload() {
5242 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5243 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5244 /*IsAssignmentOperator=*/false,
5245 /*NumContextualBoolArguments=*/2);
5246 }
5247
5248 // C++ [over.built]p13:
5249 //
5250 // For every cv-qualified or cv-unqualified object type T there
5251 // exist candidate operator functions of the form
5252 //
5253 // T* operator+(T*, ptrdiff_t); [ABOVE]
5254 // T& operator[](T*, ptrdiff_t);
5255 // T* operator-(T*, ptrdiff_t); [ABOVE]
5256 // T* operator+(ptrdiff_t, T*); [ABOVE]
5257 // T& operator[](ptrdiff_t, T*);
5258 void addSubscriptOverloads() {
5259 for (BuiltinCandidateTypeSet::iterator
5260 Ptr = CandidateTypes[0].pointer_begin(),
5261 PtrEnd = CandidateTypes[0].pointer_end();
5262 Ptr != PtrEnd; ++Ptr) {
5263 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5264 QualType PointeeType = (*Ptr)->getPointeeType();
5265 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5266
5267 // T& operator[](T*, ptrdiff_t)
5268 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5269 }
5270
5271 for (BuiltinCandidateTypeSet::iterator
5272 Ptr = CandidateTypes[1].pointer_begin(),
5273 PtrEnd = CandidateTypes[1].pointer_end();
5274 Ptr != PtrEnd; ++Ptr) {
5275 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5276 QualType PointeeType = (*Ptr)->getPointeeType();
5277 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5278
5279 // T& operator[](ptrdiff_t, T*)
5280 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5281 }
5282 }
5283
5284 // C++ [over.built]p11:
5285 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5286 // C1 is the same type as C2 or is a derived class of C2, T is an object
5287 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5288 // there exist candidate operator functions of the form
5289 //
5290 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5291 //
5292 // where CV12 is the union of CV1 and CV2.
5293 void addArrowStarOverloads() {
5294 for (BuiltinCandidateTypeSet::iterator
5295 Ptr = CandidateTypes[0].pointer_begin(),
5296 PtrEnd = CandidateTypes[0].pointer_end();
5297 Ptr != PtrEnd; ++Ptr) {
5298 QualType C1Ty = (*Ptr);
5299 QualType C1;
5300 QualifierCollector Q1;
5301 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5302 if (!isa<RecordType>(C1))
5303 continue;
5304 // heuristic to reduce number of builtin candidates in the set.
5305 // Add volatile/restrict version only if there are conversions to a
5306 // volatile/restrict type.
5307 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5308 continue;
5309 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5310 continue;
5311 for (BuiltinCandidateTypeSet::iterator
5312 MemPtr = CandidateTypes[1].member_pointer_begin(),
5313 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5314 MemPtr != MemPtrEnd; ++MemPtr) {
5315 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5316 QualType C2 = QualType(mptr->getClass(), 0);
5317 C2 = C2.getUnqualifiedType();
5318 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5319 break;
5320 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5321 // build CV12 T&
5322 QualType T = mptr->getPointeeType();
5323 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5324 T.isVolatileQualified())
5325 continue;
5326 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5327 T.isRestrictQualified())
5328 continue;
5329 T = Q1.apply(S.Context, T);
5330 QualType ResultTy = S.Context.getLValueReferenceType(T);
5331 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5332 }
5333 }
5334 }
5335
5336 // Note that we don't consider the first argument, since it has been
5337 // contextually converted to bool long ago. The candidates below are
5338 // therefore added as binary.
5339 //
5340 // C++ [over.built]p25:
5341 // For every type T, where T is a pointer, pointer-to-member, or scoped
5342 // enumeration type, there exist candidate operator functions of the form
5343 //
5344 // T operator?(bool, T, T);
5345 //
5346 void addConditionalOperatorOverloads() {
5347 /// Set of (canonical) types that we've already handled.
5348 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5349
5350 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5351 for (BuiltinCandidateTypeSet::iterator
5352 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5353 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5354 Ptr != PtrEnd; ++Ptr) {
5355 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5356 continue;
5357
5358 QualType ParamTypes[2] = { *Ptr, *Ptr };
5359 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5360 }
5361
5362 for (BuiltinCandidateTypeSet::iterator
5363 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5364 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5365 MemPtr != MemPtrEnd; ++MemPtr) {
5366 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5367 continue;
5368
5369 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5370 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5371 }
5372
5373 if (S.getLangOptions().CPlusPlus0x) {
5374 for (BuiltinCandidateTypeSet::iterator
5375 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5376 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5377 Enum != EnumEnd; ++Enum) {
5378 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5379 continue;
5380
5381 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5382 continue;
5383
5384 QualType ParamTypes[2] = { *Enum, *Enum };
5385 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5386 }
5387 }
5388 }
5389 }
5390};
5391
5392CanQualType ASTContext::* const
5393BuiltinOperatorOverloadBuilder::ArithmeticTypes[NumArithmeticTypes] = {
5394 // Start of promoted types.
5395 &ASTContext::FloatTy,
5396 &ASTContext::DoubleTy,
5397 &ASTContext::LongDoubleTy,
5398
5399 // Start of integral types.
5400 &ASTContext::IntTy,
5401 &ASTContext::LongTy,
5402 &ASTContext::LongLongTy,
5403 &ASTContext::UnsignedIntTy,
5404 &ASTContext::UnsignedLongTy,
5405 &ASTContext::UnsignedLongLongTy,
5406 // End of promoted types.
5407
5408 &ASTContext::BoolTy,
5409 &ASTContext::CharTy,
5410 &ASTContext::WCharTy,
5411 &ASTContext::Char16Ty,
5412 &ASTContext::Char32Ty,
5413 &ASTContext::SignedCharTy,
5414 &ASTContext::ShortTy,
5415 &ASTContext::UnsignedCharTy,
5416 &ASTContext::UnsignedShortTy
5417 // End of integral types.
5418 // FIXME: What about complex?
5419};
5420
5421// Accelerator table for performing the usual arithmetic conversions.
5422// The rules are basically:
5423// - if either is floating-point, use the wider floating-point
5424// - if same signedness, use the higher rank
5425// - if same size, use unsigned of the higher rank
5426// - use the larger type
5427// These rules, together with the axiom that higher ranks are
5428// never smaller, are sufficient to precompute all of these results
5429// *except* when dealing with signed types of higher rank.
5430// (we could precompute SLL x UI for all known platforms, but it's
5431// better not to make any assumptions).
5432BuiltinOperatorOverloadBuilder::PromT
5433BuiltinOperatorOverloadBuilder::UsualArithmeticConversionsTypes
5434[LastPromotedArithmeticType][LastPromotedArithmeticType] = {
5435 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5436 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5437 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5438 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5439 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5440 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5441 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5442 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5443 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
5444};
5445
5446} // end anonymous namespace
5447
5448/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5449/// operator overloads to the candidate set (C++ [over.built]), based
5450/// on the operator @p Op and the arguments given. For example, if the
5451/// operator is a binary '+', this routine might add "int
5452/// operator+(int, int)" to cover integer addition.
5453void
5454Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5455 SourceLocation OpLoc,
5456 Expr **Args, unsigned NumArgs,
5457 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005458 // Find all of the types that the arguments can convert to, but only
5459 // if the operator we're looking at has built-in operator candidates
5460 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005461 Qualifiers VisibleTypeConversionsQuals;
5462 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005463 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5464 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
5465
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005466 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5467 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5468 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5469 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5470 OpLoc,
5471 true,
5472 (Op == OO_Exclaim ||
5473 Op == OO_AmpAmp ||
5474 Op == OO_PipePipe),
5475 VisibleTypeConversionsQuals);
5476 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005477
Douglas Gregor2bbc0262010-09-12 04:28:07 +00005478 // C++ [over.built]p1:
5479 // If there is a user-written candidate with the same name and parameter
5480 // types as a built-in candidate operator function, the built-in operator
5481 // function is hidden and is not included in the set of candidate functions.
5482 //
5483 // The text is actually in a note, but if we don't implement it then we end
5484 // up with ambiguities when the user provides an overloaded operator for
5485 // an enumeration type. Note that only enumeration types have this problem,
5486 // so we track which enumeration types we've seen operators for.
5487 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5488 UserDefinedBinaryOperators;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005489
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005490 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5491 if (CandidateTypes[ArgIdx].enumeration_begin()
5492 != CandidateTypes[ArgIdx].enumeration_end()) {
5493 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5494 CEnd = CandidateSet.end();
5495 C != CEnd; ++C) {
5496 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5497 continue;
5498
5499 // Check if the first parameter is of enumeration type.
5500 QualType FirstParamType
5501 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5502 if (!FirstParamType->isEnumeralType())
5503 continue;
5504
5505 // Check if the second parameter is of enumeration type.
5506 QualType SecondParamType
5507 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5508 if (!SecondParamType->isEnumeralType())
5509 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00005510
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005511 // Add this operator to the set of known user-defined operators.
5512 UserDefinedBinaryOperators.insert(
5513 std::make_pair(Context.getCanonicalType(FirstParamType),
5514 Context.getCanonicalType(SecondParamType)));
5515 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00005516 }
5517 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005518
5519 // Setup an object to manage the common state for building overloads.
5520 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5521 VisibleTypeConversionsQuals,
5522 CandidateTypes, CandidateSet);
5523
5524 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005525 bool isComparison = false;
5526 switch (Op) {
5527 case OO_None:
5528 case NUM_OVERLOADED_OPERATORS:
5529 assert(false && "Expected an overloaded operator");
5530 break;
5531
Douglas Gregord08452f2008-11-19 15:42:04 +00005532 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00005533 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005534 OpBuilder.addUnaryStarPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005535 else
5536 goto BinaryStar;
5537 break;
5538
5539 case OO_Plus: // '+' is either unary or binary
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005540 if (NumArgs == 1) {
5541 OpBuilder.addUnaryPlusPointerOverloads();
5542 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
5543 } else {
Douglas Gregord08452f2008-11-19 15:42:04 +00005544 goto BinaryPlus;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005545 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005546 break;
5547
5548 case OO_Minus: // '-' is either unary or binary
5549 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005550 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005551 else
5552 goto BinaryMinus;
5553 break;
5554
5555 case OO_Amp: // '&' is either unary or binary
5556 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005557 // C++ [over.match.oper]p3:
5558 // -- For the operator ',', the unary operator '&', or the
5559 // operator '->', the built-in candidates set is empty.
5560 break;
5561
5562 goto BinaryAmp;
Douglas Gregord08452f2008-11-19 15:42:04 +00005563
5564 case OO_PlusPlus:
5565 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005566 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5567 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005568 break;
5569
5570 case OO_Tilde:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005571 OpBuilder.addUnaryTildePromotedIntegralOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005572 break;
5573
Douglas Gregora11693b2008-11-12 17:17:38 +00005574 case OO_New:
5575 case OO_Delete:
5576 case OO_Array_New:
5577 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00005578 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00005579 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00005580 break;
5581
5582 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00005583 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00005584 // C++ [over.match.oper]p3:
5585 // -- For the operator ',', the unary operator '&', or the
5586 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00005587 break;
5588
Douglas Gregor84605ae2009-08-24 13:43:27 +00005589 case OO_EqualEqual:
5590 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005591 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
5592
Douglas Gregor84605ae2009-08-24 13:43:27 +00005593 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00005594
Douglas Gregora11693b2008-11-12 17:17:38 +00005595 case OO_Less:
5596 case OO_Greater:
5597 case OO_LessEqual:
5598 case OO_GreaterEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005599 OpBuilder.addRelationalPointerOrEnumeralOverloads(
5600 UserDefinedBinaryOperators);
5601
Douglas Gregora11693b2008-11-12 17:17:38 +00005602 // Fall through.
5603 isComparison = true;
5604
Douglas Gregord08452f2008-11-19 15:42:04 +00005605 BinaryPlus:
5606 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00005607 if (!isComparison) {
5608 // We didn't fall through, so we must have OO_Plus or OO_Minus.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005609 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005610 }
5611 // Fall through
5612
Douglas Gregora11693b2008-11-12 17:17:38 +00005613 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00005614 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00005615 Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005616 OpBuilder.addGenericBinaryArithmeticOverloads(isComparison);
Douglas Gregora11693b2008-11-12 17:17:38 +00005617 break;
5618
5619 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005620 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005621 case OO_Caret:
5622 case OO_Pipe:
5623 case OO_LessLess:
5624 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005625 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005626 break;
5627
5628 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005629 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005630 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005631
5632 case OO_PlusEqual:
5633 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005634 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005635 // Fall through.
5636
5637 case OO_StarEqual:
5638 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005639 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005640 break;
5641
5642 case OO_PercentEqual:
5643 case OO_LessLessEqual:
5644 case OO_GreaterGreaterEqual:
5645 case OO_AmpEqual:
5646 case OO_CaretEqual:
5647 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005648 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005649 break;
5650
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005651 case OO_Exclaim:
5652 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005653 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005654
Douglas Gregora11693b2008-11-12 17:17:38 +00005655 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005656 case OO_PipePipe:
5657 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005658 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005659
5660 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005661 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005662 break;
5663
5664 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005665 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005666 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005667
5668 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005669 OpBuilder.addConditionalOperatorOverloads();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005670 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005671 }
5672}
5673
Douglas Gregore254f902009-02-04 00:32:51 +00005674/// \brief Add function candidates found via argument-dependent lookup
5675/// to the set of overloading candidates.
5676///
5677/// This routine performs argument-dependent name lookup based on the
5678/// given function name (which may also be an operator name) and adds
5679/// all of the overload candidates found by ADL to the overload
5680/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005681void
Douglas Gregore254f902009-02-04 00:32:51 +00005682Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005683 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005684 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005685 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005686 OverloadCandidateSet& CandidateSet,
5687 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005688 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005689
John McCall91f61fc2010-01-26 06:04:06 +00005690 // FIXME: This approach for uniquing ADL results (and removing
5691 // redundant candidates from the set) relies on pointer-equality,
5692 // which means we need to key off the canonical decl. However,
5693 // always going back to the canonical decl might not get us the
5694 // right set of default arguments. What default arguments are
5695 // we supposed to consider on ADL candidates, anyway?
5696
Douglas Gregorcabea402009-09-22 15:41:20 +00005697 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005698 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005699
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005700 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005701 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5702 CandEnd = CandidateSet.end();
5703 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005704 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005705 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005706 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005707 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005708 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005709
5710 // For each of the ADL candidates we found, add it to the overload
5711 // set.
John McCall8fe68082010-01-26 07:16:45 +00005712 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005713 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005714 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005715 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005716 continue;
5717
John McCalla0296f72010-03-19 07:35:19 +00005718 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005719 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005720 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005721 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005722 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005723 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005724 }
Douglas Gregore254f902009-02-04 00:32:51 +00005725}
5726
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005727/// isBetterOverloadCandidate - Determines whether the first overload
5728/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005729bool
John McCall5c32be02010-08-24 20:38:10 +00005730isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005731 const OverloadCandidate &Cand1,
5732 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005733 SourceLocation Loc,
5734 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005735 // Define viable functions to be better candidates than non-viable
5736 // functions.
5737 if (!Cand2.Viable)
5738 return Cand1.Viable;
5739 else if (!Cand1.Viable)
5740 return false;
5741
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005742 // C++ [over.match.best]p1:
5743 //
5744 // -- if F is a static member function, ICS1(F) is defined such
5745 // that ICS1(F) is neither better nor worse than ICS1(G) for
5746 // any function G, and, symmetrically, ICS1(G) is neither
5747 // better nor worse than ICS1(F).
5748 unsigned StartArg = 0;
5749 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5750 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005751
Douglas Gregord3cb3562009-07-07 23:38:56 +00005752 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005753 // A viable function F1 is defined to be a better function than another
5754 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005755 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005756 unsigned NumArgs = Cand1.Conversions.size();
5757 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5758 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005759 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005760 switch (CompareImplicitConversionSequences(S,
5761 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005762 Cand2.Conversions[ArgIdx])) {
5763 case ImplicitConversionSequence::Better:
5764 // Cand1 has a better conversion sequence.
5765 HasBetterConversion = true;
5766 break;
5767
5768 case ImplicitConversionSequence::Worse:
5769 // Cand1 can't be better than Cand2.
5770 return false;
5771
5772 case ImplicitConversionSequence::Indistinguishable:
5773 // Do nothing.
5774 break;
5775 }
5776 }
5777
Mike Stump11289f42009-09-09 15:08:12 +00005778 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005779 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005780 if (HasBetterConversion)
5781 return true;
5782
Mike Stump11289f42009-09-09 15:08:12 +00005783 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005784 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005785 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005786 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5787 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005788
5789 // -- F1 and F2 are function template specializations, and the function
5790 // template for F1 is more specialized than the template for F2
5791 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005792 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005793 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5794 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005795 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005796 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5797 Cand2.Function->getPrimaryTemplate(),
5798 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005799 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5800 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005801 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005802
Douglas Gregora1f013e2008-11-07 22:36:19 +00005803 // -- the context is an initialization by user-defined conversion
5804 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5805 // from the return type of F1 to the destination type (i.e.,
5806 // the type of the entity being initialized) is a better
5807 // conversion sequence than the standard conversion sequence
5808 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005809 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005810 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005811 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005812 switch (CompareStandardConversionSequences(S,
5813 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005814 Cand2.FinalConversion)) {
5815 case ImplicitConversionSequence::Better:
5816 // Cand1 has a better conversion sequence.
5817 return true;
5818
5819 case ImplicitConversionSequence::Worse:
5820 // Cand1 can't be better than Cand2.
5821 return false;
5822
5823 case ImplicitConversionSequence::Indistinguishable:
5824 // Do nothing
5825 break;
5826 }
5827 }
5828
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005829 return false;
5830}
5831
Mike Stump11289f42009-09-09 15:08:12 +00005832/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005833/// within an overload candidate set.
5834///
5835/// \param CandidateSet the set of candidate functions.
5836///
5837/// \param Loc the location of the function name (or operator symbol) for
5838/// which overload resolution occurs.
5839///
Mike Stump11289f42009-09-09 15:08:12 +00005840/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005841/// function, Best points to the candidate function found.
5842///
5843/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005844OverloadingResult
5845OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005846 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005847 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005848 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005849 Best = end();
5850 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5851 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005852 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5853 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005854 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005855 }
5856
5857 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005858 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005859 return OR_No_Viable_Function;
5860
5861 // Make sure that this function is better than every other viable
5862 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005863 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005864 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005865 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005866 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5867 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005868 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005869 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005870 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005871 }
Mike Stump11289f42009-09-09 15:08:12 +00005872
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005873 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005874 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005875 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005876 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005877 return OR_Deleted;
5878
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005879 // C++ [basic.def.odr]p2:
5880 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005881 // when referred to from a potentially-evaluated expression. [Note: this
5882 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005883 // (clause 13), user-defined conversions (12.3.2), allocation function for
5884 // placement new (5.3.4), as well as non-default initialization (8.5).
5885 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005886 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005887
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005888 return OR_Success;
5889}
5890
John McCall53262c92010-01-12 02:15:36 +00005891namespace {
5892
5893enum OverloadCandidateKind {
5894 oc_function,
5895 oc_method,
5896 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005897 oc_function_template,
5898 oc_method_template,
5899 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005900 oc_implicit_default_constructor,
5901 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005902 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005903};
5904
John McCalle1ac8d12010-01-13 00:25:19 +00005905OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5906 FunctionDecl *Fn,
5907 std::string &Description) {
5908 bool isTemplate = false;
5909
5910 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5911 isTemplate = true;
5912 Description = S.getTemplateArgumentBindingsText(
5913 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5914 }
John McCallfd0b2f82010-01-06 09:43:14 +00005915
5916 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005917 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005918 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005919
John McCall53262c92010-01-12 02:15:36 +00005920 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5921 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005922 }
5923
5924 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5925 // This actually gets spelled 'candidate function' for now, but
5926 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005927 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005928 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005929
Douglas Gregorec3bec02010-09-27 22:37:28 +00005930 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005931 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005932 return oc_implicit_copy_assignment;
5933 }
5934
John McCalle1ac8d12010-01-13 00:25:19 +00005935 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005936}
5937
5938} // end anonymous namespace
5939
5940// Notes the location of an overload candidate.
5941void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005942 std::string FnDesc;
5943 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5944 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5945 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005946}
5947
John McCall0d1da222010-01-12 00:44:57 +00005948/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5949/// "lead" diagnostic; it will be given two arguments, the source and
5950/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005951void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5952 Sema &S,
5953 SourceLocation CaretLoc,
5954 const PartialDiagnostic &PDiag) const {
5955 S.Diag(CaretLoc, PDiag)
5956 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005957 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005958 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5959 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005960 }
John McCall12f97bc2010-01-08 04:41:39 +00005961}
5962
John McCall0d1da222010-01-12 00:44:57 +00005963namespace {
5964
John McCall6a61b522010-01-13 09:16:55 +00005965void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5966 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5967 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005968 assert(Cand->Function && "for now, candidate must be a function");
5969 FunctionDecl *Fn = Cand->Function;
5970
5971 // There's a conversion slot for the object argument if this is a
5972 // non-constructor method. Note that 'I' corresponds the
5973 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005974 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005975 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005976 if (I == 0)
5977 isObjectArgument = true;
5978 else
5979 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005980 }
5981
John McCalle1ac8d12010-01-13 00:25:19 +00005982 std::string FnDesc;
5983 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5984
John McCall6a61b522010-01-13 09:16:55 +00005985 Expr *FromExpr = Conv.Bad.FromExpr;
5986 QualType FromTy = Conv.Bad.getFromType();
5987 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005988
John McCallfb7ad0f2010-02-02 02:42:52 +00005989 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005990 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005991 Expr *E = FromExpr->IgnoreParens();
5992 if (isa<UnaryOperator>(E))
5993 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005994 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005995
5996 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5997 << (unsigned) FnKind << FnDesc
5998 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5999 << ToTy << Name << I+1;
6000 return;
6001 }
6002
John McCall6d174642010-01-23 08:10:49 +00006003 // Do some hand-waving analysis to see if the non-viability is due
6004 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006005 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6006 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6007 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6008 CToTy = RT->getPointeeType();
6009 else {
6010 // TODO: detect and diagnose the full richness of const mismatches.
6011 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6012 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6013 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6014 }
6015
6016 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6017 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6018 // It is dumb that we have to do this here.
6019 while (isa<ArrayType>(CFromTy))
6020 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6021 while (isa<ArrayType>(CToTy))
6022 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6023
6024 Qualifiers FromQs = CFromTy.getQualifiers();
6025 Qualifiers ToQs = CToTy.getQualifiers();
6026
6027 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6028 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6029 << (unsigned) FnKind << FnDesc
6030 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6031 << FromTy
6032 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6033 << (unsigned) isObjectArgument << I+1;
6034 return;
6035 }
6036
6037 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6038 assert(CVR && "unexpected qualifiers mismatch");
6039
6040 if (isObjectArgument) {
6041 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6042 << (unsigned) FnKind << FnDesc
6043 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6044 << FromTy << (CVR - 1);
6045 } else {
6046 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6047 << (unsigned) FnKind << FnDesc
6048 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6049 << FromTy << (CVR - 1) << I+1;
6050 }
6051 return;
6052 }
6053
John McCall6d174642010-01-23 08:10:49 +00006054 // Diagnose references or pointers to incomplete types differently,
6055 // since it's far from impossible that the incompleteness triggered
6056 // the failure.
6057 QualType TempFromTy = FromTy.getNonReferenceType();
6058 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6059 TempFromTy = PTy->getPointeeType();
6060 if (TempFromTy->isIncompleteType()) {
6061 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6062 << (unsigned) FnKind << FnDesc
6063 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6064 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6065 return;
6066 }
6067
Douglas Gregor56f2e342010-06-30 23:01:39 +00006068 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006069 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006070 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6071 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6072 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6073 FromPtrTy->getPointeeType()) &&
6074 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6075 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6076 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6077 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006078 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006079 }
6080 } else if (const ObjCObjectPointerType *FromPtrTy
6081 = FromTy->getAs<ObjCObjectPointerType>()) {
6082 if (const ObjCObjectPointerType *ToPtrTy
6083 = ToTy->getAs<ObjCObjectPointerType>())
6084 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6085 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6086 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6087 FromPtrTy->getPointeeType()) &&
6088 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006089 BaseToDerivedConversion = 2;
6090 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6091 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6092 !FromTy->isIncompleteType() &&
6093 !ToRefTy->getPointeeType()->isIncompleteType() &&
6094 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6095 BaseToDerivedConversion = 3;
6096 }
6097
6098 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00006099 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006100 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006101 << (unsigned) FnKind << FnDesc
6102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006103 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006104 << FromTy << ToTy << I+1;
6105 return;
6106 }
6107
John McCall47000992010-01-14 03:28:57 +00006108 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6110 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006111 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006112 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006113}
6114
6115void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6116 unsigned NumFormalArgs) {
6117 // TODO: treat calls to a missing default constructor as a special case
6118
6119 FunctionDecl *Fn = Cand->Function;
6120 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6121
6122 unsigned MinParams = Fn->getMinRequiredArguments();
6123
6124 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00006125 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00006126 unsigned mode, modeCount;
6127 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006128 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6129 (Cand->FailureKind == ovl_fail_bad_deduction &&
6130 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00006131 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6132 mode = 0; // "at least"
6133 else
6134 mode = 2; // "exactly"
6135 modeCount = MinParams;
6136 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006137 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6138 (Cand->FailureKind == ovl_fail_bad_deduction &&
6139 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006140 if (MinParams != FnTy->getNumArgs())
6141 mode = 1; // "at most"
6142 else
6143 mode = 2; // "exactly"
6144 modeCount = FnTy->getNumArgs();
6145 }
6146
6147 std::string Description;
6148 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6149
6150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006151 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6152 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006153}
6154
John McCall8b9ed552010-02-01 18:53:26 +00006155/// Diagnose a failed template-argument deduction.
6156void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6157 Expr **Args, unsigned NumArgs) {
6158 FunctionDecl *Fn = Cand->Function; // pattern
6159
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006160 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006161 NamedDecl *ParamD;
6162 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6163 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6164 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006165 switch (Cand->DeductionFailure.Result) {
6166 case Sema::TDK_Success:
6167 llvm_unreachable("TDK_success while diagnosing bad deduction");
6168
6169 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006170 assert(ParamD && "no parameter found for incomplete deduction result");
6171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6172 << ParamD->getDeclName();
6173 return;
6174 }
6175
John McCall42d7d192010-08-05 09:05:08 +00006176 case Sema::TDK_Underqualified: {
6177 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6178 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6179
6180 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6181
6182 // Param will have been canonicalized, but it should just be a
6183 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006184 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006185 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006186 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006187 assert(S.Context.hasSameType(Param, NonCanonParam));
6188
6189 // Arg has also been canonicalized, but there's nothing we can do
6190 // about that. It also doesn't matter as much, because it won't
6191 // have any template parameters in it (because deduction isn't
6192 // done on dependent types).
6193 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6194
6195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6196 << ParamD->getDeclName() << Arg << NonCanonParam;
6197 return;
6198 }
6199
6200 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006201 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006202 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006203 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006204 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006205 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006206 which = 1;
6207 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006208 which = 2;
6209 }
6210
6211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6212 << which << ParamD->getDeclName()
6213 << *Cand->DeductionFailure.getFirstArg()
6214 << *Cand->DeductionFailure.getSecondArg();
6215 return;
6216 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006217
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006218 case Sema::TDK_InvalidExplicitArguments:
6219 assert(ParamD && "no parameter found for invalid explicit arguments");
6220 if (ParamD->getDeclName())
6221 S.Diag(Fn->getLocation(),
6222 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6223 << ParamD->getDeclName();
6224 else {
6225 int index = 0;
6226 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6227 index = TTP->getIndex();
6228 else if (NonTypeTemplateParmDecl *NTTP
6229 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6230 index = NTTP->getIndex();
6231 else
6232 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6233 S.Diag(Fn->getLocation(),
6234 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6235 << (index + 1);
6236 }
6237 return;
6238
Douglas Gregor02eb4832010-05-08 18:13:28 +00006239 case Sema::TDK_TooManyArguments:
6240 case Sema::TDK_TooFewArguments:
6241 DiagnoseArityMismatch(S, Cand, NumArgs);
6242 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006243
6244 case Sema::TDK_InstantiationDepth:
6245 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6246 return;
6247
6248 case Sema::TDK_SubstitutionFailure: {
6249 std::string ArgString;
6250 if (TemplateArgumentList *Args
6251 = Cand->DeductionFailure.getTemplateArgumentList())
6252 ArgString = S.getTemplateArgumentBindingsText(
6253 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6254 *Args);
6255 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6256 << ArgString;
6257 return;
6258 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006259
John McCall8b9ed552010-02-01 18:53:26 +00006260 // TODO: diagnose these individually, then kill off
6261 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006262 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006263 case Sema::TDK_FailedOverloadResolution:
6264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6265 return;
6266 }
6267}
6268
6269/// Generates a 'note' diagnostic for an overload candidate. We've
6270/// already generated a primary error at the call site.
6271///
6272/// It really does need to be a single diagnostic with its caret
6273/// pointed at the candidate declaration. Yes, this creates some
6274/// major challenges of technical writing. Yes, this makes pointing
6275/// out problems with specific arguments quite awkward. It's still
6276/// better than generating twenty screens of text for every failed
6277/// overload.
6278///
6279/// It would be great to be able to express per-candidate problems
6280/// more richly for those diagnostic clients that cared, but we'd
6281/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006282void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6283 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006284 FunctionDecl *Fn = Cand->Function;
6285
John McCall12f97bc2010-01-08 04:41:39 +00006286 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006287 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006288 std::string FnDesc;
6289 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006290
6291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006292 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006293 return;
John McCall12f97bc2010-01-08 04:41:39 +00006294 }
6295
John McCalle1ac8d12010-01-13 00:25:19 +00006296 // We don't really have anything else to say about viable candidates.
6297 if (Cand->Viable) {
6298 S.NoteOverloadCandidate(Fn);
6299 return;
6300 }
John McCall0d1da222010-01-12 00:44:57 +00006301
John McCall6a61b522010-01-13 09:16:55 +00006302 switch (Cand->FailureKind) {
6303 case ovl_fail_too_many_arguments:
6304 case ovl_fail_too_few_arguments:
6305 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006306
John McCall6a61b522010-01-13 09:16:55 +00006307 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006308 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6309
John McCallfe796dd2010-01-23 05:17:32 +00006310 case ovl_fail_trivial_conversion:
6311 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006312 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006313 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006314
John McCall65eb8792010-02-25 01:37:24 +00006315 case ovl_fail_bad_conversion: {
6316 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6317 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006318 if (Cand->Conversions[I].isBad())
6319 return DiagnoseBadConversion(S, Cand, I);
6320
6321 // FIXME: this currently happens when we're called from SemaInit
6322 // when user-conversion overload fails. Figure out how to handle
6323 // those conditions and diagnose them well.
6324 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006325 }
John McCall65eb8792010-02-25 01:37:24 +00006326 }
John McCalld3224162010-01-08 00:58:21 +00006327}
6328
6329void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6330 // Desugar the type of the surrogate down to a function type,
6331 // retaining as many typedefs as possible while still showing
6332 // the function type (and, therefore, its parameter types).
6333 QualType FnType = Cand->Surrogate->getConversionType();
6334 bool isLValueReference = false;
6335 bool isRValueReference = false;
6336 bool isPointer = false;
6337 if (const LValueReferenceType *FnTypeRef =
6338 FnType->getAs<LValueReferenceType>()) {
6339 FnType = FnTypeRef->getPointeeType();
6340 isLValueReference = true;
6341 } else if (const RValueReferenceType *FnTypeRef =
6342 FnType->getAs<RValueReferenceType>()) {
6343 FnType = FnTypeRef->getPointeeType();
6344 isRValueReference = true;
6345 }
6346 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6347 FnType = FnTypePtr->getPointeeType();
6348 isPointer = true;
6349 }
6350 // Desugar down to a function type.
6351 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6352 // Reconstruct the pointer/reference as appropriate.
6353 if (isPointer) FnType = S.Context.getPointerType(FnType);
6354 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6355 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6356
6357 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6358 << FnType;
6359}
6360
6361void NoteBuiltinOperatorCandidate(Sema &S,
6362 const char *Opc,
6363 SourceLocation OpLoc,
6364 OverloadCandidate *Cand) {
6365 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6366 std::string TypeStr("operator");
6367 TypeStr += Opc;
6368 TypeStr += "(";
6369 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6370 if (Cand->Conversions.size() == 1) {
6371 TypeStr += ")";
6372 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6373 } else {
6374 TypeStr += ", ";
6375 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6376 TypeStr += ")";
6377 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6378 }
6379}
6380
6381void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6382 OverloadCandidate *Cand) {
6383 unsigned NoOperands = Cand->Conversions.size();
6384 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6385 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006386 if (ICS.isBad()) break; // all meaningless after first invalid
6387 if (!ICS.isAmbiguous()) continue;
6388
John McCall5c32be02010-08-24 20:38:10 +00006389 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006390 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006391 }
6392}
6393
John McCall3712d9e2010-01-15 23:32:50 +00006394SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6395 if (Cand->Function)
6396 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006397 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006398 return Cand->Surrogate->getLocation();
6399 return SourceLocation();
6400}
6401
John McCallad2587a2010-01-12 00:48:53 +00006402struct CompareOverloadCandidatesForDisplay {
6403 Sema &S;
6404 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006405
6406 bool operator()(const OverloadCandidate *L,
6407 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006408 // Fast-path this check.
6409 if (L == R) return false;
6410
John McCall12f97bc2010-01-08 04:41:39 +00006411 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006412 if (L->Viable) {
6413 if (!R->Viable) return true;
6414
6415 // TODO: introduce a tri-valued comparison for overload
6416 // candidates. Would be more worthwhile if we had a sort
6417 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006418 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6419 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006420 } else if (R->Viable)
6421 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006422
John McCall3712d9e2010-01-15 23:32:50 +00006423 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006424
John McCall3712d9e2010-01-15 23:32:50 +00006425 // Criteria by which we can sort non-viable candidates:
6426 if (!L->Viable) {
6427 // 1. Arity mismatches come after other candidates.
6428 if (L->FailureKind == ovl_fail_too_many_arguments ||
6429 L->FailureKind == ovl_fail_too_few_arguments)
6430 return false;
6431 if (R->FailureKind == ovl_fail_too_many_arguments ||
6432 R->FailureKind == ovl_fail_too_few_arguments)
6433 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006434
John McCallfe796dd2010-01-23 05:17:32 +00006435 // 2. Bad conversions come first and are ordered by the number
6436 // of bad conversions and quality of good conversions.
6437 if (L->FailureKind == ovl_fail_bad_conversion) {
6438 if (R->FailureKind != ovl_fail_bad_conversion)
6439 return true;
6440
6441 // If there's any ordering between the defined conversions...
6442 // FIXME: this might not be transitive.
6443 assert(L->Conversions.size() == R->Conversions.size());
6444
6445 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006446 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6447 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006448 switch (CompareImplicitConversionSequences(S,
6449 L->Conversions[I],
6450 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006451 case ImplicitConversionSequence::Better:
6452 leftBetter++;
6453 break;
6454
6455 case ImplicitConversionSequence::Worse:
6456 leftBetter--;
6457 break;
6458
6459 case ImplicitConversionSequence::Indistinguishable:
6460 break;
6461 }
6462 }
6463 if (leftBetter > 0) return true;
6464 if (leftBetter < 0) return false;
6465
6466 } else if (R->FailureKind == ovl_fail_bad_conversion)
6467 return false;
6468
John McCall3712d9e2010-01-15 23:32:50 +00006469 // TODO: others?
6470 }
6471
6472 // Sort everything else by location.
6473 SourceLocation LLoc = GetLocationForCandidate(L);
6474 SourceLocation RLoc = GetLocationForCandidate(R);
6475
6476 // Put candidates without locations (e.g. builtins) at the end.
6477 if (LLoc.isInvalid()) return false;
6478 if (RLoc.isInvalid()) return true;
6479
6480 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006481 }
6482};
6483
John McCallfe796dd2010-01-23 05:17:32 +00006484/// CompleteNonViableCandidate - Normally, overload resolution only
6485/// computes up to the first
6486void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6487 Expr **Args, unsigned NumArgs) {
6488 assert(!Cand->Viable);
6489
6490 // Don't do anything on failures other than bad conversion.
6491 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6492
6493 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006494 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006495 unsigned ConvCount = Cand->Conversions.size();
6496 while (true) {
6497 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6498 ConvIdx++;
6499 if (Cand->Conversions[ConvIdx - 1].isBad())
6500 break;
6501 }
6502
6503 if (ConvIdx == ConvCount)
6504 return;
6505
John McCall65eb8792010-02-25 01:37:24 +00006506 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6507 "remaining conversion is initialized?");
6508
Douglas Gregoradc7a702010-04-16 17:45:54 +00006509 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006510 // operation somehow.
6511 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006512
6513 const FunctionProtoType* Proto;
6514 unsigned ArgIdx = ConvIdx;
6515
6516 if (Cand->IsSurrogate) {
6517 QualType ConvType
6518 = Cand->Surrogate->getConversionType().getNonReferenceType();
6519 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6520 ConvType = ConvPtrType->getPointeeType();
6521 Proto = ConvType->getAs<FunctionProtoType>();
6522 ArgIdx--;
6523 } else if (Cand->Function) {
6524 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6525 if (isa<CXXMethodDecl>(Cand->Function) &&
6526 !isa<CXXConstructorDecl>(Cand->Function))
6527 ArgIdx--;
6528 } else {
6529 // Builtin binary operator with a bad first conversion.
6530 assert(ConvCount <= 3);
6531 for (; ConvIdx != ConvCount; ++ConvIdx)
6532 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006533 = TryCopyInitialization(S, Args[ConvIdx],
6534 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6535 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006536 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006537 return;
6538 }
6539
6540 // Fill in the rest of the conversions.
6541 unsigned NumArgsInProto = Proto->getNumArgs();
6542 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6543 if (ArgIdx < NumArgsInProto)
6544 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006545 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6546 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006547 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006548 else
6549 Cand->Conversions[ConvIdx].setEllipsis();
6550 }
6551}
6552
John McCalld3224162010-01-08 00:58:21 +00006553} // end anonymous namespace
6554
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006555/// PrintOverloadCandidates - When overload resolution fails, prints
6556/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006557/// set.
John McCall5c32be02010-08-24 20:38:10 +00006558void OverloadCandidateSet::NoteCandidates(Sema &S,
6559 OverloadCandidateDisplayKind OCD,
6560 Expr **Args, unsigned NumArgs,
6561 const char *Opc,
6562 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006563 // Sort the candidates by viability and position. Sorting directly would
6564 // be prohibitive, so we make a set of pointers and sort those.
6565 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006566 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6567 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006568 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006569 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006570 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006571 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006572 if (Cand->Function || Cand->IsSurrogate)
6573 Cands.push_back(Cand);
6574 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6575 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006576 }
6577 }
6578
John McCallad2587a2010-01-12 00:48:53 +00006579 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006580 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006581
John McCall0d1da222010-01-12 00:44:57 +00006582 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006583
John McCall12f97bc2010-01-08 04:41:39 +00006584 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006585 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006586 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006587 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6588 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006589
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006590 // Set an arbitrary limit on the number of candidate functions we'll spam
6591 // the user with. FIXME: This limit should depend on details of the
6592 // candidate list.
6593 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6594 break;
6595 }
6596 ++CandsShown;
6597
John McCalld3224162010-01-08 00:58:21 +00006598 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006599 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006600 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006601 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006602 else {
6603 assert(Cand->Viable &&
6604 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006605 // Generally we only see ambiguities including viable builtin
6606 // operators if overload resolution got screwed up by an
6607 // ambiguous user-defined conversion.
6608 //
6609 // FIXME: It's quite possible for different conversions to see
6610 // different ambiguities, though.
6611 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006612 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006613 ReportedAmbiguousConversions = true;
6614 }
John McCalld3224162010-01-08 00:58:21 +00006615
John McCall0d1da222010-01-12 00:44:57 +00006616 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006617 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006618 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006619 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006620
6621 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006622 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006623}
6624
John McCalla0296f72010-03-19 07:35:19 +00006625static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006626 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006627 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006628
John McCalla0296f72010-03-19 07:35:19 +00006629 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006630}
6631
Douglas Gregorcd695e52008-11-10 20:40:00 +00006632/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6633/// an overloaded function (C++ [over.over]), where @p From is an
6634/// expression with overloaded function type and @p ToType is the type
6635/// we're trying to resolve to. For example:
6636///
6637/// @code
6638/// int f(double);
6639/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006640///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006641/// int (*pfd)(double) = f; // selects f(double)
6642/// @endcode
6643///
6644/// This routine returns the resulting FunctionDecl if it could be
6645/// resolved, and NULL otherwise. When @p Complain is true, this
6646/// routine will emit diagnostics if there is an error.
6647FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006648Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006649 bool Complain,
6650 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006651 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006652 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006653 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006654 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006655 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006656 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006657 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006658 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006659 FunctionType = MemTypePtr->getPointeeType();
6660 IsMember = true;
6661 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006662
Douglas Gregorcd695e52008-11-10 20:40:00 +00006663 // C++ [over.over]p1:
6664 // [...] [Note: any redundant set of parentheses surrounding the
6665 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006666 // C++ [over.over]p1:
6667 // [...] The overloaded function name can be preceded by the &
6668 // operator.
John McCall7d460512010-08-24 23:26:21 +00006669 // However, remember whether the expression has member-pointer form:
6670 // C++ [expr.unary.op]p4:
6671 // A pointer to member is only formed when an explicit & is used
6672 // and its operand is a qualified-id not enclosed in
6673 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006674 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6675 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006676
Douglas Gregor064fdb22010-04-14 23:11:21 +00006677 // We expect a pointer or reference to function, or a function pointer.
6678 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6679 if (!FunctionType->isFunctionType()) {
6680 if (Complain)
6681 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6682 << OvlExpr->getName() << ToType;
6683
6684 return 0;
6685 }
6686
John McCall24d18942010-08-24 22:52:39 +00006687 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006688 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006689 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006690 if (!Complain) return 0;
6691
6692 // TODO: Should we condition this on whether any functions might
6693 // have matched, or is it more appropriate to do that in callers?
6694 // TODO: a fixit wouldn't hurt.
6695 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6696 << ToType << OvlExpr->getSourceRange();
6697 return 0;
6698 }
6699
6700 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6701 if (OvlExpr->hasExplicitTemplateArgs()) {
6702 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6703 ExplicitTemplateArgs = &ETABuffer;
6704 }
6705
Douglas Gregor064fdb22010-04-14 23:11:21 +00006706 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006707
Douglas Gregorcd695e52008-11-10 20:40:00 +00006708 // Look through all of the overloaded functions, searching for one
6709 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006710 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006711 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006712
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006713 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006714 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6715 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006716 // Look through any using declarations to find the underlying function.
6717 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6718
Douglas Gregorcd695e52008-11-10 20:40:00 +00006719 // C++ [over.over]p3:
6720 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006721 // targets of type "pointer-to-function" or "reference-to-function."
6722 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006723 // type "pointer-to-member-function."
6724 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006725
Mike Stump11289f42009-09-09 15:08:12 +00006726 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006727 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006728 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006729 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006730 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006731 // static when converting to member pointer.
6732 if (Method->isStatic() == IsMember)
6733 continue;
6734 } else if (IsMember)
6735 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006736
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006737 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006738 // If the name is a function template, template argument deduction is
6739 // done (14.8.2.2), and if the argument deduction succeeds, the
6740 // resulting template argument list is used to generate a single
6741 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006742 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006743 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006744 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006745 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006746 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006747 FunctionType, Specialization, Info)) {
6748 // FIXME: make a note of the failed deduction for diagnostics.
6749 (void)Result;
6750 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006751 // Template argument deduction ensures that we have an exact match.
6752 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006753 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006754 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006755 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006756 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006757 }
John McCalld14a8642009-11-21 08:51:07 +00006758
6759 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006760 }
Mike Stump11289f42009-09-09 15:08:12 +00006761
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006763 // Skip non-static functions when converting to pointer, and static
6764 // when converting to member pointer.
6765 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006766 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006767
6768 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006769 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006770 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006771 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006772 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006773
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006774 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006775 QualType ResultTy;
6776 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6777 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6778 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006779 Matches.push_back(std::make_pair(I.getPair(),
6780 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006781 FoundNonTemplateFunction = true;
6782 }
Mike Stump11289f42009-09-09 15:08:12 +00006783 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006784 }
6785
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006786 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006787 if (Matches.empty()) {
6788 if (Complain) {
6789 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6790 << OvlExpr->getName() << FunctionType;
6791 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6792 E = OvlExpr->decls_end();
6793 I != E; ++I)
6794 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6795 NoteOverloadCandidate(F);
6796 }
6797
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006798 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006799 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006800 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006801 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006802 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006803 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006804 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006805 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006806 return Result;
6807 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006808
6809 // C++ [over.over]p4:
6810 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006811 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006812 // [...] and any given function template specialization F1 is
6813 // eliminated if the set contains a second function template
6814 // specialization whose function template is more specialized
6815 // than the function template of F1 according to the partial
6816 // ordering rules of 14.5.5.2.
6817
6818 // The algorithm specified above is quadratic. We instead use a
6819 // two-pass algorithm (similar to the one used to identify the
6820 // best viable function in an overload set) that identifies the
6821 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006822
6823 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6824 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6825 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006826
6827 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006828 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006829 TPOC_Other, From->getLocStart(),
6830 PDiag(),
6831 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006832 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006833 PDiag(diag::note_ovl_candidate)
6834 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006835 if (Result == MatchesCopy.end())
6836 return 0;
6837
John McCall58cc69d2010-01-27 01:50:18 +00006838 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006839 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006840 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006841 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006842 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006843 }
Mike Stump11289f42009-09-09 15:08:12 +00006844
Douglas Gregorfae1d712009-09-26 03:56:17 +00006845 // [...] any function template specializations in the set are
6846 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006847 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006848 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006849 ++I;
6850 else {
John McCalla0296f72010-03-19 07:35:19 +00006851 Matches[I] = Matches[--N];
6852 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006853 }
6854 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006855
Mike Stump11289f42009-09-09 15:08:12 +00006856 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006857 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006858 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006859 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006860 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006861 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006862 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6863 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006864 }
Mike Stump11289f42009-09-09 15:08:12 +00006865
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006866 // FIXME: We should probably return the same thing that BestViableFunction
6867 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006868 if (Complain) {
6869 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6870 << Matches[0].second->getDeclName();
6871 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6872 NoteOverloadCandidate(Matches[I].second);
6873 }
6874
Douglas Gregorcd695e52008-11-10 20:40:00 +00006875 return 0;
6876}
6877
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006878/// \brief Given an expression that refers to an overloaded function, try to
6879/// resolve that overloaded function expression down to a single function.
6880///
6881/// This routine can only resolve template-ids that refer to a single function
6882/// template, where that template-id refers to a single template whose template
6883/// arguments are either provided by the template-id or have defaults,
6884/// as described in C++0x [temp.arg.explicit]p3.
6885FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6886 // C++ [over.over]p1:
6887 // [...] [Note: any redundant set of parentheses surrounding the
6888 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006889 // C++ [over.over]p1:
6890 // [...] The overloaded function name can be preceded by the &
6891 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006892
6893 if (From->getType() != Context.OverloadTy)
6894 return 0;
6895
John McCall8d08b9b2010-08-27 09:08:28 +00006896 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006897
6898 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006899 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006900 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006901
6902 TemplateArgumentListInfo ExplicitTemplateArgs;
6903 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006904
6905 // Look through all of the overloaded functions, searching for one
6906 // whose type matches exactly.
6907 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006908 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6909 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006910 // C++0x [temp.arg.explicit]p3:
6911 // [...] In contexts where deduction is done and fails, or in contexts
6912 // where deduction is not done, if a template argument list is
6913 // specified and it, along with any default template arguments,
6914 // identifies a single function template specialization, then the
6915 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006916 FunctionTemplateDecl *FunctionTemplate
6917 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006918
6919 // C++ [over.over]p2:
6920 // If the name is a function template, template argument deduction is
6921 // done (14.8.2.2), and if the argument deduction succeeds, the
6922 // resulting template argument list is used to generate a single
6923 // function template specialization, which is added to the set of
6924 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006925 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006926 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006927 if (TemplateDeductionResult Result
6928 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6929 Specialization, Info)) {
6930 // FIXME: make a note of the failed deduction for diagnostics.
6931 (void)Result;
6932 continue;
6933 }
6934
6935 // Multiple matches; we can't resolve to a single declaration.
6936 if (Matched)
6937 return 0;
6938
6939 Matched = Specialization;
6940 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006941
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006942 return Matched;
6943}
6944
Douglas Gregorcabea402009-09-22 15:41:20 +00006945/// \brief Add a single candidate to the overload set.
6946static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006947 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006948 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006949 Expr **Args, unsigned NumArgs,
6950 OverloadCandidateSet &CandidateSet,
6951 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006952 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006953 if (isa<UsingShadowDecl>(Callee))
6954 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6955
Douglas Gregorcabea402009-09-22 15:41:20 +00006956 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006957 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006958 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006959 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006960 return;
John McCalld14a8642009-11-21 08:51:07 +00006961 }
6962
6963 if (FunctionTemplateDecl *FuncTemplate
6964 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006965 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6966 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006967 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006968 return;
6969 }
6970
6971 assert(false && "unhandled case in overloaded call candidate");
6972
6973 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006974}
6975
6976/// \brief Add the overload candidates named by callee and/or found by argument
6977/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006978void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006979 Expr **Args, unsigned NumArgs,
6980 OverloadCandidateSet &CandidateSet,
6981 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006982
6983#ifndef NDEBUG
6984 // Verify that ArgumentDependentLookup is consistent with the rules
6985 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006986 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006987 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6988 // and let Y be the lookup set produced by argument dependent
6989 // lookup (defined as follows). If X contains
6990 //
6991 // -- a declaration of a class member, or
6992 //
6993 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006994 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006995 //
6996 // -- a declaration that is neither a function or a function
6997 // template
6998 //
6999 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007000
John McCall57500772009-12-16 12:17:52 +00007001 if (ULE->requiresADL()) {
7002 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7003 E = ULE->decls_end(); I != E; ++I) {
7004 assert(!(*I)->getDeclContext()->isRecord());
7005 assert(isa<UsingShadowDecl>(*I) ||
7006 !(*I)->getDeclContext()->isFunctionOrMethod());
7007 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007008 }
7009 }
7010#endif
7011
John McCall57500772009-12-16 12:17:52 +00007012 // It would be nice to avoid this copy.
7013 TemplateArgumentListInfo TABuffer;
7014 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7015 if (ULE->hasExplicitTemplateArgs()) {
7016 ULE->copyTemplateArgumentsInto(TABuffer);
7017 ExplicitTemplateArgs = &TABuffer;
7018 }
7019
7020 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7021 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007022 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007023 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007024 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007025
John McCall57500772009-12-16 12:17:52 +00007026 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007027 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7028 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007029 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007030 CandidateSet,
7031 PartialOverloading);
7032}
John McCalld681c392009-12-16 08:11:27 +00007033
7034/// Attempts to recover from a call where no functions were found.
7035///
7036/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007037static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007038BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007039 UnresolvedLookupExpr *ULE,
7040 SourceLocation LParenLoc,
7041 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007042 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007043
7044 CXXScopeSpec SS;
7045 if (ULE->getQualifier()) {
7046 SS.setScopeRep(ULE->getQualifier());
7047 SS.setRange(ULE->getQualifierRange());
7048 }
7049
John McCall57500772009-12-16 12:17:52 +00007050 TemplateArgumentListInfo TABuffer;
7051 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7052 if (ULE->hasExplicitTemplateArgs()) {
7053 ULE->copyTemplateArgumentsInto(TABuffer);
7054 ExplicitTemplateArgs = &TABuffer;
7055 }
7056
John McCalld681c392009-12-16 08:11:27 +00007057 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7058 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007059 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007060 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007061
John McCall57500772009-12-16 12:17:52 +00007062 assert(!R.empty() && "lookup results empty despite recovery");
7063
7064 // Build an implicit member call if appropriate. Just drop the
7065 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007066 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007067 if ((*R.begin())->isCXXClassMember())
7068 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
7069 else if (ExplicitTemplateArgs)
7070 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7071 else
7072 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7073
7074 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007075 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007076
7077 // This shouldn't cause an infinite loop because we're giving it
7078 // an expression with non-empty lookup results, which should never
7079 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007080 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007081 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007082}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007083
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007084/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007085/// (which eventually refers to the declaration Func) and the call
7086/// arguments Args/NumArgs, attempt to resolve the function call down
7087/// to a specific function. If overload resolution succeeds, returns
7088/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007089/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007090/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007091ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007092Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007093 SourceLocation LParenLoc,
7094 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007095 SourceLocation RParenLoc) {
7096#ifndef NDEBUG
7097 if (ULE->requiresADL()) {
7098 // To do ADL, we must have found an unqualified name.
7099 assert(!ULE->getQualifier() && "qualified name with ADL");
7100
7101 // We don't perform ADL for implicit declarations of builtins.
7102 // Verify that this was correctly set up.
7103 FunctionDecl *F;
7104 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7105 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7106 F->getBuiltinID() && F->isImplicit())
7107 assert(0 && "performing ADL for builtin");
7108
7109 // We don't perform ADL in C.
7110 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7111 }
7112#endif
7113
John McCallbc077cf2010-02-08 23:07:23 +00007114 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007115
John McCall57500772009-12-16 12:17:52 +00007116 // Add the functions denoted by the callee to the set of candidate
7117 // functions, including those from argument-dependent lookup.
7118 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007119
7120 // If we found nothing, try to recover.
7121 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7122 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007123 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007124 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007125 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007126
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007127 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007128 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007129 case OR_Success: {
7130 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007131 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00007132 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007133 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00007134 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
7135 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007136
7137 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007138 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007139 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007140 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007141 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007142 break;
7143
7144 case OR_Ambiguous:
7145 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007146 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007147 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007148 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007149
7150 case OR_Deleted:
7151 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7152 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007153 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007154 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007155 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007156 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007157 }
7158
Douglas Gregorb412e172010-07-25 18:17:45 +00007159 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007160 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007161}
7162
John McCall4c4c1df2010-01-26 03:27:55 +00007163static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007164 return Functions.size() > 1 ||
7165 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7166}
7167
Douglas Gregor084d8552009-03-13 23:49:33 +00007168/// \brief Create a unary operation that may resolve to an overloaded
7169/// operator.
7170///
7171/// \param OpLoc The location of the operator itself (e.g., '*').
7172///
7173/// \param OpcIn The UnaryOperator::Opcode that describes this
7174/// operator.
7175///
7176/// \param Functions The set of non-member functions that will be
7177/// considered by overload resolution. The caller needs to build this
7178/// set based on the context using, e.g.,
7179/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7180/// set should not contain any member functions; those will be added
7181/// by CreateOverloadedUnaryOp().
7182///
7183/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007184ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007185Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7186 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007187 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007188 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007189
7190 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7191 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7192 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007193 // TODO: provide better source location info.
7194 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007195
John McCalle26a8722010-12-04 08:14:53 +00007196 if (Input->getObjectKind() == OK_ObjCProperty)
7197 ConvertPropertyForRValue(Input);
7198
Douglas Gregor084d8552009-03-13 23:49:33 +00007199 Expr *Args[2] = { Input, 0 };
7200 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007201
Douglas Gregor084d8552009-03-13 23:49:33 +00007202 // For post-increment and post-decrement, add the implicit '0' as
7203 // the second argument, so that we know this is a post-increment or
7204 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007205 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007206 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007207 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7208 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007209 NumArgs = 2;
7210 }
7211
7212 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007213 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007214 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007215 Opc,
7216 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007217 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007218 OpLoc));
7219
John McCall58cc69d2010-01-27 01:50:18 +00007220 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007221 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007222 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007223 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007224 /*ADL*/ true, IsOverloaded(Fns),
7225 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007226 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7227 &Args[0], NumArgs,
7228 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007229 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007230 OpLoc));
7231 }
7232
7233 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007234 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007235
7236 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007237 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007238
7239 // Add operator candidates that are member functions.
7240 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7241
John McCall4c4c1df2010-01-26 03:27:55 +00007242 // Add candidates from ADL.
7243 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007244 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007245 /*ExplicitTemplateArgs*/ 0,
7246 CandidateSet);
7247
Douglas Gregor084d8552009-03-13 23:49:33 +00007248 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007249 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007250
7251 // Perform overload resolution.
7252 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007253 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007254 case OR_Success: {
7255 // We found a built-in operator or an overloaded operator.
7256 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007257
Douglas Gregor084d8552009-03-13 23:49:33 +00007258 if (FnDecl) {
7259 // We matched an overloaded operator. Build a call to that
7260 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007261
Douglas Gregor084d8552009-03-13 23:49:33 +00007262 // Convert the arguments.
7263 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007264 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007265
John McCall16df1e52010-03-30 21:47:33 +00007266 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7267 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007268 return ExprError();
7269 } else {
7270 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007271 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007272 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007273 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007274 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007275 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007276 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007277 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007278 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007279 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007280 }
7281
John McCall4fa0d5f2010-05-06 18:15:07 +00007282 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7283
John McCall7decc9e2010-11-18 06:31:45 +00007284 // Determine the result type.
7285 QualType ResultTy = FnDecl->getResultType();
7286 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7287 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007288
Douglas Gregor084d8552009-03-13 23:49:33 +00007289 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007290 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007291
Eli Friedman030eee42009-11-18 03:58:17 +00007292 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007293 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007294 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007295 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007296
John McCallb268a282010-08-23 23:25:46 +00007297 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007298 FnDecl))
7299 return ExprError();
7300
John McCallb268a282010-08-23 23:25:46 +00007301 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007302 } else {
7303 // We matched a built-in operator. Convert the arguments, then
7304 // break out so that we will build the appropriate built-in
7305 // operator node.
7306 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007307 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007308 return ExprError();
7309
7310 break;
7311 }
7312 }
7313
7314 case OR_No_Viable_Function:
7315 // No viable function; fall through to handling this as a
7316 // built-in operator, which will produce an error message for us.
7317 break;
7318
7319 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007320 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007321 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007322 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007323 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007324 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7325 Args, NumArgs,
7326 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007327 return ExprError();
7328
7329 case OR_Deleted:
7330 Diag(OpLoc, diag::err_ovl_deleted_oper)
7331 << Best->Function->isDeleted()
7332 << UnaryOperator::getOpcodeStr(Opc)
7333 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007334 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007335 return ExprError();
7336 }
7337
7338 // Either we found no viable overloaded operator or we matched a
7339 // built-in operator. In either case, fall through to trying to
7340 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007341 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007342}
7343
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007344/// \brief Create a binary operation that may resolve to an overloaded
7345/// operator.
7346///
7347/// \param OpLoc The location of the operator itself (e.g., '+').
7348///
7349/// \param OpcIn The BinaryOperator::Opcode that describes this
7350/// operator.
7351///
7352/// \param Functions The set of non-member functions that will be
7353/// considered by overload resolution. The caller needs to build this
7354/// set based on the context using, e.g.,
7355/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7356/// set should not contain any member functions; those will be added
7357/// by CreateOverloadedBinOp().
7358///
7359/// \param LHS Left-hand argument.
7360/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007361ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007362Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007363 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007364 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007365 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007366 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007367 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007368
7369 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7370 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7371 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7372
7373 // If either side is type-dependent, create an appropriate dependent
7374 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007375 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007376 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007377 // If there are no functions to store, just build a dependent
7378 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007379 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007380 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007381 Context.DependentTy,
7382 VK_RValue, OK_Ordinary,
7383 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007384
7385 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7386 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007387 VK_LValue,
7388 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007389 Context.DependentTy,
7390 Context.DependentTy,
7391 OpLoc));
7392 }
John McCall4c4c1df2010-01-26 03:27:55 +00007393
7394 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007395 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007396 // TODO: provide better source location info in DNLoc component.
7397 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007398 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007399 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007400 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007401 /*ADL*/ true, IsOverloaded(Fns),
7402 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007403 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007404 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007405 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007406 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007407 OpLoc));
7408 }
7409
John McCalle26a8722010-12-04 08:14:53 +00007410 // Always do property rvalue conversions on the RHS.
7411 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7412 ConvertPropertyForRValue(Args[1]);
7413
7414 // The LHS is more complicated.
7415 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7416
7417 // There's a tension for assignment operators between primitive
7418 // property assignment and the overloaded operators.
7419 if (BinaryOperator::isAssignmentOp(Opc)) {
7420 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7421
7422 // Is the property "logically" settable?
7423 bool Settable = (PRE->isExplicitProperty() ||
7424 PRE->getImplicitPropertySetter());
7425
7426 // To avoid gratuitously inventing semantics, use the primitive
7427 // unless it isn't. Thoughts in case we ever really care:
7428 // - If the property isn't logically settable, we have to
7429 // load and hope.
7430 // - If the property is settable and this is simple assignment,
7431 // we really should use the primitive.
7432 // - If the property is settable, then we could try overloading
7433 // on a generic lvalue of the appropriate type; if it works
7434 // out to a builtin candidate, we would do that same operation
7435 // on the property, and otherwise just error.
7436 if (Settable)
7437 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7438 }
7439
7440 ConvertPropertyForRValue(Args[0]);
7441 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007442
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007443 // If this is the assignment operator, we only perform overload resolution
7444 // if the left-hand side is a class or enumeration type. This is actually
7445 // a hack. The standard requires that we do overload resolution between the
7446 // various built-in candidates, but as DR507 points out, this can lead to
7447 // problems. So we do it this way, which pretty much follows what GCC does.
7448 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007449 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007450 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007451
John McCalle26a8722010-12-04 08:14:53 +00007452 // If this is the .* operator, which is not overloadable, just
7453 // create a built-in binary operator.
7454 if (Opc == BO_PtrMemD)
7455 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7456
Douglas Gregor084d8552009-03-13 23:49:33 +00007457 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007458 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007459
7460 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007461 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007462
7463 // Add operator candidates that are member functions.
7464 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7465
John McCall4c4c1df2010-01-26 03:27:55 +00007466 // Add candidates from ADL.
7467 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7468 Args, 2,
7469 /*ExplicitTemplateArgs*/ 0,
7470 CandidateSet);
7471
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007472 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007473 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007474
7475 // Perform overload resolution.
7476 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007477 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007478 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007479 // We found a built-in operator or an overloaded operator.
7480 FunctionDecl *FnDecl = Best->Function;
7481
7482 if (FnDecl) {
7483 // We matched an overloaded operator. Build a call to that
7484 // operator.
7485
7486 // Convert the arguments.
7487 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007488 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007489 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007490
John McCalldadc5752010-08-24 06:29:42 +00007491 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007492 = PerformCopyInitialization(
7493 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007494 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007495 FnDecl->getParamDecl(0)),
7496 SourceLocation(),
7497 Owned(Args[1]));
7498 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007499 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007500
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007501 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007502 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007503 return ExprError();
7504
7505 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007506 } else {
7507 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007508 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007509 = PerformCopyInitialization(
7510 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007511 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007512 FnDecl->getParamDecl(0)),
7513 SourceLocation(),
7514 Owned(Args[0]));
7515 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007516 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007517
John McCalldadc5752010-08-24 06:29:42 +00007518 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007519 = PerformCopyInitialization(
7520 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007521 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007522 FnDecl->getParamDecl(1)),
7523 SourceLocation(),
7524 Owned(Args[1]));
7525 if (Arg1.isInvalid())
7526 return ExprError();
7527 Args[0] = LHS = Arg0.takeAs<Expr>();
7528 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007529 }
7530
John McCall4fa0d5f2010-05-06 18:15:07 +00007531 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7532
John McCall7decc9e2010-11-18 06:31:45 +00007533 // Determine the result type.
7534 QualType ResultTy = FnDecl->getResultType();
7535 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7536 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007537
7538 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007539 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007540
John McCallb268a282010-08-23 23:25:46 +00007541 CXXOperatorCallExpr *TheCall =
7542 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007543 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007544
John McCallb268a282010-08-23 23:25:46 +00007545 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007546 FnDecl))
7547 return ExprError();
7548
John McCallb268a282010-08-23 23:25:46 +00007549 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007550 } else {
7551 // We matched a built-in operator. Convert the arguments, then
7552 // break out so that we will build the appropriate built-in
7553 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007554 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007555 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007556 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007557 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007558 return ExprError();
7559
7560 break;
7561 }
7562 }
7563
Douglas Gregor66950a32009-09-30 21:46:01 +00007564 case OR_No_Viable_Function: {
7565 // C++ [over.match.oper]p9:
7566 // If the operator is the operator , [...] and there are no
7567 // viable functions, then the operator is assumed to be the
7568 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007569 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007570 break;
7571
Sebastian Redl027de2a2009-05-21 11:50:50 +00007572 // For class as left operand for assignment or compound assigment operator
7573 // do not fall through to handling in built-in, but report that no overloaded
7574 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007575 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007576 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007577 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007578 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7579 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007580 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007581 } else {
7582 // No viable function; try to create a built-in operation, which will
7583 // produce an error. Then, show the non-viable candidates.
7584 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007585 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007586 assert(Result.isInvalid() &&
7587 "C++ binary operator overloading is missing candidates!");
7588 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007589 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7590 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007591 return move(Result);
7592 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007593
7594 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007595 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007596 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007597 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007598 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007599 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7600 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007601 return ExprError();
7602
7603 case OR_Deleted:
7604 Diag(OpLoc, diag::err_ovl_deleted_oper)
7605 << Best->Function->isDeleted()
7606 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007607 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007608 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007609 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007610 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007611
Douglas Gregor66950a32009-09-30 21:46:01 +00007612 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007613 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007614}
7615
John McCalldadc5752010-08-24 06:29:42 +00007616ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007617Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7618 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007619 Expr *Base, Expr *Idx) {
7620 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007621 DeclarationName OpName =
7622 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7623
7624 // If either side is type-dependent, create an appropriate dependent
7625 // expression.
7626 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7627
John McCall58cc69d2010-01-27 01:50:18 +00007628 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007629 // CHECKME: no 'operator' keyword?
7630 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7631 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007632 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007633 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007634 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007635 /*ADL*/ true, /*Overloaded*/ false,
7636 UnresolvedSetIterator(),
7637 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007638 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007639
Sebastian Redladba46e2009-10-29 20:17:01 +00007640 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7641 Args, 2,
7642 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007643 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007644 RLoc));
7645 }
7646
John McCalle26a8722010-12-04 08:14:53 +00007647 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7648 ConvertPropertyForRValue(Args[0]);
7649 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7650 ConvertPropertyForRValue(Args[1]);
7651
Sebastian Redladba46e2009-10-29 20:17:01 +00007652 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007653 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007654
7655 // Subscript can only be overloaded as a member function.
7656
7657 // Add operator candidates that are member functions.
7658 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7659
7660 // Add builtin operator candidates.
7661 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7662
7663 // Perform overload resolution.
7664 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007665 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007666 case OR_Success: {
7667 // We found a built-in operator or an overloaded operator.
7668 FunctionDecl *FnDecl = Best->Function;
7669
7670 if (FnDecl) {
7671 // We matched an overloaded operator. Build a call to that
7672 // operator.
7673
John McCalla0296f72010-03-19 07:35:19 +00007674 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007675 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007676
Sebastian Redladba46e2009-10-29 20:17:01 +00007677 // Convert the arguments.
7678 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007679 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007680 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007681 return ExprError();
7682
Anders Carlssona68e51e2010-01-29 18:37:50 +00007683 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007684 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007685 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007686 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007687 FnDecl->getParamDecl(0)),
7688 SourceLocation(),
7689 Owned(Args[1]));
7690 if (InputInit.isInvalid())
7691 return ExprError();
7692
7693 Args[1] = InputInit.takeAs<Expr>();
7694
Sebastian Redladba46e2009-10-29 20:17:01 +00007695 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007696 QualType ResultTy = FnDecl->getResultType();
7697 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7698 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007699
7700 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007701 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007702
John McCallb268a282010-08-23 23:25:46 +00007703 CXXOperatorCallExpr *TheCall =
7704 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7705 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007706 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007707
John McCallb268a282010-08-23 23:25:46 +00007708 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007709 FnDecl))
7710 return ExprError();
7711
John McCallb268a282010-08-23 23:25:46 +00007712 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007713 } else {
7714 // We matched a built-in operator. Convert the arguments, then
7715 // break out so that we will build the appropriate built-in
7716 // operator node.
7717 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007718 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007719 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007720 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007721 return ExprError();
7722
7723 break;
7724 }
7725 }
7726
7727 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007728 if (CandidateSet.empty())
7729 Diag(LLoc, diag::err_ovl_no_oper)
7730 << Args[0]->getType() << /*subscript*/ 0
7731 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7732 else
7733 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7734 << Args[0]->getType()
7735 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007736 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7737 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007738 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007739 }
7740
7741 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007742 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7743 << "[]"
7744 << Args[0]->getType() << Args[1]->getType()
7745 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007746 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7747 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007748 return ExprError();
7749
7750 case OR_Deleted:
7751 Diag(LLoc, diag::err_ovl_deleted_oper)
7752 << Best->Function->isDeleted() << "[]"
7753 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7755 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007756 return ExprError();
7757 }
7758
7759 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007760 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007761}
7762
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007763/// BuildCallToMemberFunction - Build a call to a member
7764/// function. MemExpr is the expression that refers to the member
7765/// function (and includes the object parameter), Args/NumArgs are the
7766/// arguments to the function call (not including the object
7767/// parameter). The caller needs to validate that the member
7768/// expression refers to a member function or an overloaded member
7769/// function.
John McCalldadc5752010-08-24 06:29:42 +00007770ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007771Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7772 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007773 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007774 // Dig out the member expression. This holds both the object
7775 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007776 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7777
John McCall10eae182009-11-30 22:42:35 +00007778 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007779 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007780 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007781 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007782 if (isa<MemberExpr>(NakedMemExpr)) {
7783 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007784 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007785 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007786 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007787 } else {
7788 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007789 Qualifier = UnresExpr->getQualifier();
7790
John McCall6e9f8f62009-12-03 04:06:58 +00007791 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007792
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007793 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007794 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007795
John McCall2d74de92009-12-01 22:10:20 +00007796 // FIXME: avoid copy.
7797 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7798 if (UnresExpr->hasExplicitTemplateArgs()) {
7799 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7800 TemplateArgs = &TemplateArgsBuffer;
7801 }
7802
John McCall10eae182009-11-30 22:42:35 +00007803 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7804 E = UnresExpr->decls_end(); I != E; ++I) {
7805
John McCall6e9f8f62009-12-03 04:06:58 +00007806 NamedDecl *Func = *I;
7807 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7808 if (isa<UsingShadowDecl>(Func))
7809 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7810
John McCall10eae182009-11-30 22:42:35 +00007811 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007812 // If explicit template arguments were provided, we can't call a
7813 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007814 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007815 continue;
7816
John McCalla0296f72010-03-19 07:35:19 +00007817 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007818 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007819 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007820 } else {
John McCall10eae182009-11-30 22:42:35 +00007821 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007822 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007823 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007824 CandidateSet,
7825 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007826 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007827 }
Mike Stump11289f42009-09-09 15:08:12 +00007828
John McCall10eae182009-11-30 22:42:35 +00007829 DeclarationName DeclName = UnresExpr->getMemberName();
7830
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007831 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007832 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007833 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007834 case OR_Success:
7835 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007836 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007837 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007838 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007839 break;
7840
7841 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007842 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007843 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007844 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007845 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007846 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007847 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007848
7849 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007850 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007851 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007852 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007853 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007854 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007855
7856 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007857 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007858 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007859 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007860 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007861 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007862 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007863 }
7864
John McCall16df1e52010-03-30 21:47:33 +00007865 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007866
John McCall2d74de92009-12-01 22:10:20 +00007867 // If overload resolution picked a static member, build a
7868 // non-member call based on that function.
7869 if (Method->isStatic()) {
7870 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7871 Args, NumArgs, RParenLoc);
7872 }
7873
John McCall10eae182009-11-30 22:42:35 +00007874 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007875 }
7876
John McCall7decc9e2010-11-18 06:31:45 +00007877 QualType ResultType = Method->getResultType();
7878 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7879 ResultType = ResultType.getNonLValueExprType(Context);
7880
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007881 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007882 CXXMemberCallExpr *TheCall =
7883 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00007884 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007885
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007886 // Check for a valid return type.
7887 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007888 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007889 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007890
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007891 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007892 // We only need to do this if there was actually an overload; otherwise
7893 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007894 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007895 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007896 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7897 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007898 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007899 MemExpr->setBase(ObjectArg);
7900
7901 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007902 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007903 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007904 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007905 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007906
John McCallb268a282010-08-23 23:25:46 +00007907 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007908 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007909
John McCallb268a282010-08-23 23:25:46 +00007910 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007911}
7912
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007913/// BuildCallToObjectOfClassType - Build a call to an object of class
7914/// type (C++ [over.call.object]), which can end up invoking an
7915/// overloaded function call operator (@c operator()) or performing a
7916/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007917ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007918Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007919 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007920 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007921 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00007922 if (Object->getObjectKind() == OK_ObjCProperty)
7923 ConvertPropertyForRValue(Object);
7924
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007925 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007926 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007927
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007928 // C++ [over.call.object]p1:
7929 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007930 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007931 // candidate functions includes at least the function call
7932 // operators of T. The function call operators of T are obtained by
7933 // ordinary lookup of the name operator() in the context of
7934 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007935 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007936 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007937
7938 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007939 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007940 << Object->getSourceRange()))
7941 return true;
7942
John McCall27b18f82009-11-17 02:14:36 +00007943 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7944 LookupQualifiedName(R, Record->getDecl());
7945 R.suppressDiagnostics();
7946
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007947 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007948 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007949 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007950 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007951 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007952 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007953
Douglas Gregorab7897a2008-11-19 22:57:39 +00007954 // C++ [over.call.object]p2:
7955 // In addition, for each conversion function declared in T of the
7956 // form
7957 //
7958 // operator conversion-type-id () cv-qualifier;
7959 //
7960 // where cv-qualifier is the same cv-qualification as, or a
7961 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007962 // denotes the type "pointer to function of (P1,...,Pn) returning
7963 // R", or the type "reference to pointer to function of
7964 // (P1,...,Pn) returning R", or the type "reference to function
7965 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007966 // is also considered as a candidate function. Similarly,
7967 // surrogate call functions are added to the set of candidate
7968 // functions for each conversion function declared in an
7969 // accessible base class provided the function is not hidden
7970 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007971 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007972 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007973 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007974 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007975 NamedDecl *D = *I;
7976 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7977 if (isa<UsingShadowDecl>(D))
7978 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7979
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007980 // Skip over templated conversion functions; they aren't
7981 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007982 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007983 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007984
John McCall6e9f8f62009-12-03 04:06:58 +00007985 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007986
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007987 // Strip the reference type (if any) and then the pointer type (if
7988 // any) to get down to what might be a function type.
7989 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7990 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7991 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007992
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007993 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007994 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007995 Object->getType(), Args, NumArgs,
7996 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007997 }
Mike Stump11289f42009-09-09 15:08:12 +00007998
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007999 // Perform overload resolution.
8000 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008001 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8002 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008003 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008004 // Overload resolution succeeded; we'll build the appropriate call
8005 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008006 break;
8007
8008 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008009 if (CandidateSet.empty())
8010 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8011 << Object->getType() << /*call*/ 1
8012 << Object->getSourceRange();
8013 else
8014 Diag(Object->getSourceRange().getBegin(),
8015 diag::err_ovl_no_viable_object_call)
8016 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008018 break;
8019
8020 case OR_Ambiguous:
8021 Diag(Object->getSourceRange().getBegin(),
8022 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008023 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008024 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008025 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008026
8027 case OR_Deleted:
8028 Diag(Object->getSourceRange().getBegin(),
8029 diag::err_ovl_deleted_object_call)
8030 << Best->Function->isDeleted()
8031 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008032 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008033 break;
Mike Stump11289f42009-09-09 15:08:12 +00008034 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008035
Douglas Gregorb412e172010-07-25 18:17:45 +00008036 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008037 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008038
Douglas Gregorab7897a2008-11-19 22:57:39 +00008039 if (Best->Function == 0) {
8040 // Since there is no function declaration, this is one of the
8041 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008042 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008043 = cast<CXXConversionDecl>(
8044 Best->Conversions[0].UserDefined.ConversionFunction);
8045
John McCalla0296f72010-03-19 07:35:19 +00008046 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008047 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008048
Douglas Gregorab7897a2008-11-19 22:57:39 +00008049 // We selected one of the surrogate functions that converts the
8050 // object parameter to a function pointer. Perform the conversion
8051 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008052
8053 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008054 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00008055 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
8056 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008057
John McCallfaf5fb42010-08-26 23:41:50 +00008058 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008059 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008060 }
8061
John McCalla0296f72010-03-19 07:35:19 +00008062 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008063 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008064
Douglas Gregorab7897a2008-11-19 22:57:39 +00008065 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8066 // that calls this method, using Object for the implicit object
8067 // parameter and passing along the remaining arguments.
8068 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00008069 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008070
8071 unsigned NumArgsInProto = Proto->getNumArgs();
8072 unsigned NumArgsToCheck = NumArgs;
8073
8074 // Build the full argument list for the method call (the
8075 // implicit object parameter is placed at the beginning of the
8076 // list).
8077 Expr **MethodArgs;
8078 if (NumArgs < NumArgsInProto) {
8079 NumArgsToCheck = NumArgsInProto;
8080 MethodArgs = new Expr*[NumArgsInProto + 1];
8081 } else {
8082 MethodArgs = new Expr*[NumArgs + 1];
8083 }
8084 MethodArgs[0] = Object;
8085 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8086 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008087
John McCall7decc9e2010-11-18 06:31:45 +00008088 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008089
8090 // Once we've built TheCall, all of the expressions are properly
8091 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008092 QualType ResultTy = Method->getResultType();
8093 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8094 ResultTy = ResultTy.getNonLValueExprType(Context);
8095
John McCallb268a282010-08-23 23:25:46 +00008096 CXXOperatorCallExpr *TheCall =
8097 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8098 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008099 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008100 delete [] MethodArgs;
8101
John McCallb268a282010-08-23 23:25:46 +00008102 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008103 Method))
8104 return true;
8105
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008106 // We may have default arguments. If so, we need to allocate more
8107 // slots in the call for them.
8108 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008109 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008110 else if (NumArgs > NumArgsInProto)
8111 NumArgsToCheck = NumArgsInProto;
8112
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008113 bool IsError = false;
8114
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008115 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008116 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008117 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008118 TheCall->setArg(0, Object);
8119
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008120
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008121 // Check the argument types.
8122 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008123 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008124 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008125 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008126
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008127 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008128
John McCalldadc5752010-08-24 06:29:42 +00008129 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008130 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008131 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008132 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008133 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008134
8135 IsError |= InputInit.isInvalid();
8136 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008137 } else {
John McCalldadc5752010-08-24 06:29:42 +00008138 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008139 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8140 if (DefArg.isInvalid()) {
8141 IsError = true;
8142 break;
8143 }
8144
8145 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008146 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008147
8148 TheCall->setArg(i + 1, Arg);
8149 }
8150
8151 // If this is a variadic call, handle args passed through "...".
8152 if (Proto->isVariadic()) {
8153 // Promote the arguments (C99 6.5.2.2p7).
8154 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8155 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008156 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008157 TheCall->setArg(i + 1, Arg);
8158 }
8159 }
8160
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008161 if (IsError) return true;
8162
John McCallb268a282010-08-23 23:25:46 +00008163 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008164 return true;
8165
John McCalle172be52010-08-24 06:09:16 +00008166 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008167}
8168
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008169/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008170/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008171/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008172ExprResult
John McCallb268a282010-08-23 23:25:46 +00008173Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008174 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008175
John McCalle26a8722010-12-04 08:14:53 +00008176 if (Base->getObjectKind() == OK_ObjCProperty)
8177 ConvertPropertyForRValue(Base);
8178
John McCallbc077cf2010-02-08 23:07:23 +00008179 SourceLocation Loc = Base->getExprLoc();
8180
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008181 // C++ [over.ref]p1:
8182 //
8183 // [...] An expression x->m is interpreted as (x.operator->())->m
8184 // for a class object x of type T if T::operator->() exists and if
8185 // the operator is selected as the best match function by the
8186 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008187 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008188 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008189 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008190
John McCallbc077cf2010-02-08 23:07:23 +00008191 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008192 PDiag(diag::err_typecheck_incomplete_tag)
8193 << Base->getSourceRange()))
8194 return ExprError();
8195
John McCall27b18f82009-11-17 02:14:36 +00008196 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8197 LookupQualifiedName(R, BaseRecord->getDecl());
8198 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008199
8200 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008201 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008202 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008203 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008204 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008205
8206 // Perform overload resolution.
8207 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008208 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008209 case OR_Success:
8210 // Overload resolution succeeded; we'll build the call below.
8211 break;
8212
8213 case OR_No_Viable_Function:
8214 if (CandidateSet.empty())
8215 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008216 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008217 else
8218 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008219 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008220 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008221 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008222
8223 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008224 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8225 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008226 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008227 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008228
8229 case OR_Deleted:
8230 Diag(OpLoc, diag::err_ovl_deleted_oper)
8231 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008232 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008233 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008234 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008235 }
8236
John McCalla0296f72010-03-19 07:35:19 +00008237 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008238 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008239
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008240 // Convert the object parameter.
8241 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008242 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8243 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008244 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008245
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008246 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008247 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008248
John McCall7decc9e2010-11-18 06:31:45 +00008249 QualType ResultTy = Method->getResultType();
8250 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8251 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008252 CXXOperatorCallExpr *TheCall =
8253 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008254 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008255
John McCallb268a282010-08-23 23:25:46 +00008256 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008257 Method))
8258 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008259 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008260}
8261
Douglas Gregorcd695e52008-11-10 20:40:00 +00008262/// FixOverloadedFunctionReference - E is an expression that refers to
8263/// a C++ overloaded function (possibly with some parentheses and
8264/// perhaps a '&' around it). We have resolved the overloaded function
8265/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008266/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008267Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008268 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008269 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008270 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8271 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008272 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008273 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008274
8275 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8276 }
8277
8278 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008279 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8280 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008281 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008282 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008283 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008284 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008285 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008286 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008287
John McCallcf142162010-08-07 06:22:56 +00008288 return ImplicitCastExpr::Create(Context, ICE->getType(),
8289 ICE->getCastKind(),
8290 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008291 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008292 }
8293
8294 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008295 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008296 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008297 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8298 if (Method->isStatic()) {
8299 // Do nothing: static member functions aren't any different
8300 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008301 } else {
John McCalle66edc12009-11-24 19:00:30 +00008302 // Fix the sub expression, which really has to be an
8303 // UnresolvedLookupExpr holding an overloaded member function
8304 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008305 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8306 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008307 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008308 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008309
John McCalld14a8642009-11-21 08:51:07 +00008310 assert(isa<DeclRefExpr>(SubExpr)
8311 && "fixed to something other than a decl ref");
8312 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8313 && "fixed to a member ref with no nested name qualifier");
8314
8315 // We have taken the address of a pointer to member
8316 // function. Perform the computation here so that we get the
8317 // appropriate pointer to member type.
8318 QualType ClassType
8319 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8320 QualType MemPtrType
8321 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8322
John McCall7decc9e2010-11-18 06:31:45 +00008323 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8324 VK_RValue, OK_Ordinary,
8325 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008326 }
8327 }
John McCall16df1e52010-03-30 21:47:33 +00008328 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8329 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008330 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008331 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008332
John McCalle3027922010-08-25 11:45:40 +00008333 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008334 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008335 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008336 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008337 }
John McCalld14a8642009-11-21 08:51:07 +00008338
8339 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008340 // FIXME: avoid copy.
8341 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008342 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008343 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8344 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008345 }
8346
John McCalld14a8642009-11-21 08:51:07 +00008347 return DeclRefExpr::Create(Context,
8348 ULE->getQualifier(),
8349 ULE->getQualifierRange(),
8350 Fn,
8351 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008352 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008353 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008354 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008355 }
8356
John McCall10eae182009-11-30 22:42:35 +00008357 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008358 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008359 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8360 if (MemExpr->hasExplicitTemplateArgs()) {
8361 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8362 TemplateArgs = &TemplateArgsBuffer;
8363 }
John McCall6b51f282009-11-23 01:53:49 +00008364
John McCall2d74de92009-12-01 22:10:20 +00008365 Expr *Base;
8366
John McCall7decc9e2010-11-18 06:31:45 +00008367 // If we're filling in a static method where we used to have an
8368 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008369 if (MemExpr->isImplicitAccess()) {
8370 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8371 return DeclRefExpr::Create(Context,
8372 MemExpr->getQualifier(),
8373 MemExpr->getQualifierRange(),
8374 Fn,
8375 MemExpr->getMemberLoc(),
8376 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008377 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008378 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008379 } else {
8380 SourceLocation Loc = MemExpr->getMemberLoc();
8381 if (MemExpr->getQualifier())
8382 Loc = MemExpr->getQualifierRange().getBegin();
8383 Base = new (Context) CXXThisExpr(Loc,
8384 MemExpr->getBaseType(),
8385 /*isImplicit=*/true);
8386 }
John McCall2d74de92009-12-01 22:10:20 +00008387 } else
John McCallc3007a22010-10-26 07:05:15 +00008388 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008389
8390 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008391 MemExpr->isArrow(),
8392 MemExpr->getQualifier(),
8393 MemExpr->getQualifierRange(),
8394 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008395 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008396 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008397 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008398 Fn->getType(),
8399 cast<CXXMethodDecl>(Fn)->isStatic()
8400 ? VK_LValue : VK_RValue,
8401 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008402 }
8403
John McCallc3007a22010-10-26 07:05:15 +00008404 llvm_unreachable("Invalid reference to overloaded function");
8405 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008406}
8407
John McCalldadc5752010-08-24 06:29:42 +00008408ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8409 DeclAccessPair Found,
8410 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008411 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008412}
8413
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008414} // end namespace clang