blob: 0ff8dc4ace3bad31b6a83f819bf4d72ea57cc737 [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
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004547
Douglas Gregord08452f2008-11-19 15:42:04 +00004548/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4549/// operator overloads to the candidate set (C++ [over.built]), based
4550/// on the operator @p Op and the arguments given. For example, if the
4551/// operator is a binary '+', this routine might add "int
4552/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004553void
Mike Stump11289f42009-09-09 15:08:12 +00004554Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004555 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004556 Expr **Args, unsigned NumArgs,
4557 OverloadCandidateSet& CandidateSet) {
John McCall52872982010-11-13 05:51:15 +00004558 // Information about arithmetic types useful to builtin-type
4559 // calculations.
4560
4561 // The "promoted arithmetic types" are the arithmetic
4562 // types are that preserved by promotion (C++ [over.built]p2).
4563
4564 static const unsigned FirstIntegralType = 3;
4565 static const unsigned LastIntegralType = 18;
4566 static const unsigned FirstPromotedIntegralType = 3,
4567 LastPromotedIntegralType = 9;
4568 static const unsigned FirstPromotedArithmeticType = 0,
4569 LastPromotedArithmeticType = 9;
4570 static const unsigned NumArithmeticTypes = 18;
4571
John McCall988ffb72010-11-13 02:01:09 +00004572 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall52872982010-11-13 05:51:15 +00004573 // Start of promoted types.
4574 &ASTContext::FloatTy,
4575 &ASTContext::DoubleTy,
4576 &ASTContext::LongDoubleTy,
4577
4578 // Start of integral types.
4579 &ASTContext::IntTy,
4580 &ASTContext::LongTy,
4581 &ASTContext::LongLongTy,
4582 &ASTContext::UnsignedIntTy,
4583 &ASTContext::UnsignedLongTy,
4584 &ASTContext::UnsignedLongLongTy,
4585 // End of promoted types.
4586
John McCall988ffb72010-11-13 02:01:09 +00004587 &ASTContext::BoolTy,
4588 &ASTContext::CharTy,
4589 &ASTContext::WCharTy,
4590 &ASTContext::Char16Ty,
4591 &ASTContext::Char32Ty,
4592 &ASTContext::SignedCharTy,
4593 &ASTContext::ShortTy,
4594 &ASTContext::UnsignedCharTy,
John McCall52872982010-11-13 05:51:15 +00004595 &ASTContext::UnsignedShortTy
4596 // End of integral types.
Douglas Gregora11693b2008-11-12 17:17:38 +00004597 };
John McCall52872982010-11-13 05:51:15 +00004598 // FIXME: What about complex?
John McCall988ffb72010-11-13 02:01:09 +00004599 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004600 "Invalid first promoted integral type");
4601 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall988ffb72010-11-13 02:01:09 +00004602 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004603 "Invalid last promoted integral type");
John McCall52872982010-11-13 05:51:15 +00004604 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004605 "Invalid first promoted arithmetic type");
4606 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall52872982010-11-13 05:51:15 +00004607 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregorb8440a72009-10-21 22:01:30 +00004608 "Invalid last promoted arithmetic type");
John McCall52872982010-11-13 05:51:15 +00004609
4610 // Accelerator table for performing the usual arithmetic conversions.
4611 // The rules are basically:
4612 // - if either is floating-point, use the wider floating-point
4613 // - if same signedness, use the higher rank
4614 // - if same size, use unsigned of the higher rank
4615 // - use the larger type
4616 // These rules, together with the axiom that higher ranks are
4617 // never smaller, are sufficient to precompute all of these results
4618 // *except* when dealing with signed types of higher rank.
4619 // (we could precompute SLL x UI for all known platforms, but it's
4620 // better not to make any assumptions).
4621 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4622 static PromT UsualArithmeticConversionsTypes
4623 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4624 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4625 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4626 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4627 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4628 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4629 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4630 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4631 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4632 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4633 };
4634 struct UsualArithmeticConversionsType {
4635 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4636 assert(L < LastPromotedArithmeticType);
4637 assert(R < LastPromotedArithmeticType);
4638 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4639
4640 // Fast path: the table gives us a concrete answer.
4641 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4642
4643 // Slow path: we need to compare widths.
4644 // An invariant is that the signed type has higher rank.
4645 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4646 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4647
4648 // If they're different widths, use the signed type.
4649 if (LW > RW) return LT;
4650 else if (LW > RW) return RT;
4651
4652 // Otherwise, use the unsigned type of the signed type's rank.
4653 if (L == SL || R == SL) return C.UnsignedLongTy;
4654 assert(L == SLL || R == SLL);
4655 return C.UnsignedLongLongTy;
4656 }
4657 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004658
Douglas Gregora11693b2008-11-12 17:17:38 +00004659 // Find all of the types that the arguments can convert to, but only
4660 // if the operator we're looking at has built-in operator candidates
4661 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004662 Qualifiers VisibleTypeConversionsQuals;
4663 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004664 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4665 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4666
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004667 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4668 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4669 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4670 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4671 OpLoc,
4672 true,
4673 (Op == OO_Exclaim ||
4674 Op == OO_AmpAmp ||
4675 Op == OO_PipePipe),
4676 VisibleTypeConversionsQuals);
4677 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004678
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004679 // C++ [over.built]p1:
4680 // If there is a user-written candidate with the same name and parameter
4681 // types as a built-in candidate operator function, the built-in operator
4682 // function is hidden and is not included in the set of candidate functions.
4683 //
4684 // The text is actually in a note, but if we don't implement it then we end
4685 // up with ambiguities when the user provides an overloaded operator for
4686 // an enumeration type. Note that only enumeration types have this problem,
4687 // so we track which enumeration types we've seen operators for.
4688 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4689 UserDefinedBinaryOperators;
4690
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004691 /// Set of (canonical) types that we've already handled.
4692 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4693
4694 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4695 if (CandidateTypes[ArgIdx].enumeration_begin()
4696 != CandidateTypes[ArgIdx].enumeration_end()) {
4697 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4698 CEnd = CandidateSet.end();
4699 C != CEnd; ++C) {
4700 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4701 continue;
4702
4703 // Check if the first parameter is of enumeration type.
4704 QualType FirstParamType
4705 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4706 if (!FirstParamType->isEnumeralType())
4707 continue;
4708
4709 // Check if the second parameter is of enumeration type.
4710 QualType SecondParamType
4711 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4712 if (!SecondParamType->isEnumeralType())
4713 continue;
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004714
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004715 // Add this operator to the set of known user-defined operators.
4716 UserDefinedBinaryOperators.insert(
4717 std::make_pair(Context.getCanonicalType(FirstParamType),
4718 Context.getCanonicalType(SecondParamType)));
4719 }
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004720 }
4721 }
4722
Douglas Gregora11693b2008-11-12 17:17:38 +00004723 bool isComparison = false;
4724 switch (Op) {
4725 case OO_None:
4726 case NUM_OVERLOADED_OPERATORS:
4727 assert(false && "Expected an overloaded operator");
4728 break;
4729
Douglas Gregord08452f2008-11-19 15:42:04 +00004730 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004731 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004732 goto UnaryStar;
4733 else
4734 goto BinaryStar;
4735 break;
4736
4737 case OO_Plus: // '+' is either unary or binary
4738 if (NumArgs == 1)
4739 goto UnaryPlus;
4740 else
4741 goto BinaryPlus;
4742 break;
4743
4744 case OO_Minus: // '-' is either unary or binary
4745 if (NumArgs == 1)
4746 goto UnaryMinus;
4747 else
4748 goto BinaryMinus;
4749 break;
4750
4751 case OO_Amp: // '&' is either unary or binary
4752 if (NumArgs == 1)
4753 goto UnaryAmp;
4754 else
4755 goto BinaryAmp;
4756
4757 case OO_PlusPlus:
4758 case OO_MinusMinus:
4759 // C++ [over.built]p3:
4760 //
4761 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4762 // is either volatile or empty, there exist candidate operator
4763 // functions of the form
4764 //
4765 // VQ T& operator++(VQ T&);
4766 // T operator++(VQ T&, int);
4767 //
4768 // C++ [over.built]p4:
4769 //
4770 // For every pair (T, VQ), where T is an arithmetic type other
4771 // than bool, and VQ is either volatile or empty, there exist
4772 // candidate operator functions of the form
4773 //
4774 // VQ T& operator--(VQ T&);
4775 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004776 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004777 Arith < NumArithmeticTypes; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004778 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004779 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004780 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004781
4782 // Non-volatile version.
4783 if (NumArgs == 1)
4784 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4785 else
4786 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004787 // heuristic to reduce number of builtin candidates in the set.
4788 // Add volatile version only if there are conversions to a volatile type.
4789 if (VisibleTypeConversionsQuals.hasVolatile()) {
4790 // Volatile version
4791 ParamTypes[0]
4792 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4793 if (NumArgs == 1)
4794 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4795 else
4796 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4797 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004798 }
4799
4800 // C++ [over.built]p5:
4801 //
4802 // For every pair (T, VQ), where T is a cv-qualified or
4803 // cv-unqualified object type, and VQ is either volatile or
4804 // empty, there exist candidate operator functions of the form
4805 //
4806 // T*VQ& operator++(T*VQ&);
4807 // T*VQ& operator--(T*VQ&);
4808 // T* operator++(T*VQ&, int);
4809 // T* operator--(T*VQ&, int);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004810 for (BuiltinCandidateTypeSet::iterator
4811 Ptr = CandidateTypes[0].pointer_begin(),
4812 PtrEnd = CandidateTypes[0].pointer_end();
4813 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004814 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004815 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004816 continue;
4817
Mike Stump11289f42009-09-09 15:08:12 +00004818 QualType ParamTypes[2] = {
4819 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004820 };
Mike Stump11289f42009-09-09 15:08:12 +00004821
Douglas Gregord08452f2008-11-19 15:42:04 +00004822 // Without volatile
4823 if (NumArgs == 1)
4824 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4825 else
4826 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4827
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004828 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4829 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004830 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004831 ParamTypes[0]
4832 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004833 if (NumArgs == 1)
4834 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4835 else
4836 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4837 }
4838 }
4839 break;
4840
4841 UnaryStar:
4842 // C++ [over.built]p6:
4843 // For every cv-qualified or cv-unqualified object type T, there
4844 // exist candidate operator functions of the form
4845 //
4846 // T& operator*(T*);
4847 //
4848 // C++ [over.built]p7:
4849 // For every function type T, there exist candidate operator
4850 // functions of the form
4851 // T& operator*(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004852 for (BuiltinCandidateTypeSet::iterator
4853 Ptr = CandidateTypes[0].pointer_begin(),
4854 PtrEnd = CandidateTypes[0].pointer_end();
4855 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004856 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004857 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004858 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004859 &ParamTy, Args, 1, CandidateSet);
4860 }
4861 break;
4862
4863 UnaryPlus:
4864 // C++ [over.built]p8:
4865 // For every type T, there exist candidate operator functions of
4866 // the form
4867 //
4868 // T* operator+(T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004869 for (BuiltinCandidateTypeSet::iterator
4870 Ptr = CandidateTypes[0].pointer_begin(),
4871 PtrEnd = CandidateTypes[0].pointer_end();
4872 Ptr != PtrEnd; ++Ptr) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004873 QualType ParamTy = *Ptr;
4874 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4875 }
Mike Stump11289f42009-09-09 15:08:12 +00004876
Douglas Gregord08452f2008-11-19 15:42:04 +00004877 // Fall through
4878
4879 UnaryMinus:
4880 // C++ [over.built]p9:
4881 // For every promoted arithmetic type T, there exist candidate
4882 // operator functions of the form
4883 //
4884 // T operator+(T);
4885 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004886 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004887 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall988ffb72010-11-13 02:01:09 +00004888 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregord08452f2008-11-19 15:42:04 +00004889 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4890 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004891
4892 // Extension: We also add these operators for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004893 for (BuiltinCandidateTypeSet::iterator
4894 Vec = CandidateTypes[0].vector_begin(),
4895 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004896 Vec != VecEnd; ++Vec) {
4897 QualType VecTy = *Vec;
4898 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4899 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004900 break;
4901
4902 case OO_Tilde:
4903 // C++ [over.built]p10:
4904 // For every promoted integral type T, there exist candidate
4905 // operator functions of the form
4906 //
4907 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004908 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004909 Int < LastPromotedIntegralType; ++Int) {
John McCall988ffb72010-11-13 02:01:09 +00004910 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregord08452f2008-11-19 15:42:04 +00004911 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4912 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004913
4914 // Extension: We also add this operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004915 for (BuiltinCandidateTypeSet::iterator
4916 Vec = CandidateTypes[0].vector_begin(),
4917 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004918 Vec != VecEnd; ++Vec) {
4919 QualType VecTy = *Vec;
4920 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4921 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004922 break;
4923
Douglas Gregora11693b2008-11-12 17:17:38 +00004924 case OO_New:
4925 case OO_Delete:
4926 case OO_Array_New:
4927 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004928 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004929 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004930 break;
4931
4932 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004933 UnaryAmp:
4934 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004935 // C++ [over.match.oper]p3:
4936 // -- For the operator ',', the unary operator '&', or the
4937 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004938 break;
4939
Douglas Gregor84605ae2009-08-24 13:43:27 +00004940 case OO_EqualEqual:
4941 case OO_ExclaimEqual:
4942 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004943 // For every pointer to member type T, there exist candidate operator
4944 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004945 //
4946 // bool operator==(T,T);
4947 // bool operator!=(T,T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004948 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4949 for (BuiltinCandidateTypeSet::iterator
4950 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4951 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4952 MemPtr != MemPtrEnd;
4953 ++MemPtr) {
4954 // Don't add the same builtin candidate twice.
4955 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4956 continue;
4957
4958 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4959 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4960 }
Douglas Gregor84605ae2009-08-24 13:43:27 +00004961 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004962 AddedTypes.clear();
4963
Douglas Gregor84605ae2009-08-24 13:43:27 +00004964 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004965
Douglas Gregora11693b2008-11-12 17:17:38 +00004966 case OO_Less:
4967 case OO_Greater:
4968 case OO_LessEqual:
4969 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004970 // C++ [over.built]p15:
4971 //
4972 // For every pointer or enumeration type T, there exist
4973 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004974 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004975 // bool operator<(T, T);
4976 // bool operator>(T, T);
4977 // bool operator<=(T, T);
4978 // bool operator>=(T, T);
4979 // bool operator==(T, T);
4980 // bool operator!=(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004981 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4982 for (BuiltinCandidateTypeSet::iterator
4983 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4984 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4985 Ptr != PtrEnd; ++Ptr) {
4986 // Don't add the same builtin candidate twice.
4987 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4988 continue;
4989
4990 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004991 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00004992 }
4993 for (BuiltinCandidateTypeSet::iterator
4994 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4995 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4996 Enum != EnumEnd; ++Enum) {
4997 // Don't add the same builtin candidate twice.
4998 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4999 continue;
5000
5001 QualType ParamTypes[2] = { *Enum, *Enum };
5002 CanQualType CanonType = Context.getCanonicalType(*Enum);
5003 if (!UserDefinedBinaryOperators.count(
5004 std::make_pair(CanonType, CanonType)))
5005 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
5006 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005007 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005008 AddedTypes.clear();
5009
Douglas Gregora11693b2008-11-12 17:17:38 +00005010 // Fall through.
5011 isComparison = true;
5012
Douglas Gregord08452f2008-11-19 15:42:04 +00005013 BinaryPlus:
5014 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00005015 if (!isComparison) {
5016 // We didn't fall through, so we must have OO_Plus or OO_Minus.
5017
5018 // C++ [over.built]p13:
5019 //
5020 // For every cv-qualified or cv-unqualified object type T
5021 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005022 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005023 // T* operator+(T*, ptrdiff_t);
5024 // T& operator[](T*, ptrdiff_t); [BELOW]
5025 // T* operator-(T*, ptrdiff_t);
5026 // T* operator+(ptrdiff_t, T*);
5027 // T& operator[](ptrdiff_t, T*); [BELOW]
5028 //
5029 // C++ [over.built]p14:
5030 //
5031 // For every T, where T is a pointer to object type, there
5032 // exist candidate operator functions of the form
5033 //
5034 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005035 for (BuiltinCandidateTypeSet::iterator
5036 Ptr = CandidateTypes[0].pointer_begin(),
5037 PtrEnd = CandidateTypes[0].pointer_end();
5038 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005039 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
5040
5041 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5042 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5043
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005044 if (Op == OO_Minus) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005045 // ptrdiff_t operator-(T, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005046 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5047 continue;
5048
Douglas Gregora11693b2008-11-12 17:17:38 +00005049 ParamTypes[1] = *Ptr;
5050 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5051 Args, 2, CandidateSet);
5052 }
5053 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005054
5055 for (BuiltinCandidateTypeSet::iterator
5056 Ptr = CandidateTypes[1].pointer_begin(),
5057 PtrEnd = CandidateTypes[1].pointer_end();
5058 Ptr != PtrEnd; ++Ptr) {
5059 if (Op == OO_Plus) {
5060 // T* operator+(ptrdiff_t, T*);
5061 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5062 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5063 } else {
5064 // ptrdiff_t operator-(T, T);
5065 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5066 continue;
5067
5068 QualType ParamTypes[2] = { *Ptr, *Ptr };
5069 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5070 Args, 2, CandidateSet);
5071 }
5072 }
5073
5074 AddedTypes.clear();
Douglas Gregora11693b2008-11-12 17:17:38 +00005075 }
5076 // Fall through
5077
Douglas Gregora11693b2008-11-12 17:17:38 +00005078 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00005079 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00005080 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00005081 // C++ [over.built]p12:
5082 //
5083 // For every pair of promoted arithmetic types L and R, there
5084 // exist candidate operator functions of the form
5085 //
5086 // LR operator*(L, R);
5087 // LR operator/(L, R);
5088 // LR operator+(L, R);
5089 // LR operator-(L, R);
5090 // bool operator<(L, R);
5091 // bool operator>(L, R);
5092 // bool operator<=(L, R);
5093 // bool operator>=(L, R);
5094 // bool operator==(L, R);
5095 // bool operator!=(L, R);
5096 //
5097 // where LR is the result of the usual arithmetic conversions
5098 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005099 //
5100 // C++ [over.built]p24:
5101 //
5102 // For every pair of promoted arithmetic types L and R, there exist
5103 // candidate operator functions of the form
5104 //
5105 // LR operator?(bool, L, R);
5106 //
5107 // where LR is the result of the usual arithmetic conversions
5108 // between types L and R.
5109 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005110 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005111 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005112 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005113 Right < LastPromotedArithmeticType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005114 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5115 Context.*ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005116 QualType Result
5117 = isComparison
5118 ? Context.BoolTy
John McCall52872982010-11-13 05:51:15 +00005119 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005120 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5121 }
5122 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005123
5124 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5125 // conditional operator for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005126 for (BuiltinCandidateTypeSet::iterator
5127 Vec1 = CandidateTypes[0].vector_begin(),
5128 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005129 Vec1 != Vec1End; ++Vec1)
5130 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005131 Vec2 = CandidateTypes[1].vector_begin(),
5132 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005133 Vec2 != Vec2End; ++Vec2) {
5134 QualType LandR[2] = { *Vec1, *Vec2 };
5135 QualType Result;
5136 if (isComparison)
5137 Result = Context.BoolTy;
5138 else {
5139 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5140 Result = *Vec1;
5141 else
5142 Result = *Vec2;
5143 }
5144
5145 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5146 }
5147
Douglas Gregora11693b2008-11-12 17:17:38 +00005148 break;
5149
5150 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00005151 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00005152 case OO_Caret:
5153 case OO_Pipe:
5154 case OO_LessLess:
5155 case OO_GreaterGreater:
5156 // C++ [over.built]p17:
5157 //
5158 // For every pair of promoted integral types L and R, there
5159 // exist candidate operator functions of the form
5160 //
5161 // LR operator%(L, R);
5162 // LR operator&(L, R);
5163 // LR operator^(L, R);
5164 // LR operator|(L, R);
5165 // L operator<<(L, R);
5166 // L operator>>(L, R);
5167 //
5168 // where LR is the result of the usual arithmetic conversions
5169 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00005170 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005171 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005172 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005173 Right < LastPromotedIntegralType; ++Right) {
John McCall988ffb72010-11-13 02:01:09 +00005174 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5175 Context.*ArithmeticTypes[Right] };
Douglas Gregora11693b2008-11-12 17:17:38 +00005176 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5177 ? LandR[0]
John McCall52872982010-11-13 05:51:15 +00005178 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregora11693b2008-11-12 17:17:38 +00005179 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5180 }
5181 }
5182 break;
5183
5184 case OO_Equal:
5185 // C++ [over.built]p20:
5186 //
5187 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00005188 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00005189 // empty, there exist candidate operator functions of the form
5190 //
5191 // VQ T& operator=(VQ T&, T);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005192 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5193 for (BuiltinCandidateTypeSet::iterator
5194 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5195 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5196 Enum != EnumEnd; ++Enum) {
5197 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5198 continue;
5199
5200 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5201 CandidateSet);
5202 }
5203
5204 for (BuiltinCandidateTypeSet::iterator
5205 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5206 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5207 MemPtr != MemPtrEnd; ++MemPtr) {
5208 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5209 continue;
5210
5211 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5212 CandidateSet);
5213 }
5214 }
5215 AddedTypes.clear();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005216
5217 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005218
5219 case OO_PlusEqual:
5220 case OO_MinusEqual:
5221 // C++ [over.built]p19:
5222 //
5223 // For every pair (T, VQ), where T is any type and VQ is either
5224 // volatile or empty, there exist candidate operator functions
5225 // of the form
5226 //
5227 // T*VQ& operator=(T*VQ&, T*);
5228 //
5229 // C++ [over.built]p21:
5230 //
5231 // For every pair (T, VQ), where T is a cv-qualified or
5232 // cv-unqualified object type and VQ is either volatile or
5233 // empty, there exist candidate operator functions of the form
5234 //
5235 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5236 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005237 for (BuiltinCandidateTypeSet::iterator
5238 Ptr = CandidateTypes[0].pointer_begin(),
5239 PtrEnd = CandidateTypes[0].pointer_end();
5240 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005241 QualType ParamTypes[2];
5242 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5243
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005244 // If this is operator=, keep track of the builtin candidates we added.
5245 if (Op == OO_Equal)
5246 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5247
Douglas Gregora11693b2008-11-12 17:17:38 +00005248 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005249 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005250 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5251 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005252
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005253 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5254 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005255 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005256 ParamTypes[0]
5257 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005258 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5259 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005260 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005261 }
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005262
5263 if (Op == OO_Equal) {
5264 for (BuiltinCandidateTypeSet::iterator
5265 Ptr = CandidateTypes[1].pointer_begin(),
5266 PtrEnd = CandidateTypes[1].pointer_end();
5267 Ptr != PtrEnd; ++Ptr) {
5268 // Make sure we don't add the same candidate twice.
5269 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5270 continue;
5271
5272 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5273
5274 // non-volatile version
5275 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5276 /*IsAssigmentOperator=*/true);
5277
5278 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5279 VisibleTypeConversionsQuals.hasVolatile()) {
5280 // volatile version
5281 ParamTypes[0]
5282 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5283 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5284 /*IsAssigmentOperator=*/true);
5285 }
5286 }
5287 AddedTypes.clear();
5288 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005289 // Fall through.
5290
5291 case OO_StarEqual:
5292 case OO_SlashEqual:
5293 // C++ [over.built]p18:
5294 //
5295 // For every triple (L, VQ, R), where L is an arithmetic type,
5296 // VQ is either volatile or empty, and R is a promoted
5297 // arithmetic type, there exist candidate operator functions of
5298 // the form
5299 //
5300 // VQ L& operator=(VQ L&, R);
5301 // VQ L& operator*=(VQ L&, R);
5302 // VQ L& operator/=(VQ L&, R);
5303 // VQ L& operator+=(VQ L&, R);
5304 // VQ L& operator-=(VQ L&, R);
5305 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005306 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005307 Right < LastPromotedArithmeticType; ++Right) {
5308 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005309 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005310
5311 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005312 ParamTypes[0] =
5313 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005314 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5315 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005316
5317 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005318 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall988ffb72010-11-13 02:01:09 +00005319 ParamTypes[0] =
5320 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005321 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5322 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5323 /*IsAssigmentOperator=*/Op == OO_Equal);
5324 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005325 }
5326 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005327
5328 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005329 for (BuiltinCandidateTypeSet::iterator
5330 Vec1 = CandidateTypes[0].vector_begin(),
5331 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005332 Vec1 != Vec1End; ++Vec1)
5333 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005334 Vec2 = CandidateTypes[1].vector_begin(),
5335 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005336 Vec2 != Vec2End; ++Vec2) {
5337 QualType ParamTypes[2];
5338 ParamTypes[1] = *Vec2;
5339 // Add this built-in operator as a candidate (VQ is empty).
5340 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5341 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5342 /*IsAssigmentOperator=*/Op == OO_Equal);
5343
5344 // Add this built-in operator as a candidate (VQ is 'volatile').
5345 if (VisibleTypeConversionsQuals.hasVolatile()) {
5346 ParamTypes[0] = Context.getVolatileType(*Vec1);
5347 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5348 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5349 /*IsAssigmentOperator=*/Op == OO_Equal);
5350 }
5351 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005352 break;
5353
5354 case OO_PercentEqual:
5355 case OO_LessLessEqual:
5356 case OO_GreaterGreaterEqual:
5357 case OO_AmpEqual:
5358 case OO_CaretEqual:
5359 case OO_PipeEqual:
5360 // C++ [over.built]p22:
5361 //
5362 // For every triple (L, VQ, R), where L is an integral type, VQ
5363 // is either volatile or empty, and R is a promoted integral
5364 // type, there exist candidate operator functions of the form
5365 //
5366 // VQ L& operator%=(VQ L&, R);
5367 // VQ L& operator<<=(VQ L&, R);
5368 // VQ L& operator>>=(VQ L&, R);
5369 // VQ L& operator&=(VQ L&, R);
5370 // VQ L& operator^=(VQ L&, R);
5371 // VQ L& operator|=(VQ L&, R);
5372 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005373 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005374 Right < LastPromotedIntegralType; ++Right) {
5375 QualType ParamTypes[2];
John McCall988ffb72010-11-13 02:01:09 +00005376 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregora11693b2008-11-12 17:17:38 +00005377
5378 // Add this built-in operator as a candidate (VQ is empty).
John McCall988ffb72010-11-13 02:01:09 +00005379 ParamTypes[0] =
5380 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005381 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005382 if (VisibleTypeConversionsQuals.hasVolatile()) {
5383 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall988ffb72010-11-13 02:01:09 +00005384 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005385 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5386 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5387 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5388 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005389 }
5390 }
5391 break;
5392
Douglas Gregord08452f2008-11-19 15:42:04 +00005393 case OO_Exclaim: {
5394 // C++ [over.operator]p23:
5395 //
5396 // There also exist candidate operator functions of the form
5397 //
Mike Stump11289f42009-09-09 15:08:12 +00005398 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005399 // bool operator&&(bool, bool); [BELOW]
5400 // bool operator||(bool, bool); [BELOW]
5401 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005402 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5403 /*IsAssignmentOperator=*/false,
5404 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005405 break;
5406 }
5407
Douglas Gregora11693b2008-11-12 17:17:38 +00005408 case OO_AmpAmp:
5409 case OO_PipePipe: {
5410 // C++ [over.operator]p23:
5411 //
5412 // There also exist candidate operator functions of the form
5413 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005414 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005415 // bool operator&&(bool, bool);
5416 // bool operator||(bool, bool);
5417 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005418 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5419 /*IsAssignmentOperator=*/false,
5420 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005421 break;
5422 }
5423
5424 case OO_Subscript:
5425 // C++ [over.built]p13:
5426 //
5427 // For every cv-qualified or cv-unqualified object type T there
5428 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005429 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005430 // T* operator+(T*, ptrdiff_t); [ABOVE]
5431 // T& operator[](T*, ptrdiff_t);
5432 // T* operator-(T*, ptrdiff_t); [ABOVE]
5433 // T* operator+(ptrdiff_t, T*); [ABOVE]
5434 // T& operator[](ptrdiff_t, T*);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005435 for (BuiltinCandidateTypeSet::iterator
5436 Ptr = CandidateTypes[0].pointer_begin(),
5437 PtrEnd = CandidateTypes[0].pointer_end();
5438 Ptr != PtrEnd; ++Ptr) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005439 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005440 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005441 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005442
5443 // T& operator[](T*, ptrdiff_t)
5444 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005445 }
5446
5447 for (BuiltinCandidateTypeSet::iterator
5448 Ptr = CandidateTypes[1].pointer_begin(),
5449 PtrEnd = CandidateTypes[1].pointer_end();
5450 Ptr != PtrEnd; ++Ptr) {
5451 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5452 QualType PointeeType = (*Ptr)->getPointeeType();
5453 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5454
5455 // T& operator[](ptrdiff_t, T*)
Douglas Gregora11693b2008-11-12 17:17:38 +00005456 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005457 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005458 break;
5459
5460 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005461 // C++ [over.built]p11:
5462 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5463 // C1 is the same type as C2 or is a derived class of C2, T is an object
5464 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5465 // there exist candidate operator functions of the form
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005466 //
5467 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5468 //
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005469 // where CV12 is the union of CV1 and CV2.
5470 {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005471 for (BuiltinCandidateTypeSet::iterator
5472 Ptr = CandidateTypes[0].pointer_begin(),
5473 PtrEnd = CandidateTypes[0].pointer_end();
5474 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005475 QualType C1Ty = (*Ptr);
5476 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005477 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005478 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5479 if (!isa<RecordType>(C1))
5480 continue;
5481 // heuristic to reduce number of builtin candidates in the set.
5482 // Add volatile/restrict version only if there are conversions to a
5483 // volatile/restrict type.
5484 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5485 continue;
5486 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5487 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005488 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005489 MemPtr = CandidateTypes[1].member_pointer_begin(),
5490 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005491 MemPtr != MemPtrEnd; ++MemPtr) {
5492 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5493 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005494 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005495 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5496 break;
5497 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5498 // build CV12 T&
5499 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005500 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5501 T.isVolatileQualified())
5502 continue;
5503 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5504 T.isRestrictQualified())
5505 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005506 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005507 QualType ResultTy = Context.getLValueReferenceType(T);
5508 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5509 }
5510 }
5511 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005512 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513
5514 case OO_Conditional:
5515 // Note that we don't consider the first argument, since it has been
5516 // contextually converted to bool long ago. The candidates below are
5517 // therefore added as binary.
5518 //
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005519 // C++ [over.built]p25:
5520 // For every type T, where T is a pointer, pointer-to-member, or scoped
5521 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl1a99f442009-04-16 17:51:27 +00005522 //
5523 // T operator?(bool, T, T);
5524 //
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005525 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5526 for (BuiltinCandidateTypeSet::iterator
5527 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5528 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5529 Ptr != PtrEnd; ++Ptr) {
5530 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5531 continue;
5532
5533 QualType ParamTypes[2] = { *Ptr, *Ptr };
5534 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5535 }
5536
5537 for (BuiltinCandidateTypeSet::iterator
5538 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5539 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5540 MemPtr != MemPtrEnd; ++MemPtr) {
5541 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5542 continue;
5543
5544 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5545 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5546 }
5547
5548 if (getLangOptions().CPlusPlus0x) {
5549 for (BuiltinCandidateTypeSet::iterator
5550 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5551 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5552 Enum != EnumEnd; ++Enum) {
5553 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5554 continue;
5555
5556 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5557 continue;
5558
5559 QualType ParamTypes[2] = { *Enum, *Enum };
5560 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5561 }
5562 }
Douglas Gregor8a8e0312010-10-15 00:50:56 +00005563 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005564 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005565 }
5566}
5567
Douglas Gregore254f902009-02-04 00:32:51 +00005568/// \brief Add function candidates found via argument-dependent lookup
5569/// to the set of overloading candidates.
5570///
5571/// This routine performs argument-dependent name lookup based on the
5572/// given function name (which may also be an operator name) and adds
5573/// all of the overload candidates found by ADL to the overload
5574/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005575void
Douglas Gregore254f902009-02-04 00:32:51 +00005576Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005577 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005578 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005579 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005580 OverloadCandidateSet& CandidateSet,
5581 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005582 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005583
John McCall91f61fc2010-01-26 06:04:06 +00005584 // FIXME: This approach for uniquing ADL results (and removing
5585 // redundant candidates from the set) relies on pointer-equality,
5586 // which means we need to key off the canonical decl. However,
5587 // always going back to the canonical decl might not get us the
5588 // right set of default arguments. What default arguments are
5589 // we supposed to consider on ADL candidates, anyway?
5590
Douglas Gregorcabea402009-09-22 15:41:20 +00005591 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005592 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005593
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005594 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005595 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5596 CandEnd = CandidateSet.end();
5597 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005598 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005599 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005600 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005601 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005602 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005603
5604 // For each of the ADL candidates we found, add it to the overload
5605 // set.
John McCall8fe68082010-01-26 07:16:45 +00005606 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005607 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005608 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005609 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005610 continue;
5611
John McCalla0296f72010-03-19 07:35:19 +00005612 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005613 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005614 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005615 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005616 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005617 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005618 }
Douglas Gregore254f902009-02-04 00:32:51 +00005619}
5620
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005621/// isBetterOverloadCandidate - Determines whether the first overload
5622/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005623bool
John McCall5c32be02010-08-24 20:38:10 +00005624isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005625 const OverloadCandidate &Cand1,
5626 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005627 SourceLocation Loc,
5628 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005629 // Define viable functions to be better candidates than non-viable
5630 // functions.
5631 if (!Cand2.Viable)
5632 return Cand1.Viable;
5633 else if (!Cand1.Viable)
5634 return false;
5635
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005636 // C++ [over.match.best]p1:
5637 //
5638 // -- if F is a static member function, ICS1(F) is defined such
5639 // that ICS1(F) is neither better nor worse than ICS1(G) for
5640 // any function G, and, symmetrically, ICS1(G) is neither
5641 // better nor worse than ICS1(F).
5642 unsigned StartArg = 0;
5643 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5644 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005645
Douglas Gregord3cb3562009-07-07 23:38:56 +00005646 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005647 // A viable function F1 is defined to be a better function than another
5648 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005649 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005650 unsigned NumArgs = Cand1.Conversions.size();
5651 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5652 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005653 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005654 switch (CompareImplicitConversionSequences(S,
5655 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005656 Cand2.Conversions[ArgIdx])) {
5657 case ImplicitConversionSequence::Better:
5658 // Cand1 has a better conversion sequence.
5659 HasBetterConversion = true;
5660 break;
5661
5662 case ImplicitConversionSequence::Worse:
5663 // Cand1 can't be better than Cand2.
5664 return false;
5665
5666 case ImplicitConversionSequence::Indistinguishable:
5667 // Do nothing.
5668 break;
5669 }
5670 }
5671
Mike Stump11289f42009-09-09 15:08:12 +00005672 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005673 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005674 if (HasBetterConversion)
5675 return true;
5676
Mike Stump11289f42009-09-09 15:08:12 +00005677 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005678 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005679 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005680 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5681 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005682
5683 // -- F1 and F2 are function template specializations, and the function
5684 // template for F1 is more specialized than the template for F2
5685 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005686 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005687 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5688 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005689 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005690 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5691 Cand2.Function->getPrimaryTemplate(),
5692 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005693 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5694 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005695 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005696
Douglas Gregora1f013e2008-11-07 22:36:19 +00005697 // -- the context is an initialization by user-defined conversion
5698 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5699 // from the return type of F1 to the destination type (i.e.,
5700 // the type of the entity being initialized) is a better
5701 // conversion sequence than the standard conversion sequence
5702 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005703 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005704 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005705 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005706 switch (CompareStandardConversionSequences(S,
5707 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005708 Cand2.FinalConversion)) {
5709 case ImplicitConversionSequence::Better:
5710 // Cand1 has a better conversion sequence.
5711 return true;
5712
5713 case ImplicitConversionSequence::Worse:
5714 // Cand1 can't be better than Cand2.
5715 return false;
5716
5717 case ImplicitConversionSequence::Indistinguishable:
5718 // Do nothing
5719 break;
5720 }
5721 }
5722
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005723 return false;
5724}
5725
Mike Stump11289f42009-09-09 15:08:12 +00005726/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005727/// within an overload candidate set.
5728///
5729/// \param CandidateSet the set of candidate functions.
5730///
5731/// \param Loc the location of the function name (or operator symbol) for
5732/// which overload resolution occurs.
5733///
Mike Stump11289f42009-09-09 15:08:12 +00005734/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005735/// function, Best points to the candidate function found.
5736///
5737/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005738OverloadingResult
5739OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005740 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005741 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005742 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005743 Best = end();
5744 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5745 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005746 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5747 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005748 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005749 }
5750
5751 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005752 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005753 return OR_No_Viable_Function;
5754
5755 // Make sure that this function is better than every other viable
5756 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005757 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005758 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005759 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005760 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5761 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005762 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005763 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005764 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005765 }
Mike Stump11289f42009-09-09 15:08:12 +00005766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005767 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005768 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005769 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005770 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005771 return OR_Deleted;
5772
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005773 // C++ [basic.def.odr]p2:
5774 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005775 // when referred to from a potentially-evaluated expression. [Note: this
5776 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005777 // (clause 13), user-defined conversions (12.3.2), allocation function for
5778 // placement new (5.3.4), as well as non-default initialization (8.5).
5779 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005780 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00005781
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005782 return OR_Success;
5783}
5784
John McCall53262c92010-01-12 02:15:36 +00005785namespace {
5786
5787enum OverloadCandidateKind {
5788 oc_function,
5789 oc_method,
5790 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005791 oc_function_template,
5792 oc_method_template,
5793 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005794 oc_implicit_default_constructor,
5795 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005796 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005797};
5798
John McCalle1ac8d12010-01-13 00:25:19 +00005799OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5800 FunctionDecl *Fn,
5801 std::string &Description) {
5802 bool isTemplate = false;
5803
5804 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5805 isTemplate = true;
5806 Description = S.getTemplateArgumentBindingsText(
5807 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5808 }
John McCallfd0b2f82010-01-06 09:43:14 +00005809
5810 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005811 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005812 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005813
John McCall53262c92010-01-12 02:15:36 +00005814 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5815 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005816 }
5817
5818 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5819 // This actually gets spelled 'candidate function' for now, but
5820 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005821 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005822 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005823
Douglas Gregorec3bec02010-09-27 22:37:28 +00005824 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005825 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005826 return oc_implicit_copy_assignment;
5827 }
5828
John McCalle1ac8d12010-01-13 00:25:19 +00005829 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005830}
5831
5832} // end anonymous namespace
5833
5834// Notes the location of an overload candidate.
5835void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005836 std::string FnDesc;
5837 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5838 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5839 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005840}
5841
John McCall0d1da222010-01-12 00:44:57 +00005842/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5843/// "lead" diagnostic; it will be given two arguments, the source and
5844/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005845void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5846 Sema &S,
5847 SourceLocation CaretLoc,
5848 const PartialDiagnostic &PDiag) const {
5849 S.Diag(CaretLoc, PDiag)
5850 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005851 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005852 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5853 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005854 }
John McCall12f97bc2010-01-08 04:41:39 +00005855}
5856
John McCall0d1da222010-01-12 00:44:57 +00005857namespace {
5858
John McCall6a61b522010-01-13 09:16:55 +00005859void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5860 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5861 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005862 assert(Cand->Function && "for now, candidate must be a function");
5863 FunctionDecl *Fn = Cand->Function;
5864
5865 // There's a conversion slot for the object argument if this is a
5866 // non-constructor method. Note that 'I' corresponds the
5867 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005868 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005869 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005870 if (I == 0)
5871 isObjectArgument = true;
5872 else
5873 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005874 }
5875
John McCalle1ac8d12010-01-13 00:25:19 +00005876 std::string FnDesc;
5877 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5878
John McCall6a61b522010-01-13 09:16:55 +00005879 Expr *FromExpr = Conv.Bad.FromExpr;
5880 QualType FromTy = Conv.Bad.getFromType();
5881 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005882
John McCallfb7ad0f2010-02-02 02:42:52 +00005883 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005884 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005885 Expr *E = FromExpr->IgnoreParens();
5886 if (isa<UnaryOperator>(E))
5887 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005888 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005889
5890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5891 << (unsigned) FnKind << FnDesc
5892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5893 << ToTy << Name << I+1;
5894 return;
5895 }
5896
John McCall6d174642010-01-23 08:10:49 +00005897 // Do some hand-waving analysis to see if the non-viability is due
5898 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005899 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5900 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5901 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5902 CToTy = RT->getPointeeType();
5903 else {
5904 // TODO: detect and diagnose the full richness of const mismatches.
5905 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5906 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5907 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5908 }
5909
5910 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5911 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5912 // It is dumb that we have to do this here.
5913 while (isa<ArrayType>(CFromTy))
5914 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5915 while (isa<ArrayType>(CToTy))
5916 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5917
5918 Qualifiers FromQs = CFromTy.getQualifiers();
5919 Qualifiers ToQs = CToTy.getQualifiers();
5920
5921 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5922 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5923 << (unsigned) FnKind << FnDesc
5924 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5925 << FromTy
5926 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5927 << (unsigned) isObjectArgument << I+1;
5928 return;
5929 }
5930
5931 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5932 assert(CVR && "unexpected qualifiers mismatch");
5933
5934 if (isObjectArgument) {
5935 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5936 << (unsigned) FnKind << FnDesc
5937 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5938 << FromTy << (CVR - 1);
5939 } else {
5940 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5941 << (unsigned) FnKind << FnDesc
5942 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5943 << FromTy << (CVR - 1) << I+1;
5944 }
5945 return;
5946 }
5947
John McCall6d174642010-01-23 08:10:49 +00005948 // Diagnose references or pointers to incomplete types differently,
5949 // since it's far from impossible that the incompleteness triggered
5950 // the failure.
5951 QualType TempFromTy = FromTy.getNonReferenceType();
5952 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5953 TempFromTy = PTy->getPointeeType();
5954 if (TempFromTy->isIncompleteType()) {
5955 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5956 << (unsigned) FnKind << FnDesc
5957 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5958 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5959 return;
5960 }
5961
Douglas Gregor56f2e342010-06-30 23:01:39 +00005962 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005963 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005964 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5965 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5966 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5967 FromPtrTy->getPointeeType()) &&
5968 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5969 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5970 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5971 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005972 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005973 }
5974 } else if (const ObjCObjectPointerType *FromPtrTy
5975 = FromTy->getAs<ObjCObjectPointerType>()) {
5976 if (const ObjCObjectPointerType *ToPtrTy
5977 = ToTy->getAs<ObjCObjectPointerType>())
5978 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5979 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5980 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5981 FromPtrTy->getPointeeType()) &&
5982 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005983 BaseToDerivedConversion = 2;
5984 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5985 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5986 !FromTy->isIncompleteType() &&
5987 !ToRefTy->getPointeeType()->isIncompleteType() &&
5988 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5989 BaseToDerivedConversion = 3;
5990 }
5991
5992 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005993 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005994 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005995 << (unsigned) FnKind << FnDesc
5996 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005997 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005998 << FromTy << ToTy << I+1;
5999 return;
6000 }
6001
John McCall47000992010-01-14 03:28:57 +00006002 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006003 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6004 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006005 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006006 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006007}
6008
6009void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6010 unsigned NumFormalArgs) {
6011 // TODO: treat calls to a missing default constructor as a special case
6012
6013 FunctionDecl *Fn = Cand->Function;
6014 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6015
6016 unsigned MinParams = Fn->getMinRequiredArguments();
6017
6018 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00006019 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00006020 unsigned mode, modeCount;
6021 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006022 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6023 (Cand->FailureKind == ovl_fail_bad_deduction &&
6024 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00006025 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6026 mode = 0; // "at least"
6027 else
6028 mode = 2; // "exactly"
6029 modeCount = MinParams;
6030 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006031 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6032 (Cand->FailureKind == ovl_fail_bad_deduction &&
6033 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006034 if (MinParams != FnTy->getNumArgs())
6035 mode = 1; // "at most"
6036 else
6037 mode = 2; // "exactly"
6038 modeCount = FnTy->getNumArgs();
6039 }
6040
6041 std::string Description;
6042 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6043
6044 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006045 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6046 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006047}
6048
John McCall8b9ed552010-02-01 18:53:26 +00006049/// Diagnose a failed template-argument deduction.
6050void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6051 Expr **Args, unsigned NumArgs) {
6052 FunctionDecl *Fn = Cand->Function; // pattern
6053
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006054 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006055 NamedDecl *ParamD;
6056 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6057 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6058 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006059 switch (Cand->DeductionFailure.Result) {
6060 case Sema::TDK_Success:
6061 llvm_unreachable("TDK_success while diagnosing bad deduction");
6062
6063 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006064 assert(ParamD && "no parameter found for incomplete deduction result");
6065 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6066 << ParamD->getDeclName();
6067 return;
6068 }
6069
John McCall42d7d192010-08-05 09:05:08 +00006070 case Sema::TDK_Underqualified: {
6071 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6072 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6073
6074 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6075
6076 // Param will have been canonicalized, but it should just be a
6077 // qualified version of ParamD, so move the qualifiers to that.
6078 QualifierCollector Qs(S.Context);
6079 Qs.strip(Param);
6080 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6081 assert(S.Context.hasSameType(Param, NonCanonParam));
6082
6083 // Arg has also been canonicalized, but there's nothing we can do
6084 // about that. It also doesn't matter as much, because it won't
6085 // have any template parameters in it (because deduction isn't
6086 // done on dependent types).
6087 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6088
6089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6090 << ParamD->getDeclName() << Arg << NonCanonParam;
6091 return;
6092 }
6093
6094 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006095 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006096 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006097 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006098 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006099 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006100 which = 1;
6101 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006102 which = 2;
6103 }
6104
6105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6106 << which << ParamD->getDeclName()
6107 << *Cand->DeductionFailure.getFirstArg()
6108 << *Cand->DeductionFailure.getSecondArg();
6109 return;
6110 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006111
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006112 case Sema::TDK_InvalidExplicitArguments:
6113 assert(ParamD && "no parameter found for invalid explicit arguments");
6114 if (ParamD->getDeclName())
6115 S.Diag(Fn->getLocation(),
6116 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6117 << ParamD->getDeclName();
6118 else {
6119 int index = 0;
6120 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6121 index = TTP->getIndex();
6122 else if (NonTypeTemplateParmDecl *NTTP
6123 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6124 index = NTTP->getIndex();
6125 else
6126 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6127 S.Diag(Fn->getLocation(),
6128 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6129 << (index + 1);
6130 }
6131 return;
6132
Douglas Gregor02eb4832010-05-08 18:13:28 +00006133 case Sema::TDK_TooManyArguments:
6134 case Sema::TDK_TooFewArguments:
6135 DiagnoseArityMismatch(S, Cand, NumArgs);
6136 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006137
6138 case Sema::TDK_InstantiationDepth:
6139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6140 return;
6141
6142 case Sema::TDK_SubstitutionFailure: {
6143 std::string ArgString;
6144 if (TemplateArgumentList *Args
6145 = Cand->DeductionFailure.getTemplateArgumentList())
6146 ArgString = S.getTemplateArgumentBindingsText(
6147 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6148 *Args);
6149 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6150 << ArgString;
6151 return;
6152 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006153
John McCall8b9ed552010-02-01 18:53:26 +00006154 // TODO: diagnose these individually, then kill off
6155 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006156 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006157 case Sema::TDK_FailedOverloadResolution:
6158 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6159 return;
6160 }
6161}
6162
6163/// Generates a 'note' diagnostic for an overload candidate. We've
6164/// already generated a primary error at the call site.
6165///
6166/// It really does need to be a single diagnostic with its caret
6167/// pointed at the candidate declaration. Yes, this creates some
6168/// major challenges of technical writing. Yes, this makes pointing
6169/// out problems with specific arguments quite awkward. It's still
6170/// better than generating twenty screens of text for every failed
6171/// overload.
6172///
6173/// It would be great to be able to express per-candidate problems
6174/// more richly for those diagnostic clients that cared, but we'd
6175/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006176void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6177 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006178 FunctionDecl *Fn = Cand->Function;
6179
John McCall12f97bc2010-01-08 04:41:39 +00006180 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006181 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006182 std::string FnDesc;
6183 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006184
6185 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006186 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006187 return;
John McCall12f97bc2010-01-08 04:41:39 +00006188 }
6189
John McCalle1ac8d12010-01-13 00:25:19 +00006190 // We don't really have anything else to say about viable candidates.
6191 if (Cand->Viable) {
6192 S.NoteOverloadCandidate(Fn);
6193 return;
6194 }
John McCall0d1da222010-01-12 00:44:57 +00006195
John McCall6a61b522010-01-13 09:16:55 +00006196 switch (Cand->FailureKind) {
6197 case ovl_fail_too_many_arguments:
6198 case ovl_fail_too_few_arguments:
6199 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006200
John McCall6a61b522010-01-13 09:16:55 +00006201 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006202 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6203
John McCallfe796dd2010-01-23 05:17:32 +00006204 case ovl_fail_trivial_conversion:
6205 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006206 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006207 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006208
John McCall65eb8792010-02-25 01:37:24 +00006209 case ovl_fail_bad_conversion: {
6210 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6211 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006212 if (Cand->Conversions[I].isBad())
6213 return DiagnoseBadConversion(S, Cand, I);
6214
6215 // FIXME: this currently happens when we're called from SemaInit
6216 // when user-conversion overload fails. Figure out how to handle
6217 // those conditions and diagnose them well.
6218 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006219 }
John McCall65eb8792010-02-25 01:37:24 +00006220 }
John McCalld3224162010-01-08 00:58:21 +00006221}
6222
6223void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6224 // Desugar the type of the surrogate down to a function type,
6225 // retaining as many typedefs as possible while still showing
6226 // the function type (and, therefore, its parameter types).
6227 QualType FnType = Cand->Surrogate->getConversionType();
6228 bool isLValueReference = false;
6229 bool isRValueReference = false;
6230 bool isPointer = false;
6231 if (const LValueReferenceType *FnTypeRef =
6232 FnType->getAs<LValueReferenceType>()) {
6233 FnType = FnTypeRef->getPointeeType();
6234 isLValueReference = true;
6235 } else if (const RValueReferenceType *FnTypeRef =
6236 FnType->getAs<RValueReferenceType>()) {
6237 FnType = FnTypeRef->getPointeeType();
6238 isRValueReference = true;
6239 }
6240 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6241 FnType = FnTypePtr->getPointeeType();
6242 isPointer = true;
6243 }
6244 // Desugar down to a function type.
6245 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6246 // Reconstruct the pointer/reference as appropriate.
6247 if (isPointer) FnType = S.Context.getPointerType(FnType);
6248 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6249 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6250
6251 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6252 << FnType;
6253}
6254
6255void NoteBuiltinOperatorCandidate(Sema &S,
6256 const char *Opc,
6257 SourceLocation OpLoc,
6258 OverloadCandidate *Cand) {
6259 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6260 std::string TypeStr("operator");
6261 TypeStr += Opc;
6262 TypeStr += "(";
6263 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6264 if (Cand->Conversions.size() == 1) {
6265 TypeStr += ")";
6266 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6267 } else {
6268 TypeStr += ", ";
6269 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6270 TypeStr += ")";
6271 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6272 }
6273}
6274
6275void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6276 OverloadCandidate *Cand) {
6277 unsigned NoOperands = Cand->Conversions.size();
6278 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6279 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006280 if (ICS.isBad()) break; // all meaningless after first invalid
6281 if (!ICS.isAmbiguous()) continue;
6282
John McCall5c32be02010-08-24 20:38:10 +00006283 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006284 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006285 }
6286}
6287
John McCall3712d9e2010-01-15 23:32:50 +00006288SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6289 if (Cand->Function)
6290 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006291 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006292 return Cand->Surrogate->getLocation();
6293 return SourceLocation();
6294}
6295
John McCallad2587a2010-01-12 00:48:53 +00006296struct CompareOverloadCandidatesForDisplay {
6297 Sema &S;
6298 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006299
6300 bool operator()(const OverloadCandidate *L,
6301 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006302 // Fast-path this check.
6303 if (L == R) return false;
6304
John McCall12f97bc2010-01-08 04:41:39 +00006305 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006306 if (L->Viable) {
6307 if (!R->Viable) return true;
6308
6309 // TODO: introduce a tri-valued comparison for overload
6310 // candidates. Would be more worthwhile if we had a sort
6311 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006312 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6313 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006314 } else if (R->Viable)
6315 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006316
John McCall3712d9e2010-01-15 23:32:50 +00006317 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006318
John McCall3712d9e2010-01-15 23:32:50 +00006319 // Criteria by which we can sort non-viable candidates:
6320 if (!L->Viable) {
6321 // 1. Arity mismatches come after other candidates.
6322 if (L->FailureKind == ovl_fail_too_many_arguments ||
6323 L->FailureKind == ovl_fail_too_few_arguments)
6324 return false;
6325 if (R->FailureKind == ovl_fail_too_many_arguments ||
6326 R->FailureKind == ovl_fail_too_few_arguments)
6327 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006328
John McCallfe796dd2010-01-23 05:17:32 +00006329 // 2. Bad conversions come first and are ordered by the number
6330 // of bad conversions and quality of good conversions.
6331 if (L->FailureKind == ovl_fail_bad_conversion) {
6332 if (R->FailureKind != ovl_fail_bad_conversion)
6333 return true;
6334
6335 // If there's any ordering between the defined conversions...
6336 // FIXME: this might not be transitive.
6337 assert(L->Conversions.size() == R->Conversions.size());
6338
6339 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006340 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6341 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006342 switch (CompareImplicitConversionSequences(S,
6343 L->Conversions[I],
6344 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006345 case ImplicitConversionSequence::Better:
6346 leftBetter++;
6347 break;
6348
6349 case ImplicitConversionSequence::Worse:
6350 leftBetter--;
6351 break;
6352
6353 case ImplicitConversionSequence::Indistinguishable:
6354 break;
6355 }
6356 }
6357 if (leftBetter > 0) return true;
6358 if (leftBetter < 0) return false;
6359
6360 } else if (R->FailureKind == ovl_fail_bad_conversion)
6361 return false;
6362
John McCall3712d9e2010-01-15 23:32:50 +00006363 // TODO: others?
6364 }
6365
6366 // Sort everything else by location.
6367 SourceLocation LLoc = GetLocationForCandidate(L);
6368 SourceLocation RLoc = GetLocationForCandidate(R);
6369
6370 // Put candidates without locations (e.g. builtins) at the end.
6371 if (LLoc.isInvalid()) return false;
6372 if (RLoc.isInvalid()) return true;
6373
6374 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006375 }
6376};
6377
John McCallfe796dd2010-01-23 05:17:32 +00006378/// CompleteNonViableCandidate - Normally, overload resolution only
6379/// computes up to the first
6380void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6381 Expr **Args, unsigned NumArgs) {
6382 assert(!Cand->Viable);
6383
6384 // Don't do anything on failures other than bad conversion.
6385 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6386
6387 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006388 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006389 unsigned ConvCount = Cand->Conversions.size();
6390 while (true) {
6391 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6392 ConvIdx++;
6393 if (Cand->Conversions[ConvIdx - 1].isBad())
6394 break;
6395 }
6396
6397 if (ConvIdx == ConvCount)
6398 return;
6399
John McCall65eb8792010-02-25 01:37:24 +00006400 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6401 "remaining conversion is initialized?");
6402
Douglas Gregoradc7a702010-04-16 17:45:54 +00006403 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006404 // operation somehow.
6405 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006406
6407 const FunctionProtoType* Proto;
6408 unsigned ArgIdx = ConvIdx;
6409
6410 if (Cand->IsSurrogate) {
6411 QualType ConvType
6412 = Cand->Surrogate->getConversionType().getNonReferenceType();
6413 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6414 ConvType = ConvPtrType->getPointeeType();
6415 Proto = ConvType->getAs<FunctionProtoType>();
6416 ArgIdx--;
6417 } else if (Cand->Function) {
6418 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6419 if (isa<CXXMethodDecl>(Cand->Function) &&
6420 !isa<CXXConstructorDecl>(Cand->Function))
6421 ArgIdx--;
6422 } else {
6423 // Builtin binary operator with a bad first conversion.
6424 assert(ConvCount <= 3);
6425 for (; ConvIdx != ConvCount; ++ConvIdx)
6426 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006427 = TryCopyInitialization(S, Args[ConvIdx],
6428 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6429 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006430 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006431 return;
6432 }
6433
6434 // Fill in the rest of the conversions.
6435 unsigned NumArgsInProto = Proto->getNumArgs();
6436 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6437 if (ArgIdx < NumArgsInProto)
6438 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006439 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6440 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006441 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006442 else
6443 Cand->Conversions[ConvIdx].setEllipsis();
6444 }
6445}
6446
John McCalld3224162010-01-08 00:58:21 +00006447} // end anonymous namespace
6448
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006449/// PrintOverloadCandidates - When overload resolution fails, prints
6450/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006451/// set.
John McCall5c32be02010-08-24 20:38:10 +00006452void OverloadCandidateSet::NoteCandidates(Sema &S,
6453 OverloadCandidateDisplayKind OCD,
6454 Expr **Args, unsigned NumArgs,
6455 const char *Opc,
6456 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006457 // Sort the candidates by viability and position. Sorting directly would
6458 // be prohibitive, so we make a set of pointers and sort those.
6459 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006460 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6461 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006462 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006463 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006464 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006465 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006466 if (Cand->Function || Cand->IsSurrogate)
6467 Cands.push_back(Cand);
6468 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6469 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006470 }
6471 }
6472
John McCallad2587a2010-01-12 00:48:53 +00006473 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006474 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006475
John McCall0d1da222010-01-12 00:44:57 +00006476 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006477
John McCall12f97bc2010-01-08 04:41:39 +00006478 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006479 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006480 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006481 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6482 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006483
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006484 // Set an arbitrary limit on the number of candidate functions we'll spam
6485 // the user with. FIXME: This limit should depend on details of the
6486 // candidate list.
6487 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6488 break;
6489 }
6490 ++CandsShown;
6491
John McCalld3224162010-01-08 00:58:21 +00006492 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006493 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006494 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006495 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006496 else {
6497 assert(Cand->Viable &&
6498 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006499 // Generally we only see ambiguities including viable builtin
6500 // operators if overload resolution got screwed up by an
6501 // ambiguous user-defined conversion.
6502 //
6503 // FIXME: It's quite possible for different conversions to see
6504 // different ambiguities, though.
6505 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006506 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006507 ReportedAmbiguousConversions = true;
6508 }
John McCalld3224162010-01-08 00:58:21 +00006509
John McCall0d1da222010-01-12 00:44:57 +00006510 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006511 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006512 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006513 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006514
6515 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006516 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006517}
6518
John McCalla0296f72010-03-19 07:35:19 +00006519static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006520 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006521 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006522
John McCalla0296f72010-03-19 07:35:19 +00006523 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006524}
6525
Douglas Gregorcd695e52008-11-10 20:40:00 +00006526/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6527/// an overloaded function (C++ [over.over]), where @p From is an
6528/// expression with overloaded function type and @p ToType is the type
6529/// we're trying to resolve to. For example:
6530///
6531/// @code
6532/// int f(double);
6533/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006534///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006535/// int (*pfd)(double) = f; // selects f(double)
6536/// @endcode
6537///
6538/// This routine returns the resulting FunctionDecl if it could be
6539/// resolved, and NULL otherwise. When @p Complain is true, this
6540/// routine will emit diagnostics if there is an error.
6541FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006542Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006543 bool Complain,
6544 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006545 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006546 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006547 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006548 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006549 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006550 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006551 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006552 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006553 FunctionType = MemTypePtr->getPointeeType();
6554 IsMember = true;
6555 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006556
Douglas Gregorcd695e52008-11-10 20:40:00 +00006557 // C++ [over.over]p1:
6558 // [...] [Note: any redundant set of parentheses surrounding the
6559 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006560 // C++ [over.over]p1:
6561 // [...] The overloaded function name can be preceded by the &
6562 // operator.
John McCall7d460512010-08-24 23:26:21 +00006563 // However, remember whether the expression has member-pointer form:
6564 // C++ [expr.unary.op]p4:
6565 // A pointer to member is only formed when an explicit & is used
6566 // and its operand is a qualified-id not enclosed in
6567 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006568 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6569 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006570
Douglas Gregor064fdb22010-04-14 23:11:21 +00006571 // We expect a pointer or reference to function, or a function pointer.
6572 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6573 if (!FunctionType->isFunctionType()) {
6574 if (Complain)
6575 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6576 << OvlExpr->getName() << ToType;
6577
6578 return 0;
6579 }
6580
John McCall24d18942010-08-24 22:52:39 +00006581 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006582 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006583 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006584 if (!Complain) return 0;
6585
6586 // TODO: Should we condition this on whether any functions might
6587 // have matched, or is it more appropriate to do that in callers?
6588 // TODO: a fixit wouldn't hurt.
6589 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6590 << ToType << OvlExpr->getSourceRange();
6591 return 0;
6592 }
6593
6594 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6595 if (OvlExpr->hasExplicitTemplateArgs()) {
6596 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6597 ExplicitTemplateArgs = &ETABuffer;
6598 }
6599
Douglas Gregor064fdb22010-04-14 23:11:21 +00006600 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006601
Douglas Gregorcd695e52008-11-10 20:40:00 +00006602 // Look through all of the overloaded functions, searching for one
6603 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006604 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006605 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006606
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006607 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006608 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6609 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006610 // Look through any using declarations to find the underlying function.
6611 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6612
Douglas Gregorcd695e52008-11-10 20:40:00 +00006613 // C++ [over.over]p3:
6614 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006615 // targets of type "pointer-to-function" or "reference-to-function."
6616 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006617 // type "pointer-to-member-function."
6618 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006619
Mike Stump11289f42009-09-09 15:08:12 +00006620 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006621 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006622 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006623 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006624 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006625 // static when converting to member pointer.
6626 if (Method->isStatic() == IsMember)
6627 continue;
6628 } else if (IsMember)
6629 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006630
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006631 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006632 // If the name is a function template, template argument deduction is
6633 // done (14.8.2.2), and if the argument deduction succeeds, the
6634 // resulting template argument list is used to generate a single
6635 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006636 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006637 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006638 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006639 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006640 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006641 FunctionType, Specialization, Info)) {
6642 // FIXME: make a note of the failed deduction for diagnostics.
6643 (void)Result;
6644 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006645 // Template argument deduction ensures that we have an exact match.
6646 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006647 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006648 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006649 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006650 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006651 }
John McCalld14a8642009-11-21 08:51:07 +00006652
6653 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006657 // Skip non-static functions when converting to pointer, and static
6658 // when converting to member pointer.
6659 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006660 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006661
6662 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006663 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006664 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006665 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006666 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006667
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006668 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006669 QualType ResultTy;
6670 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6671 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6672 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006673 Matches.push_back(std::make_pair(I.getPair(),
6674 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006675 FoundNonTemplateFunction = true;
6676 }
Mike Stump11289f42009-09-09 15:08:12 +00006677 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006678 }
6679
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006680 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006681 if (Matches.empty()) {
6682 if (Complain) {
6683 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6684 << OvlExpr->getName() << FunctionType;
6685 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6686 E = OvlExpr->decls_end();
6687 I != E; ++I)
6688 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6689 NoteOverloadCandidate(F);
6690 }
6691
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006692 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006693 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006694 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006695 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006696 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006697 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006698 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006699 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006700 return Result;
6701 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006702
6703 // C++ [over.over]p4:
6704 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006705 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006706 // [...] and any given function template specialization F1 is
6707 // eliminated if the set contains a second function template
6708 // specialization whose function template is more specialized
6709 // than the function template of F1 according to the partial
6710 // ordering rules of 14.5.5.2.
6711
6712 // The algorithm specified above is quadratic. We instead use a
6713 // two-pass algorithm (similar to the one used to identify the
6714 // best viable function in an overload set) that identifies the
6715 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006716
6717 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6718 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6719 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006720
6721 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006722 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006723 TPOC_Other, From->getLocStart(),
6724 PDiag(),
6725 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006726 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006727 PDiag(diag::note_ovl_candidate)
6728 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006729 if (Result == MatchesCopy.end())
6730 return 0;
6731
John McCall58cc69d2010-01-27 01:50:18 +00006732 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006733 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006734 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006735 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006736 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006737 }
Mike Stump11289f42009-09-09 15:08:12 +00006738
Douglas Gregorfae1d712009-09-26 03:56:17 +00006739 // [...] any function template specializations in the set are
6740 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006741 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006742 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006743 ++I;
6744 else {
John McCalla0296f72010-03-19 07:35:19 +00006745 Matches[I] = Matches[--N];
6746 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006747 }
6748 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006749
Mike Stump11289f42009-09-09 15:08:12 +00006750 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006751 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006752 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006753 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006754 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006755 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006756 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6757 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006758 }
Mike Stump11289f42009-09-09 15:08:12 +00006759
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006760 // FIXME: We should probably return the same thing that BestViableFunction
6761 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006762 if (Complain) {
6763 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6764 << Matches[0].second->getDeclName();
6765 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6766 NoteOverloadCandidate(Matches[I].second);
6767 }
6768
Douglas Gregorcd695e52008-11-10 20:40:00 +00006769 return 0;
6770}
6771
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006772/// \brief Given an expression that refers to an overloaded function, try to
6773/// resolve that overloaded function expression down to a single function.
6774///
6775/// This routine can only resolve template-ids that refer to a single function
6776/// template, where that template-id refers to a single template whose template
6777/// arguments are either provided by the template-id or have defaults,
6778/// as described in C++0x [temp.arg.explicit]p3.
6779FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6780 // C++ [over.over]p1:
6781 // [...] [Note: any redundant set of parentheses surrounding the
6782 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006783 // C++ [over.over]p1:
6784 // [...] The overloaded function name can be preceded by the &
6785 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006786
6787 if (From->getType() != Context.OverloadTy)
6788 return 0;
6789
John McCall8d08b9b2010-08-27 09:08:28 +00006790 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006791
6792 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006793 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006794 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006795
6796 TemplateArgumentListInfo ExplicitTemplateArgs;
6797 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006798
6799 // Look through all of the overloaded functions, searching for one
6800 // whose type matches exactly.
6801 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006802 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6803 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006804 // C++0x [temp.arg.explicit]p3:
6805 // [...] In contexts where deduction is done and fails, or in contexts
6806 // where deduction is not done, if a template argument list is
6807 // specified and it, along with any default template arguments,
6808 // identifies a single function template specialization, then the
6809 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006810 FunctionTemplateDecl *FunctionTemplate
6811 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006812
6813 // C++ [over.over]p2:
6814 // If the name is a function template, template argument deduction is
6815 // done (14.8.2.2), and if the argument deduction succeeds, the
6816 // resulting template argument list is used to generate a single
6817 // function template specialization, which is added to the set of
6818 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006819 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006820 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006821 if (TemplateDeductionResult Result
6822 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6823 Specialization, Info)) {
6824 // FIXME: make a note of the failed deduction for diagnostics.
6825 (void)Result;
6826 continue;
6827 }
6828
6829 // Multiple matches; we can't resolve to a single declaration.
6830 if (Matched)
6831 return 0;
6832
6833 Matched = Specialization;
6834 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006835
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006836 return Matched;
6837}
6838
Douglas Gregorcabea402009-09-22 15:41:20 +00006839/// \brief Add a single candidate to the overload set.
6840static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006841 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006842 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006843 Expr **Args, unsigned NumArgs,
6844 OverloadCandidateSet &CandidateSet,
6845 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006846 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006847 if (isa<UsingShadowDecl>(Callee))
6848 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6849
Douglas Gregorcabea402009-09-22 15:41:20 +00006850 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006851 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006852 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006853 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006854 return;
John McCalld14a8642009-11-21 08:51:07 +00006855 }
6856
6857 if (FunctionTemplateDecl *FuncTemplate
6858 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006859 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6860 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006861 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006862 return;
6863 }
6864
6865 assert(false && "unhandled case in overloaded call candidate");
6866
6867 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006868}
6869
6870/// \brief Add the overload candidates named by callee and/or found by argument
6871/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006872void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006873 Expr **Args, unsigned NumArgs,
6874 OverloadCandidateSet &CandidateSet,
6875 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006876
6877#ifndef NDEBUG
6878 // Verify that ArgumentDependentLookup is consistent with the rules
6879 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006880 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006881 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6882 // and let Y be the lookup set produced by argument dependent
6883 // lookup (defined as follows). If X contains
6884 //
6885 // -- a declaration of a class member, or
6886 //
6887 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006888 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006889 //
6890 // -- a declaration that is neither a function or a function
6891 // template
6892 //
6893 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006894
John McCall57500772009-12-16 12:17:52 +00006895 if (ULE->requiresADL()) {
6896 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6897 E = ULE->decls_end(); I != E; ++I) {
6898 assert(!(*I)->getDeclContext()->isRecord());
6899 assert(isa<UsingShadowDecl>(*I) ||
6900 !(*I)->getDeclContext()->isFunctionOrMethod());
6901 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006902 }
6903 }
6904#endif
6905
John McCall57500772009-12-16 12:17:52 +00006906 // It would be nice to avoid this copy.
6907 TemplateArgumentListInfo TABuffer;
6908 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6909 if (ULE->hasExplicitTemplateArgs()) {
6910 ULE->copyTemplateArgumentsInto(TABuffer);
6911 ExplicitTemplateArgs = &TABuffer;
6912 }
6913
6914 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6915 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006916 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006917 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006918 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006919
John McCall57500772009-12-16 12:17:52 +00006920 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006921 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6922 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006923 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006924 CandidateSet,
6925 PartialOverloading);
6926}
John McCalld681c392009-12-16 08:11:27 +00006927
6928/// Attempts to recover from a call where no functions were found.
6929///
6930/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006931static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006932BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006933 UnresolvedLookupExpr *ULE,
6934 SourceLocation LParenLoc,
6935 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006936 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006937
6938 CXXScopeSpec SS;
6939 if (ULE->getQualifier()) {
6940 SS.setScopeRep(ULE->getQualifier());
6941 SS.setRange(ULE->getQualifierRange());
6942 }
6943
John McCall57500772009-12-16 12:17:52 +00006944 TemplateArgumentListInfo TABuffer;
6945 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6946 if (ULE->hasExplicitTemplateArgs()) {
6947 ULE->copyTemplateArgumentsInto(TABuffer);
6948 ExplicitTemplateArgs = &TABuffer;
6949 }
6950
John McCalld681c392009-12-16 08:11:27 +00006951 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6952 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006953 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006954 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006955
John McCall57500772009-12-16 12:17:52 +00006956 assert(!R.empty() && "lookup results empty despite recovery");
6957
6958 // Build an implicit member call if appropriate. Just drop the
6959 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006960 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006961 if ((*R.begin())->isCXXClassMember())
6962 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6963 else if (ExplicitTemplateArgs)
6964 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6965 else
6966 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6967
6968 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006969 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006970
6971 // This shouldn't cause an infinite loop because we're giving it
6972 // an expression with non-empty lookup results, which should never
6973 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006974 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006975 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006976}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006977
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006978/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006979/// (which eventually refers to the declaration Func) and the call
6980/// arguments Args/NumArgs, attempt to resolve the function call down
6981/// to a specific function. If overload resolution succeeds, returns
6982/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006983/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006984/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006985ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006986Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006987 SourceLocation LParenLoc,
6988 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006989 SourceLocation RParenLoc) {
6990#ifndef NDEBUG
6991 if (ULE->requiresADL()) {
6992 // To do ADL, we must have found an unqualified name.
6993 assert(!ULE->getQualifier() && "qualified name with ADL");
6994
6995 // We don't perform ADL for implicit declarations of builtins.
6996 // Verify that this was correctly set up.
6997 FunctionDecl *F;
6998 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6999 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7000 F->getBuiltinID() && F->isImplicit())
7001 assert(0 && "performing ADL for builtin");
7002
7003 // We don't perform ADL in C.
7004 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7005 }
7006#endif
7007
John McCallbc077cf2010-02-08 23:07:23 +00007008 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007009
John McCall57500772009-12-16 12:17:52 +00007010 // Add the functions denoted by the callee to the set of candidate
7011 // functions, including those from argument-dependent lookup.
7012 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007013
7014 // If we found nothing, try to recover.
7015 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7016 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007017 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007018 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007019 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007020
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007021 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007022 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007023 case OR_Success: {
7024 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007025 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor7731d3f2010-10-13 00:27:52 +00007026 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007027 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00007028 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
7029 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007030
7031 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007032 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007033 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007034 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007035 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007036 break;
7037
7038 case OR_Ambiguous:
7039 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007040 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007041 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007042 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007043
7044 case OR_Deleted:
7045 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7046 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007047 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007048 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007049 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007050 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007051 }
7052
Douglas Gregorb412e172010-07-25 18:17:45 +00007053 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007054 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007055}
7056
John McCall4c4c1df2010-01-26 03:27:55 +00007057static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007058 return Functions.size() > 1 ||
7059 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7060}
7061
Douglas Gregor084d8552009-03-13 23:49:33 +00007062/// \brief Create a unary operation that may resolve to an overloaded
7063/// operator.
7064///
7065/// \param OpLoc The location of the operator itself (e.g., '*').
7066///
7067/// \param OpcIn The UnaryOperator::Opcode that describes this
7068/// operator.
7069///
7070/// \param Functions The set of non-member functions that will be
7071/// considered by overload resolution. The caller needs to build this
7072/// set based on the context using, e.g.,
7073/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7074/// set should not contain any member functions; those will be added
7075/// by CreateOverloadedUnaryOp().
7076///
7077/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007078ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007079Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7080 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007081 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007082 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007083
7084 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7085 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7086 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007087 // TODO: provide better source location info.
7088 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007089
John McCalle26a8722010-12-04 08:14:53 +00007090 if (Input->getObjectKind() == OK_ObjCProperty)
7091 ConvertPropertyForRValue(Input);
7092
Douglas Gregor084d8552009-03-13 23:49:33 +00007093 Expr *Args[2] = { Input, 0 };
7094 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007095
Douglas Gregor084d8552009-03-13 23:49:33 +00007096 // For post-increment and post-decrement, add the implicit '0' as
7097 // the second argument, so that we know this is a post-increment or
7098 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007099 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007100 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007101 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7102 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007103 NumArgs = 2;
7104 }
7105
7106 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007107 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007108 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007109 Opc,
7110 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007111 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007112 OpLoc));
7113
John McCall58cc69d2010-01-27 01:50:18 +00007114 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007115 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007116 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007117 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007118 /*ADL*/ true, IsOverloaded(Fns),
7119 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007120 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7121 &Args[0], NumArgs,
7122 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007123 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007124 OpLoc));
7125 }
7126
7127 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007128 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007129
7130 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007131 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007132
7133 // Add operator candidates that are member functions.
7134 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7135
John McCall4c4c1df2010-01-26 03:27:55 +00007136 // Add candidates from ADL.
7137 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007138 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007139 /*ExplicitTemplateArgs*/ 0,
7140 CandidateSet);
7141
Douglas Gregor084d8552009-03-13 23:49:33 +00007142 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007143 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007144
7145 // Perform overload resolution.
7146 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007147 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007148 case OR_Success: {
7149 // We found a built-in operator or an overloaded operator.
7150 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007151
Douglas Gregor084d8552009-03-13 23:49:33 +00007152 if (FnDecl) {
7153 // We matched an overloaded operator. Build a call to that
7154 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007155
Douglas Gregor084d8552009-03-13 23:49:33 +00007156 // Convert the arguments.
7157 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007158 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007159
John McCall16df1e52010-03-30 21:47:33 +00007160 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7161 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007162 return ExprError();
7163 } else {
7164 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007165 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007166 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007167 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007168 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007169 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007170 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007171 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007172 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007173 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007174 }
7175
John McCall4fa0d5f2010-05-06 18:15:07 +00007176 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7177
John McCall7decc9e2010-11-18 06:31:45 +00007178 // Determine the result type.
7179 QualType ResultTy = FnDecl->getResultType();
7180 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7181 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007182
Douglas Gregor084d8552009-03-13 23:49:33 +00007183 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007184 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007185
Eli Friedman030eee42009-11-18 03:58:17 +00007186 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007187 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007188 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007189 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007190
John McCallb268a282010-08-23 23:25:46 +00007191 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007192 FnDecl))
7193 return ExprError();
7194
John McCallb268a282010-08-23 23:25:46 +00007195 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007196 } else {
7197 // We matched a built-in operator. Convert the arguments, then
7198 // break out so that we will build the appropriate built-in
7199 // operator node.
7200 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007201 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007202 return ExprError();
7203
7204 break;
7205 }
7206 }
7207
7208 case OR_No_Viable_Function:
7209 // No viable function; fall through to handling this as a
7210 // built-in operator, which will produce an error message for us.
7211 break;
7212
7213 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007214 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007215 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007216 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007217 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007218 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7219 Args, NumArgs,
7220 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007221 return ExprError();
7222
7223 case OR_Deleted:
7224 Diag(OpLoc, diag::err_ovl_deleted_oper)
7225 << Best->Function->isDeleted()
7226 << UnaryOperator::getOpcodeStr(Opc)
7227 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007228 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007229 return ExprError();
7230 }
7231
7232 // Either we found no viable overloaded operator or we matched a
7233 // built-in operator. In either case, fall through to trying to
7234 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007235 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007236}
7237
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007238/// \brief Create a binary operation that may resolve to an overloaded
7239/// operator.
7240///
7241/// \param OpLoc The location of the operator itself (e.g., '+').
7242///
7243/// \param OpcIn The BinaryOperator::Opcode that describes this
7244/// operator.
7245///
7246/// \param Functions The set of non-member functions that will be
7247/// considered by overload resolution. The caller needs to build this
7248/// set based on the context using, e.g.,
7249/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7250/// set should not contain any member functions; those will be added
7251/// by CreateOverloadedBinOp().
7252///
7253/// \param LHS Left-hand argument.
7254/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007255ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007256Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007257 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007258 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007259 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007260 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007261 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007262
7263 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7264 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7265 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7266
7267 // If either side is type-dependent, create an appropriate dependent
7268 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007269 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007270 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007271 // If there are no functions to store, just build a dependent
7272 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007273 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007274 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007275 Context.DependentTy,
7276 VK_RValue, OK_Ordinary,
7277 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007278
7279 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7280 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007281 VK_LValue,
7282 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007283 Context.DependentTy,
7284 Context.DependentTy,
7285 OpLoc));
7286 }
John McCall4c4c1df2010-01-26 03:27:55 +00007287
7288 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007289 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007290 // TODO: provide better source location info in DNLoc component.
7291 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007292 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007293 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007294 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007295 /*ADL*/ true, IsOverloaded(Fns),
7296 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007297 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007298 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007299 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007300 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007301 OpLoc));
7302 }
7303
John McCalle26a8722010-12-04 08:14:53 +00007304 // Always do property rvalue conversions on the RHS.
7305 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7306 ConvertPropertyForRValue(Args[1]);
7307
7308 // The LHS is more complicated.
7309 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7310
7311 // There's a tension for assignment operators between primitive
7312 // property assignment and the overloaded operators.
7313 if (BinaryOperator::isAssignmentOp(Opc)) {
7314 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7315
7316 // Is the property "logically" settable?
7317 bool Settable = (PRE->isExplicitProperty() ||
7318 PRE->getImplicitPropertySetter());
7319
7320 // To avoid gratuitously inventing semantics, use the primitive
7321 // unless it isn't. Thoughts in case we ever really care:
7322 // - If the property isn't logically settable, we have to
7323 // load and hope.
7324 // - If the property is settable and this is simple assignment,
7325 // we really should use the primitive.
7326 // - If the property is settable, then we could try overloading
7327 // on a generic lvalue of the appropriate type; if it works
7328 // out to a builtin candidate, we would do that same operation
7329 // on the property, and otherwise just error.
7330 if (Settable)
7331 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7332 }
7333
7334 ConvertPropertyForRValue(Args[0]);
7335 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007336
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007337 // If this is the assignment operator, we only perform overload resolution
7338 // if the left-hand side is a class or enumeration type. This is actually
7339 // a hack. The standard requires that we do overload resolution between the
7340 // various built-in candidates, but as DR507 points out, this can lead to
7341 // problems. So we do it this way, which pretty much follows what GCC does.
7342 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007343 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007344 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007345
John McCalle26a8722010-12-04 08:14:53 +00007346 // If this is the .* operator, which is not overloadable, just
7347 // create a built-in binary operator.
7348 if (Opc == BO_PtrMemD)
7349 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7350
Douglas Gregor084d8552009-03-13 23:49:33 +00007351 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007352 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007353
7354 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007355 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007356
7357 // Add operator candidates that are member functions.
7358 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7359
John McCall4c4c1df2010-01-26 03:27:55 +00007360 // Add candidates from ADL.
7361 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7362 Args, 2,
7363 /*ExplicitTemplateArgs*/ 0,
7364 CandidateSet);
7365
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007366 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007367 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007368
7369 // Perform overload resolution.
7370 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007371 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007372 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007373 // We found a built-in operator or an overloaded operator.
7374 FunctionDecl *FnDecl = Best->Function;
7375
7376 if (FnDecl) {
7377 // We matched an overloaded operator. Build a call to that
7378 // operator.
7379
7380 // Convert the arguments.
7381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007382 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007383 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007384
John McCalldadc5752010-08-24 06:29:42 +00007385 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007386 = PerformCopyInitialization(
7387 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007388 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007389 FnDecl->getParamDecl(0)),
7390 SourceLocation(),
7391 Owned(Args[1]));
7392 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007393 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007394
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007395 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007396 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007397 return ExprError();
7398
7399 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007400 } else {
7401 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007402 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007403 = PerformCopyInitialization(
7404 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007405 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007406 FnDecl->getParamDecl(0)),
7407 SourceLocation(),
7408 Owned(Args[0]));
7409 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007410 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007411
John McCalldadc5752010-08-24 06:29:42 +00007412 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007413 = PerformCopyInitialization(
7414 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007415 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007416 FnDecl->getParamDecl(1)),
7417 SourceLocation(),
7418 Owned(Args[1]));
7419 if (Arg1.isInvalid())
7420 return ExprError();
7421 Args[0] = LHS = Arg0.takeAs<Expr>();
7422 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007423 }
7424
John McCall4fa0d5f2010-05-06 18:15:07 +00007425 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7426
John McCall7decc9e2010-11-18 06:31:45 +00007427 // Determine the result type.
7428 QualType ResultTy = FnDecl->getResultType();
7429 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7430 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007431
7432 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007433 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007434
John McCallb268a282010-08-23 23:25:46 +00007435 CXXOperatorCallExpr *TheCall =
7436 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007437 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007438
John McCallb268a282010-08-23 23:25:46 +00007439 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007440 FnDecl))
7441 return ExprError();
7442
John McCallb268a282010-08-23 23:25:46 +00007443 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007444 } else {
7445 // We matched a built-in operator. Convert the arguments, then
7446 // break out so that we will build the appropriate built-in
7447 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007448 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007449 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007450 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007451 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007452 return ExprError();
7453
7454 break;
7455 }
7456 }
7457
Douglas Gregor66950a32009-09-30 21:46:01 +00007458 case OR_No_Viable_Function: {
7459 // C++ [over.match.oper]p9:
7460 // If the operator is the operator , [...] and there are no
7461 // viable functions, then the operator is assumed to be the
7462 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007463 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007464 break;
7465
Sebastian Redl027de2a2009-05-21 11:50:50 +00007466 // For class as left operand for assignment or compound assigment operator
7467 // do not fall through to handling in built-in, but report that no overloaded
7468 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007469 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007470 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007471 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007472 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7473 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007474 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007475 } else {
7476 // No viable function; try to create a built-in operation, which will
7477 // produce an error. Then, show the non-viable candidates.
7478 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007479 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007480 assert(Result.isInvalid() &&
7481 "C++ binary operator overloading is missing candidates!");
7482 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007483 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7484 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007485 return move(Result);
7486 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007487
7488 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007489 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007490 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007491 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007492 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007493 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7494 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007495 return ExprError();
7496
7497 case OR_Deleted:
7498 Diag(OpLoc, diag::err_ovl_deleted_oper)
7499 << Best->Function->isDeleted()
7500 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007501 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007502 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007503 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007504 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007505
Douglas Gregor66950a32009-09-30 21:46:01 +00007506 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007507 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007508}
7509
John McCalldadc5752010-08-24 06:29:42 +00007510ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007511Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7512 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007513 Expr *Base, Expr *Idx) {
7514 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007515 DeclarationName OpName =
7516 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7517
7518 // If either side is type-dependent, create an appropriate dependent
7519 // expression.
7520 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7521
John McCall58cc69d2010-01-27 01:50:18 +00007522 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007523 // CHECKME: no 'operator' keyword?
7524 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7525 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007526 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007527 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007528 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007529 /*ADL*/ true, /*Overloaded*/ false,
7530 UnresolvedSetIterator(),
7531 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007532 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007533
Sebastian Redladba46e2009-10-29 20:17:01 +00007534 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7535 Args, 2,
7536 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007537 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007538 RLoc));
7539 }
7540
John McCalle26a8722010-12-04 08:14:53 +00007541 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7542 ConvertPropertyForRValue(Args[0]);
7543 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7544 ConvertPropertyForRValue(Args[1]);
7545
Sebastian Redladba46e2009-10-29 20:17:01 +00007546 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007547 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007548
7549 // Subscript can only be overloaded as a member function.
7550
7551 // Add operator candidates that are member functions.
7552 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7553
7554 // Add builtin operator candidates.
7555 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7556
7557 // Perform overload resolution.
7558 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007559 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007560 case OR_Success: {
7561 // We found a built-in operator or an overloaded operator.
7562 FunctionDecl *FnDecl = Best->Function;
7563
7564 if (FnDecl) {
7565 // We matched an overloaded operator. Build a call to that
7566 // operator.
7567
John McCalla0296f72010-03-19 07:35:19 +00007568 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007569 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007570
Sebastian Redladba46e2009-10-29 20:17:01 +00007571 // Convert the arguments.
7572 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007573 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007574 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007575 return ExprError();
7576
Anders Carlssona68e51e2010-01-29 18:37:50 +00007577 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007578 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007579 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007580 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007581 FnDecl->getParamDecl(0)),
7582 SourceLocation(),
7583 Owned(Args[1]));
7584 if (InputInit.isInvalid())
7585 return ExprError();
7586
7587 Args[1] = InputInit.takeAs<Expr>();
7588
Sebastian Redladba46e2009-10-29 20:17:01 +00007589 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007590 QualType ResultTy = FnDecl->getResultType();
7591 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7592 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007593
7594 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007595 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007596
John McCallb268a282010-08-23 23:25:46 +00007597 CXXOperatorCallExpr *TheCall =
7598 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7599 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007600 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007601
John McCallb268a282010-08-23 23:25:46 +00007602 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007603 FnDecl))
7604 return ExprError();
7605
John McCallb268a282010-08-23 23:25:46 +00007606 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007607 } else {
7608 // We matched a built-in operator. Convert the arguments, then
7609 // break out so that we will build the appropriate built-in
7610 // operator node.
7611 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007612 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007613 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007614 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007615 return ExprError();
7616
7617 break;
7618 }
7619 }
7620
7621 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007622 if (CandidateSet.empty())
7623 Diag(LLoc, diag::err_ovl_no_oper)
7624 << Args[0]->getType() << /*subscript*/ 0
7625 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7626 else
7627 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7628 << Args[0]->getType()
7629 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007630 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7631 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007632 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007633 }
7634
7635 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007636 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7637 << "[]"
7638 << Args[0]->getType() << Args[1]->getType()
7639 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007640 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7641 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007642 return ExprError();
7643
7644 case OR_Deleted:
7645 Diag(LLoc, diag::err_ovl_deleted_oper)
7646 << Best->Function->isDeleted() << "[]"
7647 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007648 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7649 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007650 return ExprError();
7651 }
7652
7653 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007654 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007655}
7656
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007657/// BuildCallToMemberFunction - Build a call to a member
7658/// function. MemExpr is the expression that refers to the member
7659/// function (and includes the object parameter), Args/NumArgs are the
7660/// arguments to the function call (not including the object
7661/// parameter). The caller needs to validate that the member
7662/// expression refers to a member function or an overloaded member
7663/// function.
John McCalldadc5752010-08-24 06:29:42 +00007664ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007665Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7666 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007667 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007668 // Dig out the member expression. This holds both the object
7669 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007670 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7671
John McCall10eae182009-11-30 22:42:35 +00007672 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007673 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007674 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007675 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007676 if (isa<MemberExpr>(NakedMemExpr)) {
7677 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007678 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007679 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007680 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007681 } else {
7682 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007683 Qualifier = UnresExpr->getQualifier();
7684
John McCall6e9f8f62009-12-03 04:06:58 +00007685 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007686
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007687 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007688 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007689
John McCall2d74de92009-12-01 22:10:20 +00007690 // FIXME: avoid copy.
7691 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7692 if (UnresExpr->hasExplicitTemplateArgs()) {
7693 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7694 TemplateArgs = &TemplateArgsBuffer;
7695 }
7696
John McCall10eae182009-11-30 22:42:35 +00007697 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7698 E = UnresExpr->decls_end(); I != E; ++I) {
7699
John McCall6e9f8f62009-12-03 04:06:58 +00007700 NamedDecl *Func = *I;
7701 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7702 if (isa<UsingShadowDecl>(Func))
7703 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7704
John McCall10eae182009-11-30 22:42:35 +00007705 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007706 // If explicit template arguments were provided, we can't call a
7707 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007708 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007709 continue;
7710
John McCalla0296f72010-03-19 07:35:19 +00007711 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007712 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007713 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007714 } else {
John McCall10eae182009-11-30 22:42:35 +00007715 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007716 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007717 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007718 CandidateSet,
7719 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007720 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007721 }
Mike Stump11289f42009-09-09 15:08:12 +00007722
John McCall10eae182009-11-30 22:42:35 +00007723 DeclarationName DeclName = UnresExpr->getMemberName();
7724
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007725 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007726 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007727 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007728 case OR_Success:
7729 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007730 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007731 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007732 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007733 break;
7734
7735 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007736 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007737 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007738 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007740 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007741 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007742
7743 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007744 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007745 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007746 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007747 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007748 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007749
7750 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007751 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007752 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007753 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007755 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007756 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007757 }
7758
John McCall16df1e52010-03-30 21:47:33 +00007759 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007760
John McCall2d74de92009-12-01 22:10:20 +00007761 // If overload resolution picked a static member, build a
7762 // non-member call based on that function.
7763 if (Method->isStatic()) {
7764 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7765 Args, NumArgs, RParenLoc);
7766 }
7767
John McCall10eae182009-11-30 22:42:35 +00007768 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007769 }
7770
John McCall7decc9e2010-11-18 06:31:45 +00007771 QualType ResultType = Method->getResultType();
7772 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7773 ResultType = ResultType.getNonLValueExprType(Context);
7774
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007775 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007776 CXXMemberCallExpr *TheCall =
7777 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00007778 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007779
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007780 // Check for a valid return type.
7781 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007782 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007783 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007784
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007785 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007786 // We only need to do this if there was actually an overload; otherwise
7787 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007788 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007789 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007790 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7791 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007792 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007793 MemExpr->setBase(ObjectArg);
7794
7795 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007796 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007797 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007798 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007799 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007800
John McCallb268a282010-08-23 23:25:46 +00007801 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007802 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007803
John McCallb268a282010-08-23 23:25:46 +00007804 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007805}
7806
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007807/// BuildCallToObjectOfClassType - Build a call to an object of class
7808/// type (C++ [over.call.object]), which can end up invoking an
7809/// overloaded function call operator (@c operator()) or performing a
7810/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007811ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007812Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007813 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007814 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007815 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00007816 if (Object->getObjectKind() == OK_ObjCProperty)
7817 ConvertPropertyForRValue(Object);
7818
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007819 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007820 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007821
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007822 // C++ [over.call.object]p1:
7823 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007824 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007825 // candidate functions includes at least the function call
7826 // operators of T. The function call operators of T are obtained by
7827 // ordinary lookup of the name operator() in the context of
7828 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007829 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007830 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007831
7832 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007833 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007834 << Object->getSourceRange()))
7835 return true;
7836
John McCall27b18f82009-11-17 02:14:36 +00007837 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7838 LookupQualifiedName(R, Record->getDecl());
7839 R.suppressDiagnostics();
7840
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007841 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007842 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007843 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007844 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007845 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007846 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007847
Douglas Gregorab7897a2008-11-19 22:57:39 +00007848 // C++ [over.call.object]p2:
7849 // In addition, for each conversion function declared in T of the
7850 // form
7851 //
7852 // operator conversion-type-id () cv-qualifier;
7853 //
7854 // where cv-qualifier is the same cv-qualification as, or a
7855 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007856 // denotes the type "pointer to function of (P1,...,Pn) returning
7857 // R", or the type "reference to pointer to function of
7858 // (P1,...,Pn) returning R", or the type "reference to function
7859 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007860 // is also considered as a candidate function. Similarly,
7861 // surrogate call functions are added to the set of candidate
7862 // functions for each conversion function declared in an
7863 // accessible base class provided the function is not hidden
7864 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007865 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007866 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007867 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007868 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007869 NamedDecl *D = *I;
7870 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7871 if (isa<UsingShadowDecl>(D))
7872 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7873
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007874 // Skip over templated conversion functions; they aren't
7875 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007876 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007877 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007878
John McCall6e9f8f62009-12-03 04:06:58 +00007879 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007880
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007881 // Strip the reference type (if any) and then the pointer type (if
7882 // any) to get down to what might be a function type.
7883 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7884 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7885 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007886
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007887 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007888 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007889 Object->getType(), Args, NumArgs,
7890 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007891 }
Mike Stump11289f42009-09-09 15:08:12 +00007892
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007893 // Perform overload resolution.
7894 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007895 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7896 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007897 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007898 // Overload resolution succeeded; we'll build the appropriate call
7899 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007900 break;
7901
7902 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007903 if (CandidateSet.empty())
7904 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7905 << Object->getType() << /*call*/ 1
7906 << Object->getSourceRange();
7907 else
7908 Diag(Object->getSourceRange().getBegin(),
7909 diag::err_ovl_no_viable_object_call)
7910 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007911 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007912 break;
7913
7914 case OR_Ambiguous:
7915 Diag(Object->getSourceRange().getBegin(),
7916 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007917 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007918 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007919 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007920
7921 case OR_Deleted:
7922 Diag(Object->getSourceRange().getBegin(),
7923 diag::err_ovl_deleted_object_call)
7924 << Best->Function->isDeleted()
7925 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007926 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007927 break;
Mike Stump11289f42009-09-09 15:08:12 +00007928 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007929
Douglas Gregorb412e172010-07-25 18:17:45 +00007930 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007931 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007932
Douglas Gregorab7897a2008-11-19 22:57:39 +00007933 if (Best->Function == 0) {
7934 // Since there is no function declaration, this is one of the
7935 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007936 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007937 = cast<CXXConversionDecl>(
7938 Best->Conversions[0].UserDefined.ConversionFunction);
7939
John McCalla0296f72010-03-19 07:35:19 +00007940 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007941 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007942
Douglas Gregorab7897a2008-11-19 22:57:39 +00007943 // We selected one of the surrogate functions that converts the
7944 // object parameter to a function pointer. Perform the conversion
7945 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007946
7947 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007948 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007949 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7950 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007951
John McCallfaf5fb42010-08-26 23:41:50 +00007952 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007953 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007954 }
7955
John McCalla0296f72010-03-19 07:35:19 +00007956 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007957 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007958
Douglas Gregorab7897a2008-11-19 22:57:39 +00007959 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7960 // that calls this method, using Object for the implicit object
7961 // parameter and passing along the remaining arguments.
7962 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007963 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007964
7965 unsigned NumArgsInProto = Proto->getNumArgs();
7966 unsigned NumArgsToCheck = NumArgs;
7967
7968 // Build the full argument list for the method call (the
7969 // implicit object parameter is placed at the beginning of the
7970 // list).
7971 Expr **MethodArgs;
7972 if (NumArgs < NumArgsInProto) {
7973 NumArgsToCheck = NumArgsInProto;
7974 MethodArgs = new Expr*[NumArgsInProto + 1];
7975 } else {
7976 MethodArgs = new Expr*[NumArgs + 1];
7977 }
7978 MethodArgs[0] = Object;
7979 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7980 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007981
John McCall7decc9e2010-11-18 06:31:45 +00007982 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007983
7984 // Once we've built TheCall, all of the expressions are properly
7985 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00007986 QualType ResultTy = Method->getResultType();
7987 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7988 ResultTy = ResultTy.getNonLValueExprType(Context);
7989
John McCallb268a282010-08-23 23:25:46 +00007990 CXXOperatorCallExpr *TheCall =
7991 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7992 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00007993 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007994 delete [] MethodArgs;
7995
John McCallb268a282010-08-23 23:25:46 +00007996 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007997 Method))
7998 return true;
7999
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008000 // We may have default arguments. If so, we need to allocate more
8001 // slots in the call for them.
8002 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008003 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008004 else if (NumArgs > NumArgsInProto)
8005 NumArgsToCheck = NumArgsInProto;
8006
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008007 bool IsError = false;
8008
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008009 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008010 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008011 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008012 TheCall->setArg(0, Object);
8013
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008014
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008015 // Check the argument types.
8016 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008017 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008018 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008019 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008020
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008021 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008022
John McCalldadc5752010-08-24 06:29:42 +00008023 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008024 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008025 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008026 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008027 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008028
8029 IsError |= InputInit.isInvalid();
8030 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008031 } else {
John McCalldadc5752010-08-24 06:29:42 +00008032 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008033 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8034 if (DefArg.isInvalid()) {
8035 IsError = true;
8036 break;
8037 }
8038
8039 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008040 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008041
8042 TheCall->setArg(i + 1, Arg);
8043 }
8044
8045 // If this is a variadic call, handle args passed through "...".
8046 if (Proto->isVariadic()) {
8047 // Promote the arguments (C99 6.5.2.2p7).
8048 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8049 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008050 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008051 TheCall->setArg(i + 1, Arg);
8052 }
8053 }
8054
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008055 if (IsError) return true;
8056
John McCallb268a282010-08-23 23:25:46 +00008057 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008058 return true;
8059
John McCalle172be52010-08-24 06:09:16 +00008060 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008061}
8062
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008063/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008064/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008065/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008066ExprResult
John McCallb268a282010-08-23 23:25:46 +00008067Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008068 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008069
John McCalle26a8722010-12-04 08:14:53 +00008070 if (Base->getObjectKind() == OK_ObjCProperty)
8071 ConvertPropertyForRValue(Base);
8072
John McCallbc077cf2010-02-08 23:07:23 +00008073 SourceLocation Loc = Base->getExprLoc();
8074
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008075 // C++ [over.ref]p1:
8076 //
8077 // [...] An expression x->m is interpreted as (x.operator->())->m
8078 // for a class object x of type T if T::operator->() exists and if
8079 // the operator is selected as the best match function by the
8080 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008081 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008082 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008083 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008084
John McCallbc077cf2010-02-08 23:07:23 +00008085 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008086 PDiag(diag::err_typecheck_incomplete_tag)
8087 << Base->getSourceRange()))
8088 return ExprError();
8089
John McCall27b18f82009-11-17 02:14:36 +00008090 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8091 LookupQualifiedName(R, BaseRecord->getDecl());
8092 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008093
8094 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008095 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008096 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008097 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008098 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008099
8100 // Perform overload resolution.
8101 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008102 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008103 case OR_Success:
8104 // Overload resolution succeeded; we'll build the call below.
8105 break;
8106
8107 case OR_No_Viable_Function:
8108 if (CandidateSet.empty())
8109 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008110 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008111 else
8112 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008113 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008114 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008115 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008116
8117 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008118 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8119 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008120 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008121 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008122
8123 case OR_Deleted:
8124 Diag(OpLoc, diag::err_ovl_deleted_oper)
8125 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008126 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008127 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008128 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008129 }
8130
John McCalla0296f72010-03-19 07:35:19 +00008131 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008132 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008133
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008134 // Convert the object parameter.
8135 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008136 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8137 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008138 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008139
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008140 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008141 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008142
John McCall7decc9e2010-11-18 06:31:45 +00008143 QualType ResultTy = Method->getResultType();
8144 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8145 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008146 CXXOperatorCallExpr *TheCall =
8147 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008148 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008149
John McCallb268a282010-08-23 23:25:46 +00008150 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008151 Method))
8152 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008153 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008154}
8155
Douglas Gregorcd695e52008-11-10 20:40:00 +00008156/// FixOverloadedFunctionReference - E is an expression that refers to
8157/// a C++ overloaded function (possibly with some parentheses and
8158/// perhaps a '&' around it). We have resolved the overloaded function
8159/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008160/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008161Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008162 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008163 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008164 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8165 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008166 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008167 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008168
8169 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8170 }
8171
8172 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008173 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8174 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008175 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008176 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008177 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008178 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008179 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008180 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008181
John McCallcf142162010-08-07 06:22:56 +00008182 return ImplicitCastExpr::Create(Context, ICE->getType(),
8183 ICE->getCastKind(),
8184 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008185 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008186 }
8187
8188 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008189 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008190 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008191 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8192 if (Method->isStatic()) {
8193 // Do nothing: static member functions aren't any different
8194 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008195 } else {
John McCalle66edc12009-11-24 19:00:30 +00008196 // Fix the sub expression, which really has to be an
8197 // UnresolvedLookupExpr holding an overloaded member function
8198 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008199 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8200 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008201 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008202 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008203
John McCalld14a8642009-11-21 08:51:07 +00008204 assert(isa<DeclRefExpr>(SubExpr)
8205 && "fixed to something other than a decl ref");
8206 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8207 && "fixed to a member ref with no nested name qualifier");
8208
8209 // We have taken the address of a pointer to member
8210 // function. Perform the computation here so that we get the
8211 // appropriate pointer to member type.
8212 QualType ClassType
8213 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8214 QualType MemPtrType
8215 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8216
John McCall7decc9e2010-11-18 06:31:45 +00008217 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8218 VK_RValue, OK_Ordinary,
8219 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008220 }
8221 }
John McCall16df1e52010-03-30 21:47:33 +00008222 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8223 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008224 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008225 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008226
John McCalle3027922010-08-25 11:45:40 +00008227 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008228 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008229 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008230 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008231 }
John McCalld14a8642009-11-21 08:51:07 +00008232
8233 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008234 // FIXME: avoid copy.
8235 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008236 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008237 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8238 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008239 }
8240
John McCalld14a8642009-11-21 08:51:07 +00008241 return DeclRefExpr::Create(Context,
8242 ULE->getQualifier(),
8243 ULE->getQualifierRange(),
8244 Fn,
8245 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008246 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008247 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008248 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008249 }
8250
John McCall10eae182009-11-30 22:42:35 +00008251 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008252 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008253 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8254 if (MemExpr->hasExplicitTemplateArgs()) {
8255 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8256 TemplateArgs = &TemplateArgsBuffer;
8257 }
John McCall6b51f282009-11-23 01:53:49 +00008258
John McCall2d74de92009-12-01 22:10:20 +00008259 Expr *Base;
8260
John McCall7decc9e2010-11-18 06:31:45 +00008261 // If we're filling in a static method where we used to have an
8262 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008263 if (MemExpr->isImplicitAccess()) {
8264 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8265 return DeclRefExpr::Create(Context,
8266 MemExpr->getQualifier(),
8267 MemExpr->getQualifierRange(),
8268 Fn,
8269 MemExpr->getMemberLoc(),
8270 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008271 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008272 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008273 } else {
8274 SourceLocation Loc = MemExpr->getMemberLoc();
8275 if (MemExpr->getQualifier())
8276 Loc = MemExpr->getQualifierRange().getBegin();
8277 Base = new (Context) CXXThisExpr(Loc,
8278 MemExpr->getBaseType(),
8279 /*isImplicit=*/true);
8280 }
John McCall2d74de92009-12-01 22:10:20 +00008281 } else
John McCallc3007a22010-10-26 07:05:15 +00008282 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008283
8284 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008285 MemExpr->isArrow(),
8286 MemExpr->getQualifier(),
8287 MemExpr->getQualifierRange(),
8288 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008289 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008290 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008291 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008292 Fn->getType(),
8293 cast<CXXMethodDecl>(Fn)->isStatic()
8294 ? VK_LValue : VK_RValue,
8295 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008296 }
8297
John McCallc3007a22010-10-26 07:05:15 +00008298 llvm_unreachable("Invalid reference to overloaded function");
8299 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008300}
8301
John McCalldadc5752010-08-24 06:29:42 +00008302ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8303 DeclAccessPair Found,
8304 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008305 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008306}
8307
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008308} // end namespace clang