SemaOverload.cpp revision f20d27288c7f124dcc9c50c7c6bf766d522ceb31
15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// 35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// The LLVM Compiler Infrastructure 45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// 50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source 60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details. 75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// 85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===// 95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// 105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// This file provides Sema routines for C++ overloading. 115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// 125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===// 135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer 14c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/Sema/SemaInternal.h" 150979c805475d1ba49b5d6ef93c4d2ce6d2eab6edDouglas Gregor#include "clang/Sema/Lookup.h" 16a4d55d89c8076b402bb168e3edeef0c2cd2a78c3Chris Lattner#include "clang/Sema/Initialization.h" 172eadfb638eb1bb6ccfd6fd0453e764d47e27eed9Chris Lattner#include "clang/Sema/Template.h" 18a4d55d89c8076b402bb168e3edeef0c2cd2a78c3Chris Lattner#include "clang/Sema/TemplateDeduction.h" 1998cd599ee8a9b259ed7388ee2921a20d97658864Douglas Gregor#include "clang/Basic/Diagnostic.h" 20aaba5e346dffdbad5d1c42765a89e4a7afb0da67Douglas Gregor#include "clang/Lex/Preprocessor.h" 2119cc4abea06a9b49e0e16a50d335c064cd723572Anders Carlsson#include "clang/AST/ASTContext.h" 225f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/CXXInheritance.h" 231b63e4f732dbc73d90abf886b4d21f8e3a165f6dChris Lattner#include "clang/AST/DeclObjC.h" 24da5a6b6d9fd52899499d5b7b46273ec844dcaa6eChris Lattner#include "clang/AST/Expr.h" 25cf3293eaeb3853d12cff47e648bbe835004e929fDouglas Gregor#include "clang/AST/ExprCXX.h" 263a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson#include "clang/AST/ExprObjC.h" 27ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor#include "clang/AST/TypeOrdering.h" 285f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/PartialDiagnostic.h" 295f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/ADT/DenseSet.h" 30bef0efd11bc4430a3ee437a3213cec5c18af855aChris Lattner#include "llvm/ADT/SmallPtrSet.h" 31bef0efd11bc4430a3ee437a3213cec5c18af855aChris Lattner#include "llvm/ADT/STLExtras.h" 322b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner#include <algorithm> 332b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner 342b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattnernamespace clang { 352b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattnerusing namespace sema; 362b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner 372b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner/// A convenience routine for creating a decayed reference to a 382b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner/// function. 39c302113179a1c2b1254224ea9b6f5316ceeb375cSean Huntstatic ExprResult 402ade35e2cfd554e49d35a52047cea98a82787af9Douglas GregorCreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, 41c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt SourceLocation Loc = SourceLocation(), 422b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 432b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), 44c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt VK_LValue, Loc, LocInfo)); 452b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner E = S.DefaultFunctionArrayConversion(E.take()); 462b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner if (E.isInvalid()) 472de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return ExprError(); 482de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return move(E); 492b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner} 502b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner 512b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattnerstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 522b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner bool InOverloadResolution, 532b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner StandardConversionSequence &SCS, 54c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt bool CStyle, 556907fbe758d23e1aec4c0a67e7b633d1d855feb4John McCall bool AllowObjCWritebackConversion); 566907fbe758d23e1aec4c0a67e7b633d1d855feb4John McCall 576907fbe758d23e1aec4c0a67e7b633d1d855feb4John McCallstatic bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 582b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner QualType &ToType, 59c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt bool InOverloadResolution, 602b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner StandardConversionSequence &SCS, 612b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner bool CStyle); 622b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattnerstatic OverloadingResult 632de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 642de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall UserDefinedConversionSequence& User, 652de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall OverloadCandidateSet& Conversions, 662de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool AllowExplicit); 672de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 682de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 692de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallstatic ImplicitConversionSequence::CompareKind 702de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallCompareStandardConversionSequences(Sema &S, 712b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner const StandardConversionSequence& SCS1, 72c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt const StandardConversionSequence& SCS2); 732de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 742de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallstatic ImplicitConversionSequence::CompareKind 752de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallCompareQualificationConversions(Sema &S, 762b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner const StandardConversionSequence& SCS1, 772b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner const StandardConversionSequence& SCS2); 782b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner 79c302113179a1c2b1254224ea9b6f5316ceeb375cSean Huntstatic ImplicitConversionSequence::CompareKind 802de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallCompareDerivedToBaseConversions(Sema &S, 812de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall const StandardConversionSequence& SCS1, 822b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner const StandardConversionSequence& SCS2); 832b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner 842b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner 85c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt 862b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner/// GetConversionCategory - Retrieve the implicit conversion 872b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner/// category corresponding to the given implicit conversion kind. 882b334bb3126a67895813e49e6228dad4aec0b4d6Chris LattnerImplicitConversionCategory 89c302113179a1c2b1254224ea9b6f5316ceeb375cSean HuntGetConversionCategory(ImplicitConversionKind Kind) { 902b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner static const ImplicitConversionCategory 912b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner Category[(int)ICK_Num_Conversion_Kinds] = { 922b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner ICC_Identity, 935f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer ICC_Lvalue_Transformation, 945f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer ICC_Lvalue_Transformation, 955f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer ICC_Lvalue_Transformation, 965f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer ICC_Identity, 97d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Qualification_Adjustment, 98d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Promotion, 99d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Promotion, 100d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Promotion, 101d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 102d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 103d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 104d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 105d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 106d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 107d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 108d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 109d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 110d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 111d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 112d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion, 113d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICC_Conversion 114d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall }; 115d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall return Category[(int)Kind]; 1168dfbd8b252ba4e6cf4b7a3422f6ef0ca21312dfeArgyrios Kyrtzidis} 1178dfbd8b252ba4e6cf4b7a3422f6ef0ca21312dfeArgyrios Kyrtzidis 1188dfbd8b252ba4e6cf4b7a3422f6ef0ca21312dfeArgyrios Kyrtzidis/// GetConversionRank - Retrieve the implicit conversion rank 1198dfbd8b252ba4e6cf4b7a3422f6ef0ca21312dfeArgyrios Kyrtzidis/// corresponding to the given implicit conversion kind. 1208dfbd8b252ba4e6cf4b7a3422f6ef0ca21312dfeArgyrios KyrtzidisImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 121d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall static const ImplicitConversionRank 122d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall Rank[(int)ICK_Num_Conversion_Kinds] = { 1238dfbd8b252ba4e6cf4b7a3422f6ef0ca21312dfeArgyrios Kyrtzidis ICR_Exact_Match, 124d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICR_Exact_Match, 125d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall ICR_Exact_Match, 1260da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Exact_Match, 1270da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Exact_Match, 1280da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Exact_Match, 129c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ICR_Promotion, 1300da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Promotion, 1310da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Promotion, 1320da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1330da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1340da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 135c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ICR_Conversion, 1360da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1370da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1380da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1390da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1400da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1410da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1420da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1430da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Complex_Real_Conversion, 1440da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1450da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Conversion, 1460da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor ICR_Writeback_Conversion 147c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt }; 1480da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor return Rank[(int)Kind]; 1490da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor} 1500da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor 1510da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor/// GetImplicitConversionName - Return the name of this kind of 1520da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor/// implicit conversion. 1530da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregorconst char* GetImplicitConversionName(ImplicitConversionKind Kind) { 154096832c5ed5b9106fa177ebc148489760c3bc496John McCall static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 1550da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "No conversion", 156c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt "Lvalue-to-rvalue", 1570da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Array-to-pointer", 1580da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Function-to-pointer", 1590da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Noreturn adjustment", 1600da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Qualification", 1610da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Integral promotion", 1620da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Floating point promotion", 1630da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Complex promotion", 1640da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Integral conversion", 1650da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Floating conversion", 1660da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor "Complex conversion", 1672ade35e2cfd554e49d35a52047cea98a82787af9Douglas Gregor "Floating-integral conversion", 168501edb6a54524555ad27fbf41a7920dc756b08c6Douglas Gregor "Pointer conversion", 16931310a21fb2a9f13950f864f681c86080b05d5b2Sebastian Redl "Pointer-to-member conversion", 170501edb6a54524555ad27fbf41a7920dc756b08c6Douglas Gregor "Boolean conversion", 171501edb6a54524555ad27fbf41a7920dc756b08c6Douglas Gregor "Compatible-types conversion", 172bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor "Derived-to-base conversion", 173bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor "Vector conversion", 174bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor "Vector splat", 175bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor "Complex-real conversion", 176bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor "Block Pointer conversion", 1777ed5bd3e27a6f2b37ee0449aa818116cbd03306eDouglas Gregor "Transparent Union Conversion" 178bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor "Writeback conversion" 179bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor }; 180bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor return Name[Kind]; 181bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor} 182bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor 183bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor/// StandardConversionSequence - Set the standard conversion 184bb6e73fcf60fa5a4cc36c14744dc366b658443b5Douglas Gregor/// sequence to the identity conversion. 1850da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregorvoid StandardConversionSequence::setAsIdentityConversion() { 1860da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor First = ICK_Identity; 1870da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor Second = ICK_Identity; 1880da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor Third = ICK_Identity; 1890da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor DeprecatedStringLiteralToCharPtr = false; 190c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt QualificationIncludesObjCLifetime = false; 191a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor ReferenceBinding = false; 192dbd872f273a8dbf22e089b3def6c09f0a460965dJohn McCall DirectBinding = false; 193d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall IsLvalueReference = true; 1940da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor BindsToFunctionLvalue = false; 1950da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor BindsToRvalue = false; 196a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor BindsImplicitObjectArgumentWithoutRefQualifier = false; 197a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor ObjCLifetimeConversionBinding = false; 198d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall CopyConstructor = 0; 199a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor} 200a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor 201a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor/// getRank - Retrieve the rank of this standard conversion sequence 202a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor/// implicit conversions. 204a2813cec2605ce7878d1b13471d685f689b251afDouglas GregorImplicitConversionRank StandardConversionSequence::getRank() const { 205c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ImplicitConversionRank Rank = ICR_Exact_Match; 206d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall if (GetConversionRank(First) > Rank) 207096832c5ed5b9106fa177ebc148489760c3bc496John McCall Rank = GetConversionRank(First); 208a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor if (GetConversionRank(Second) > Rank) 2090da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor Rank = GetConversionRank(Second); 210a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor if (GetConversionRank(Third) > Rank) 211a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor Rank = GetConversionRank(Third); 2122577743c5650c646fb705df01403707e94f2df04Abramo Bagnara return Rank; 2132577743c5650c646fb705df01403707e94f2df04Abramo Bagnara} 2142577743c5650c646fb705df01403707e94f2df04Abramo Bagnara 2152577743c5650c646fb705df01403707e94f2df04Abramo Bagnara/// isPointerConversionToBool - Determines whether this conversion is 2162577743c5650c646fb705df01403707e94f2df04Abramo Bagnara/// a conversion of a pointer or pointer-to-member to bool. This is 2172577743c5650c646fb705df01403707e94f2df04Abramo Bagnara/// used as part of the ranking of standard conversion sequences 2182577743c5650c646fb705df01403707e94f2df04Abramo Bagnara/// (C++ 13.3.3.2p4). 2192577743c5650c646fb705df01403707e94f2df04Abramo Bagnarabool StandardConversionSequence::isPointerConversionToBool() const { 2202577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // Note that FromType has not necessarily been transformed by the 2212577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // array-to-pointer or function-to-pointer implicit conversions, so 2222577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // check for their presence as well as checking whether FromType is 2232577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // a pointer. 2242577743c5650c646fb705df01403707e94f2df04Abramo Bagnara if (getToType(1)->isBooleanType() && 2252577743c5650c646fb705df01403707e94f2df04Abramo Bagnara (getFromType()->isPointerType() || 2262577743c5650c646fb705df01403707e94f2df04Abramo Bagnara getFromType()->isObjCObjectPointerType() || 2272577743c5650c646fb705df01403707e94f2df04Abramo Bagnara getFromType()->isBlockPointerType() || 2282577743c5650c646fb705df01403707e94f2df04Abramo Bagnara getFromType()->isNullPtrType() || 229096832c5ed5b9106fa177ebc148489760c3bc496John McCall First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 2302577743c5650c646fb705df01403707e94f2df04Abramo Bagnara return true; 2312577743c5650c646fb705df01403707e94f2df04Abramo Bagnara 2322577743c5650c646fb705df01403707e94f2df04Abramo Bagnara return false; 2332577743c5650c646fb705df01403707e94f2df04Abramo Bagnara} 234a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor 235a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor/// isPointerConversionToVoidPointer - Determines whether this 236a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor/// conversion is a conversion of a pointer to a void pointer. This is 237dbd872f273a8dbf22e089b3def6c09f0a460965dJohn McCall/// used as part of the ranking of standard conversion sequences (C++ 238a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor/// 13.3.3.2p4). 2390da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregorbool 2400da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas GregorStandardConversionSequence:: 2412577743c5650c646fb705df01403707e94f2df04Abramo BagnaraisPointerConversionToVoidPointer(ASTContext& Context) const { 2422577743c5650c646fb705df01403707e94f2df04Abramo Bagnara QualType FromType = getFromType(); 2432577743c5650c646fb705df01403707e94f2df04Abramo Bagnara QualType ToType = getToType(1); 2442577743c5650c646fb705df01403707e94f2df04Abramo Bagnara 2452577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // Note that FromType has not necessarily been transformed by the 2462577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // array-to-pointer implicit conversion, so check for its presence 2472577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // and redo the conversion to get a pointer. 2482577743c5650c646fb705df01403707e94f2df04Abramo Bagnara if (First == ICK_Array_To_Pointer) 2492577743c5650c646fb705df01403707e94f2df04Abramo Bagnara FromType = Context.getArrayDecayedType(FromType); 2502577743c5650c646fb705df01403707e94f2df04Abramo Bagnara 2512577743c5650c646fb705df01403707e94f2df04Abramo Bagnara if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 2522577743c5650c646fb705df01403707e94f2df04Abramo Bagnara if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor return ToPtrType->getPointeeType()->isVoidType(); 254a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor 255a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor return false; 256c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt} 257d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall 258d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall/// DebugPrint - Print this standard conversion sequence to standard 259c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt/// error. Useful for debugging overloading issues. 260a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregorvoid StandardConversionSequence::DebugPrint() const { 2612577743c5650c646fb705df01403707e94f2df04Abramo Bagnara raw_ostream &OS = llvm::errs(); 2620da76df9218d7c27b471b0a4d83a5b29fe24e5b4Douglas Gregor bool PrintedSomething = false; 263a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor if (First != ICK_Identity) { 264a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor OS << GetImplicitConversionName(First); 265663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis PrintedSomething = true; 266663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis } 267663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis 268663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis if (Second != ICK_Identity) { 269663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis if (PrintedSomething) { 270663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis OS << " -> "; 271663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis } 272663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis OS << GetImplicitConversionName(Second); 273663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis 274663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis if (CopyConstructor) { 275663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis OS << " (by copy constructor)"; 276663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis } else if (DirectBinding) { 277663e380d7b2de2bbf20e886e05371195bea9adc4Argyrios Kyrtzidis OS << " (direct reference binding)"; 278a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor } else if (ReferenceBinding) { 2792577743c5650c646fb705df01403707e94f2df04Abramo Bagnara OS << " (reference binding)"; 280a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor } 281a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor PrintedSomething = true; 282096832c5ed5b9106fa177ebc148489760c3bc496John McCall } 283a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor 284a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor if (Third != ICK_Identity) { 285a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor if (PrintedSomething) { 286a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor OS << " -> "; 2873a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson } 2883a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << GetImplicitConversionName(Third); 289848fa64143fbe5ae62a601ad61277f741e54dfabAnders Carlsson PrintedSomething = true; 290848fa64143fbe5ae62a601ad61277f741e54dfabAnders Carlsson } 291848fa64143fbe5ae62a601ad61277f741e54dfabAnders Carlsson 2923a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson if (!PrintedSomething) { 293848fa64143fbe5ae62a601ad61277f741e54dfabAnders Carlsson OS << "No conversions required"; 2943a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson } 2953a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson} 2963a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson 2973a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson/// DebugPrint - Print this user-defined conversion sequence to standard 2983a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson/// error. Useful for debugging overloading issues. 2993a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlssonvoid UserDefinedConversionSequence::DebugPrint() const { 300848fa64143fbe5ae62a601ad61277f741e54dfabAnders Carlsson raw_ostream &OS = llvm::errs(); 3013a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson if (Before.First || Before.Second || Before.Third) { 3024eadcc569223135e13353c9381b448986e3f7053Sam Weinig Before.DebugPrint(); 3034eadcc569223135e13353c9381b448986e3f7053Sam Weinig OS << " -> "; 3043a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson } 3053a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << '\'' << ConversionFunction << '\''; 3063a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson if (After.First || After.Second || After.Third) { 3073a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << " -> "; 3083a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson After.DebugPrint(); 3093a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson } 310183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall} 3113a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson 3123a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson/// DebugPrint - Print this implicit conversion sequence to standard 3133a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson/// error. Useful for debugging overloading issues. 3143a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlssonvoid ImplicitConversionSequence::DebugPrint() const { 3153a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson raw_ostream &OS = llvm::errs(); 3163a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson switch (ConversionKind) { 3173a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case StandardConversion: 3183a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << "Standard conversion: "; 3193a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson Standard.DebugPrint(); 3203a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson break; 3213a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case UserDefinedConversion: 3223a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << "User-defined conversion: "; 3233a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson UserDefined.DebugPrint(); 3243a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson break; 3253a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case EllipsisConversion: 3263a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << "Ellipsis conversion"; 3273a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson break; 3283a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case AmbiguousConversion: 3293a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OS << "Ambiguous conversion"; 3303a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson break; 3313a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case BadConversion: 3324eadcc569223135e13353c9381b448986e3f7053Sam Weinig OS << "Bad conversion"; 3334eadcc569223135e13353c9381b448986e3f7053Sam Weinig break; 3344eadcc569223135e13353c9381b448986e3f7053Sam Weinig } 3354eadcc569223135e13353c9381b448986e3f7053Sam Weinig 3364eadcc569223135e13353c9381b448986e3f7053Sam Weinig OS << "\n"; 3374eadcc569223135e13353c9381b448986e3f7053Sam Weinig} 3384eadcc569223135e13353c9381b448986e3f7053Sam Weinig 3394eadcc569223135e13353c9381b448986e3f7053Sam Weinigvoid AmbiguousConversionSequence::construct() { 3403a1ce1ed0f5686384e712837bad28c576622e442Sam Weinig new (&conversions()) ConversionSet(); 3413a1ce1ed0f5686384e712837bad28c576622e442Sam Weinig} 3423a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson 3433a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlssonvoid AmbiguousConversionSequence::destruct() { 3443a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson conversions().~ConversionSet(); 3453a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson} 3463a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson 3473a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlssonvoid 3483a082d81006e7a2e01a6e431a22e21c78490ff8fAnders CarlssonAmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 3493a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson FromTypePtr = O.FromTypePtr; 3503a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson ToTypePtr = O.ToTypePtr; 3513a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson new (&conversions()) ConversionSet(O.conversions()); 3523a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson} 353b03d33edaf24af2893a50caee4d2c99839242c44Ted Kremenek 354b03d33edaf24af2893a50caee4d2c99839242c44Ted Kremeneknamespace { 355b03d33edaf24af2893a50caee4d2c99839242c44Ted Kremenek // Structure used by OverloadCandidate::DeductionFailureInfo to store 356b03d33edaf24af2893a50caee4d2c99839242c44Ted Kremenek // template parameter and template argument information. 357900fc6388e803868a34b9483510c345e9b49d7ebBenjamin Kramer struct DFIParamWithArguments { 358b03d33edaf24af2893a50caee4d2c99839242c44Ted Kremenek TemplateParameter Param; 3593a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson TemplateArgument FirstArg; 360900fc6388e803868a34b9483510c345e9b49d7ebBenjamin Kramer TemplateArgument SecondArg; 361900fc6388e803868a34b9483510c345e9b49d7ebBenjamin Kramer }; 362900fc6388e803868a34b9483510c345e9b49d7ebBenjamin Kramer} 3633a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson 3643a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson/// \brief Convert from Sema's representation of template deduction information 3653a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson/// to the form used in overload-candidate information. 3663a082d81006e7a2e01a6e431a22e21c78490ff8fAnders CarlssonOverloadCandidate::DeductionFailureInfo 3673a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlssonstatic MakeDeductionFailureInfo(ASTContext &Context, 3683a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson Sema::TemplateDeductionResult TDK, 3693a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson TemplateDeductionInfo &Info) { 3703a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson OverloadCandidate::DeductionFailureInfo Result; 3713a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson Result.Result = static_cast<unsigned>(TDK); 3723a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson Result.Data = 0; 3733a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson switch (TDK) { 3743a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case Sema::TDK_Success: 3753a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case Sema::TDK_InstantiationDepth: 3763a082d81006e7a2e01a6e431a22e21c78490ff8fAnders Carlsson case Sema::TDK_TooManyArguments: 3779996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_TooFewArguments: 3789996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis break; 3799996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis 3809996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_Incomplete: 3819996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_InvalidExplicitArguments: 3829996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis Result.Data = Info.Param.getOpaqueValue(); 3839996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis break; 3849996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis 3859996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_Inconsistent: 3869996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_Underqualified: { 3879996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis // FIXME: Should allocate from normal heap so that we can free this later. 3889996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 3899996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis Saved->Param = Info.Param; 3909996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis Saved->FirstArg = Info.FirstArg; 3919996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis Saved->SecondArg = Info.SecondArg; 3929996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis Result.Data = Saved; 3939996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis break; 3949996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis } 3959996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis 3969996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_SubstitutionFailure: 3979996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis Result.Data = Info.take(); 3989996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis break; 3999996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis 4009996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_NonDeducedMismatch: 4019996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_FailedOverloadResolution: 4029996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis break; 4039996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis } 4049996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis 4059996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis return Result; 4069996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis} 4079996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis 4089996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidisvoid OverloadCandidate::DeductionFailureInfo::Destroy() { 4099996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 4109996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_Success: 4119996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_InstantiationDepth: 4129996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_Incomplete: 4139996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_TooManyArguments: 4149996a7f06a3c5b4554692e7177930cf4e8ef09afArgyrios Kyrtzidis case Sema::TDK_TooFewArguments: 415da8249e57f3badecf925571881fe57243935c6c1Chris Lattner case Sema::TDK_InvalidExplicitArguments: 416da8249e57f3badecf925571881fe57243935c6c1Chris Lattner break; 417da8249e57f3badecf925571881fe57243935c6c1Chris Lattner 418da8249e57f3badecf925571881fe57243935c6c1Chris Lattner case Sema::TDK_Inconsistent: 419da8249e57f3badecf925571881fe57243935c6c1Chris Lattner case Sema::TDK_Underqualified: 420ee5a700af3fe9ae1a639c271f093f40677dddc04Dale Johannesen // FIXME: Destroy the data? 421ee5a700af3fe9ae1a639c271f093f40677dddc04Dale Johannesen Data = 0; 422ee5a700af3fe9ae1a639c271f093f40677dddc04Dale Johannesen break; 423da8249e57f3badecf925571881fe57243935c6c1Chris Lattner 424da8249e57f3badecf925571881fe57243935c6c1Chris Lattner case Sema::TDK_SubstitutionFailure: 425da8249e57f3badecf925571881fe57243935c6c1Chris Lattner // FIXME: Destroy the template arugment list? 4262085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner Data = 0; 4272085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner break; 4282085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner 4291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // Unhandled 430a135fb43eb94524a6529768596a4533eed9aa70dAnders Carlsson case Sema::TDK_NonDeducedMismatch: 4312085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner case Sema::TDK_FailedOverloadResolution: 4322085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner break; 4332085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner } 4342085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner} 4352085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner 4362085fd6cd22ec5c268175251db10d7c60caf7aaaChris LattnerTemplateParameter 4371eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpOverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 4385f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 4392085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner case Sema::TDK_Success: 4402085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner case Sema::TDK_InstantiationDepth: 4412085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner case Sema::TDK_TooManyArguments: 4422085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner case Sema::TDK_TooFewArguments: 4432085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner case Sema::TDK_SubstitutionFailure: 4442085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner return TemplateParameter(); 4452085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner 4465f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_Incomplete: 447726e168dc09fb23f53c7b004f8e919421ee91806Chris Lattner case Sema::TDK_InvalidExplicitArguments: 4482085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner return TemplateParameter::getFromOpaqueValue(Data); 4492085fd6cd22ec5c268175251db10d7c60caf7aaaChris Lattner 450726e168dc09fb23f53c7b004f8e919421ee91806Chris Lattner case Sema::TDK_Inconsistent: 451726e168dc09fb23f53c7b004f8e919421ee91806Chris Lattner case Sema::TDK_Underqualified: 452673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor return static_cast<DFIParamWithArguments*>(Data)->Param; 453673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor 454673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor // Unhandled 455673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor case Sema::TDK_NonDeducedMismatch: 456673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor case Sema::TDK_FailedOverloadResolution: 457673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor break; 458673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor } 459673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor 460673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor return TemplateParameter(); 461673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor} 462673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor 463b648023da23e8b227cdda57a241db4c6f368726bDaniel DunbarTemplateArgumentList * 464b648023da23e8b227cdda57a241db4c6f368726bDaniel DunbarOverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 465b648023da23e8b227cdda57a241db4c6f368726bDaniel Dunbar switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 466673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor case Sema::TDK_Success: 467b648023da23e8b227cdda57a241db4c6f368726bDaniel Dunbar case Sema::TDK_InstantiationDepth: 468673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor case Sema::TDK_TooManyArguments: 469673ecd6a4a9f7c12fb6f76f84f654dbdcdc89e76Douglas Gregor case Sema::TDK_TooFewArguments: 4705f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_Incomplete: 4715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_InvalidExplicitArguments: 4725f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_Inconsistent: 4735f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_Underqualified: 4745f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer return 0; 4752de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 4762de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_SubstitutionFailure: 4772de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return static_cast<TemplateArgumentList*>(Data); 4782de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 4792de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // Unhandled 4802de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_NonDeducedMismatch: 4812de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_FailedOverloadResolution: 4822de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall break; 4832de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } 4842de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 4852de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return 0; 4862de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 4872de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 4885f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerconst TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 4895f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 4905f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_Success: 4912de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_InstantiationDepth: 492bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_Incomplete: 493bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_TooManyArguments: 494bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_TooFewArguments: 4952de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_InvalidExplicitArguments: 4962de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_SubstitutionFailure: 4972de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return 0; 4982de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 4992de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_Inconsistent: 5002de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_Underqualified: 5012de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 5022de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 503bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor // Unhandled 504bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_NonDeducedMismatch: 505bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_FailedOverloadResolution: 506bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor break; 507bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor } 5082de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 5092de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return 0; 5102de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 5112de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 5122de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallconst TemplateArgument * 5132de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallOverloadCandidate::DeductionFailureInfo::getSecondArg() { 5142de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 5152de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall case Sema::TDK_Success: 516bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_InstantiationDepth: 517bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_Incomplete: 518bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_TooManyArguments: 519bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_TooFewArguments: 520bc736fceca6f0bca31d16003a7587857190408fbDouglas Gregor case Sema::TDK_InvalidExplicitArguments: 5215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_SubstitutionFailure: 5225f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer return 0; 5235f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer 5245f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer case Sema::TDK_Inconsistent: 525668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek case Sema::TDK_Underqualified: 5268189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 5271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump 528898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor // Unhandled 529d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner case Sema::TDK_NonDeducedMismatch: 530898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor case Sema::TDK_FailedOverloadResolution: 5311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump break; 532668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek } 533b4609806e9232593ece09ce08b630836e825865cDouglas Gregor 534b4609806e9232593ece09ce08b630836e825865cDouglas Gregor return 0; 535b4609806e9232593ece09ce08b630836e825865cDouglas Gregor} 536668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek 537b4609806e9232593ece09ce08b630836e825865cDouglas Gregorvoid OverloadCandidateSet::clear() { 538b4609806e9232593ece09ce08b630836e825865cDouglas Gregor inherited::clear(); 539e2ce1d9440186cf3332368291cd884a6e3ae8946Nate Begeman Functions.clear(); 540668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek} 541668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek 542898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor// IsOverload - Determine whether the given New declaration is an 543898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor// overload of the declarations in Old. This routine returns false if 544d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner// New and Old cannot be overloaded, e.g., if New has the same 545898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor// signature as some function in Old (C++ 1.3.10) or if the Old 546668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek// declarations aren't functions (or function templates) at all. When 547668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek// it does return false, MatchedDecl will point to the decl that New 54877ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek// cannot be overloaded with. This decl may be a UsingShadowDecl on 5495f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// top of the underlying declaration. 55077ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek// 551668bf91d31265b6ea8c3eb854ba450857701f269Ted Kremenek// Example: Given the following input: 5525f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// 5535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// void f(int, float); // #1 5545f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// void f(int, int); // #2 5551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump// int f(int, int); // #3 5561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump// 5571f0d0133b0e8d1f01f63951ee04927796b34740dDouglas Gregor// When we process #1, there is no previous declaration of "f", 5581f0d0133b0e8d1f01f63951ee04927796b34740dDouglas Gregor// so IsOverload will not be used. 5591f0d0133b0e8d1f01f63951ee04927796b34740dDouglas Gregor// 560d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes// When we process #2, Old contains only the FunctionDecl for #1. By 561a00425414e8c209cabc25d1826b200aeb94259afZhongxing Xu// comparing the parameter types, we see that #1 and #2 are overloaded 5626346f963145ed18b6edf50a78753b47db505e912Chris Lattner// (since they have different signatures), so this routine returns 563d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes// false; MatchedDecl is unchanged. 564cb1c77f90d4e747b83a0d0cc125dc01567378f82Nuno Lopes// 565cb1c77f90d4e747b83a0d0cc125dc01567378f82Nuno Lopes// When we process #3, Old is an overload set containing #1 and #2. We 566a00425414e8c209cabc25d1826b200aeb94259afZhongxing Xu// compare the signatures of #3 to #1 (they're overloaded, so we do 567a00425414e8c209cabc25d1826b200aeb94259afZhongxing Xu// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 568a00425414e8c209cabc25d1826b200aeb94259afZhongxing Xu// identical (return types of functions are not part of the 569a00425414e8c209cabc25d1826b200aeb94259afZhongxing Xu// signature), IsOverload returns false and MatchedDecl will be set to 570d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes// point to the FunctionDecl for #2. 571caabf9bf331156e96dacb072385901fdfa057ec1Chris Lattner// 572d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 573d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes// into a class by a using declaration. The rules for whether to hide 574d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner// shadow declarations ignore some properties which otherwise figure 575d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner// into a function template's signature. 576d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris LattnerSema::OverloadKind 5778189cde56b4f6f938cd65f53c932fe1860d0204cTed KremenekSema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 578d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner NamedDecl *&Match, bool NewIsUsingDecl) { 579d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner for (LookupResult::iterator I = Old.begin(), E = Old.end(); 5801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump I != E; ++I) { 581d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner NamedDecl *OldD = *I; 582d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner 583d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner bool OldIsUsingDecl = false; 584d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner if (isa<UsingShadowDecl>(OldD)) { 585d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner OldIsUsingDecl = true; 586d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner 587d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner // We can always introduce two using declarations into the same 58868a049cab6015a7437bec5661601b7d37d23c70cDaniel Dunbar // context, even if they have identical signatures. 589d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner if (NewIsUsingDecl) continue; 590d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner 591d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 592d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner } 593d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner 594d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner // If either declaration was introduced by a using declaration, 5951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // we'll need to use slightly different rules for matching. 59688c9a46f0b84f1ee83e01917825346551ee540d0Douglas Gregor // Essentially, these rules are the normal rules, except that 597d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner // function templates hide function templates with different 598d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner // return types or template parameter lists. 599d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner bool UseMemberUsingDeclRules = 600d18b3299debb7b0dbd9d34d9369189dc98c87f53Chris Lattner (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 601cb888967400a03504c88acedd5248d6778a82f46Chris Lattner 602cb888967400a03504c88acedd5248d6778a82f46Chris Lattner if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 6033c385e5f8d9008fff18597ca302be19fa86e51f6Douglas Gregor if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 604c4f8e8b645b8e0e685c089dde0674c6f29a24168Steve Naroff if (UseMemberUsingDeclRules && OldIsUsingDecl) { 6051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 606c4f8e8b645b8e0e685c089dde0674c6f29a24168Steve Naroff continue; 607c4f8e8b645b8e0e685c089dde0674c6f29a24168Steve Naroff } 608c4f8e8b645b8e0e685c089dde0674c6f29a24168Steve Naroff 609cb888967400a03504c88acedd5248d6778a82f46Chris Lattner Match = *I; 6101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump return Ovl_Match; 611c4f8e8b645b8e0e685c089dde0674c6f29a24168Steve Naroff } 612c4f8e8b645b8e0e685c089dde0674c6f29a24168Steve Naroff } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 613cb888967400a03504c88acedd5248d6778a82f46Chris Lattner if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump if (UseMemberUsingDeclRules && OldIsUsingDecl) { 615bcba201a1118d7852b8b97187d495ae2a4f49519Anders Carlsson HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 616bcba201a1118d7852b8b97187d495ae2a4f49519Anders Carlsson continue; 617cb888967400a03504c88acedd5248d6778a82f46Chris Lattner } 6181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump 6194fcd399a52ae45ed8ebfdd3a25e01cfb76fa366dDouglas Gregor Match = *I; 6204fcd399a52ae45ed8ebfdd3a25e01cfb76fa366dDouglas Gregor return Ovl_Match; 6214fcd399a52ae45ed8ebfdd3a25e01cfb76fa366dDouglas Gregor } 6227814e6d6645d587891293d59ecf6576defcfac92Douglas Gregor } else if (isa<UsingDecl>(OldD)) { 623cb888967400a03504c88acedd5248d6778a82f46Chris Lattner // We can overload with these, which can show up when doing 624bcba201a1118d7852b8b97187d495ae2a4f49519Anders Carlsson // redeclaration checks for UsingDecls. 6256dde78f744382a5627a04f984a97049e0c4b5e73Anders Carlsson assert(Old.getLookupKind() == LookupUsingDeclName); 6266dde78f744382a5627a04f984a97049e0c4b5e73Anders Carlsson } else if (isa<TagDecl>(OldD)) { 6276217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek // We can always overload with tags by hiding them. 6286dde78f744382a5627a04f984a97049e0c4b5e73Anders Carlsson } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 6296217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek // Optimistically assume that an unresolved using decl will 6306dde78f744382a5627a04f984a97049e0c4b5e73Anders Carlsson // overload; if it doesn't, we'll have to diagnose during 6315291c3cec0dbe8ad1d8e7e67e93af2b1586d5400Douglas Gregor // template instantiation. 6325291c3cec0dbe8ad1d8e7e67e93af2b1586d5400Douglas Gregor } else { 6335291c3cec0dbe8ad1d8e7e67e93af2b1586d5400Douglas Gregor // (C++ 13p1): 6345291c3cec0dbe8ad1d8e7e67e93af2b1586d5400Douglas Gregor // Only function declarations can be overloaded; object and type 635183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall // declarations cannot be overloaded. 6366dde78f744382a5627a04f984a97049e0c4b5e73Anders Carlsson Match = *I; 6376dde78f744382a5627a04f984a97049e0c4b5e73Anders Carlsson return Ovl_NonFunction; 638cb888967400a03504c88acedd5248d6778a82f46Chris Lattner } 639c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt } 6408ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 641c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return Ovl_Overload; 642c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt} 6438ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 6448ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregorbool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 6458ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor bool UseUsingDeclRules) { 646c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // If both of the functions are extern "C", then they are not 6478ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // overloads. 6488ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor if (Old->isExternC() && New->isExternC()) 6498ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor return false; 6508ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 6518ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 6528ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 6538ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 6548ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // C++ [temp.fct]p2: 6558ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // A function template can be overloaded with other function templates 6568ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // and with normal (non-template) functions. 6578ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor if ((OldTemplate == 0) != (NewTemplate == 0)) 6588ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor return true; 6598ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 6608ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // Is the function New an overload of the function Old? 661c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt QualType OldQType = Context.getCanonicalType(Old->getType()); 6628ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor QualType NewQType = Context.getCanonicalType(New->getType()); 663c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt 6648ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // Compare the signatures (C++ 1.3.10) of the two functions to 6658ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // determine whether they are overloads. If we find any mismatch 666c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // in the signature, they are overloads. 6678ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 6688ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // If either of these functions is a K&R-style function (no 6698ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // prototype), then we consider them to have matching signatures. 670c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 671c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt isa<FunctionNoProtoType>(NewQType.getTypePtr())) 6728ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor return false; 6738ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 6748ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 6758ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 676c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt 6778ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // The signature of a function includes the types of its 6788ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // parameters (C++ 1.3.10), which includes the presence or absence 6798ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // of the ellipsis; see C++ DR 357). 6808ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor if (OldQType != NewQType && 6818ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor (OldType->getNumArgs() != NewType->getNumArgs() || 6828ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor OldType->isVariadic() != NewType->isVariadic() || 6838ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor !FunctionArgTypesAreEqual(OldType, NewType))) 6848ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor return true; 6858ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 686c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // C++ [temp.over.link]p4: 6878ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // The signature of a function template consists of its function 6888ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // signature, its return type and its template parameter list. The names 6898ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // of the template parameters are significant only for establishing the 6901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // relationship between the template parameters and the rest of the 6911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // signature. 69283f6faf37d9bf58986bedc9bc0ea897a56b4dbadDouglas Gregor // 693f595cc41c4d95fe323f8a2b209523de9956f874dEli Friedman // We check the return type and template parameter lists for function 694161755a09898c95d21bfff33707da9ca41cd53c5John McCall // templates first; the remaining checks follow. 6952577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // 696d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall // However, we don't consider either of these when deciding whether 697c4bf26fbdff42967d660f505a83f75a4df2cc752Douglas Gregor // a member introduced by a shadow declaration is hidden. 69883f6faf37d9bf58986bedc9bc0ea897a56b4dbadDouglas Gregor if (!UseUsingDeclRules && NewTemplate && 6996bb8017bb9e828d118e15e59d71c66bba323c364John McCall (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 700161755a09898c95d21bfff33707da9ca41cd53c5John McCall OldTemplate->getTemplateParameters(), 701161755a09898c95d21bfff33707da9ca41cd53c5John McCall false, TPL_TemplateMatch) || 702161755a09898c95d21bfff33707da9ca41cd53c5John McCall OldType->getResultType() != NewType->getResultType())) 7036bb8017bb9e828d118e15e59d71c66bba323c364John McCall return true; 7046bb8017bb9e828d118e15e59d71c66bba323c364John McCall 7051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // If the function is a class member, its signature includes the 706d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 707d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall // 7081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // As part of this, also check whether one of the member functions 70983f6faf37d9bf58986bedc9bc0ea897a56b4dbadDouglas Gregor // is static, in which case they are not overloads (C++ 7102577743c5650c646fb705df01403707e94f2df04Abramo Bagnara // 13.1p2). While not part of the definition of the signature, 7116bb8017bb9e828d118e15e59d71c66bba323c364John McCall // this check is important to determine whether these functions 7126bb8017bb9e828d118e15e59d71c66bba323c364John McCall // can be overloaded. 7136bb8017bb9e828d118e15e59d71c66bba323c364John McCall CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 7146bb8017bb9e828d118e15e59d71c66bba323c364John McCall CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 7156bb8017bb9e828d118e15e59d71c66bba323c364John McCall if (OldMethod && NewMethod && 7166bb8017bb9e828d118e15e59d71c66bba323c364John McCall !OldMethod->isStatic() && !NewMethod->isStatic() && 7176bb8017bb9e828d118e15e59d71c66bba323c364John McCall (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 7186bb8017bb9e828d118e15e59d71c66bba323c364John McCall OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 7196bb8017bb9e828d118e15e59d71c66bba323c364John McCall if (!UseUsingDeclRules && 7206bb8017bb9e828d118e15e59d71c66bba323c364John McCall OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 7216bb8017bb9e828d118e15e59d71c66bba323c364John McCall (OldMethod->getRefQualifier() == RQ_None || 7226bb8017bb9e828d118e15e59d71c66bba323c364John McCall NewMethod->getRefQualifier() == RQ_None)) { 7236bb8017bb9e828d118e15e59d71c66bba323c364John McCall // C++0x [over.load]p2: 7246bb8017bb9e828d118e15e59d71c66bba323c364John McCall // - Member function declarations with the same name and the same 7256bb8017bb9e828d118e15e59d71c66bba323c364John McCall // parameter-type-list as well as member function template 7266bb8017bb9e828d118e15e59d71c66bba323c364John McCall // declarations with the same name, the same parameter-type-list, and 727096832c5ed5b9106fa177ebc148489760c3bc496John McCall // the same template parameter lists cannot be overloaded if any of 7286bb8017bb9e828d118e15e59d71c66bba323c364John McCall // them, but not all, have a ref-qualifier (8.3.5). 7296bb8017bb9e828d118e15e59d71c66bba323c364John McCall Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 7306bb8017bb9e828d118e15e59d71c66bba323c364John McCall << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 73183f6faf37d9bf58986bedc9bc0ea897a56b4dbadDouglas Gregor Diag(OldMethod->getLocation(), diag::note_previous_declaration); 73283f6faf37d9bf58986bedc9bc0ea897a56b4dbadDouglas Gregor } 733f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson 734f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson return true; 7352de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } 736f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson 7372de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // The signatures match; this is not an overload. 738f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson return false; 7392de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 740e39a3894513349908cdb3beba2614e53cb288e6cDouglas Gregor 7412de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// \brief Checks availability of the function depending on the current 742f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// function context. Inside an unavailable function, unavailability is ignored. 7432de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// 74411de6de25a0110cd7be97eef761ef3b189781da6Anders Carlsson/// \returns true if \arg FD is unavailable and current context is inside 7452de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// an available function, false otherwise. 746f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlssonbool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 7472de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 74823cba801e11b03929c44f8cf54578305963a3476John McCall} 7492de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 750f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// TryImplicitConversion - Attempt to perform an implicit conversion 7512de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// from the given expression (Expr) to the given type (ToType). This 752f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// function returns an implicit conversion sequence that can be used 7532de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// to perform the initialization. Given 754f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// 7552de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// void f(float f); 756f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// void g(int i) { f(i); } 7572de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// 758f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// this routine would produce an implicit conversion sequence to 7592de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// describe the initialization of f from i, which will be a standard 760f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 7612de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// 4.1) followed by a floating-integral conversion (C++ 4.9). 7621a31a18db9d657751f38c724adc0d62e86852bd7Anders Carlsson// 7632de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// Note that this routine only determines how the conversion can be 764f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// performed; it does not actually perform the conversion. As such, 7652de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// it will not produce any diagnostics if no conversion is available, 766f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson/// but will instead return an implicit conversion sequence of kind 7672de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// "BadConversion". 7687f9e646b7ed47bc8e9a60031ad0c2b55031e2077Anders Carlsson/// 7692de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// If @p SuppressUserConversions, then user-defined conversions are 7707f9e646b7ed47bc8e9a60031ad0c2b55031e2077Anders Carlsson/// not permitted. 7712de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// If @p AllowExplicit, then explicit user-defined conversions are 772ebeaf2031c968143c531bfe232d7507f20c57347Anders Carlsson/// permitted. 7732de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// 77416a8904f3f5ed19158657e1da95e5902fbee66f7Anders Carlsson/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 7752de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// writeback conversion, which allows __autoreleasing id* parameters to 77682debc7d282e723e58d183bfa89ddc2500a8daafAnders Carlsson/// be initialized with __strong id* or __weak id* arguments. 7772de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallstatic ImplicitConversionSequence 77882debc7d282e723e58d183bfa89ddc2500a8daafAnders CarlssonTryImplicitConversion(Sema &S, Expr *From, QualType ToType, 7792de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool SuppressUserConversions, 78082debc7d282e723e58d183bfa89ddc2500a8daafAnders Carlsson bool AllowExplicit, 7812de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool InOverloadResolution, 782c6b29163557d02da5d2a4a06f986f0480291f51fBenjamin Kramer bool CStyle, 7832de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool AllowObjCWritebackConversion) { 784bc0e0781da778bd5eb41a810419912893ae20448Anders Carlsson ImplicitConversionSequence ICS; 7852de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (IsStandardConversion(S, From, ToType, InOverloadResolution, 7864cbf9d43cc47bb7a070c5c5026521d7d6a8f73c7Fariborz Jahanian ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 7872de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall ICS.setStandard(); 7883b27f1a80e4e433b503efd344c909eeafaa9033cFariborz Jahanian return ICS; 7892de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } 790569c3166874324c24011f8ade6978421f0d39b3cDouglas Gregor 791f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson if (!S.getLangOptions().CPlusPlus) { 7921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 793f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson return ICS; 794f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson } 795f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson 796f8ec55a104e55961f8666f773dce99bbc628298fAnders Carlsson // C++ [over.ics.user]p4: 7976eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // A conversion of an expression of class type to the same class 7986eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // type is given Exact Match rank, and a conversion of an 7996eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // expression of class type to a base class of that type is 8006eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // given Conversion rank, in spite of the fact that a copy/move 8016eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // constructor (i.e., a user-defined conversion function) is 802c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // called for those cases. 8036eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor QualType FromType = From->getType(); 8046eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 8056eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor (S.Context.hasSameUnqualifiedType(FromType, ToType) || 806c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt S.IsDerivedFrom(FromType, ToType))) { 8076eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor ICS.setStandard(); 8086eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor ICS.Standard.setAsIdentityConversion(); 8092de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall ICS.Standard.setFromType(FromType); 8106eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor ICS.Standard.setAllToTypes(ToType); 8112de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 8126eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // We don't actually check at this point whether there is a valid 813c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // copy/move constructor, since overloading just assumes that it 8146eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // exists. When we actually perform initialization, we'll find the 8156eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // appropriate constructor to copy the returned object, if needed. 816c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ICS.Standard.CopyConstructor = 0; 817c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt 8186eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // Determine whether this is considered a derived-to-base conversion. 8196eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 8206eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor ICS.Standard.Second = ICK_Derived_To_Base; 821f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall 822f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall return ICS; 823f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall } 824f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall 825f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall if (SuppressUserConversions) { 826f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // We're not in the case above, so there is no conversion that 827f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // we can perform. 828f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 829f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall return ICS; 830f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall } 831f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall 832f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // Attempt user-defined conversion. 833f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall OverloadCandidateSet Conversions(From->getExprLoc()); 834f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall OverloadingResult UserDefResult 835f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 836f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall AllowExplicit); 837f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall 838f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall if (UserDefResult == OR_Success) { 839f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.setUserDefined(); 840f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // C++ [over.ics.user]p4: 841f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // A conversion of an expression of class type to the same class 842f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // type is given Exact Match rank, and a conversion of an 8435baba9d98364a3525d6afa15a04cdad82fd6dd30John McCall // expression of class type to a base class of that type is 844f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // given Conversion rank, in spite of the fact that a copy 845f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // constructor (i.e., a user-defined conversion function) is 846f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // called for those cases. 847f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall if (CXXConstructorDecl *Constructor 8485baba9d98364a3525d6afa15a04cdad82fd6dd30John McCall = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 849f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall QualType FromCanon 850f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 851f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall QualType ToCanon 852f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 853f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall if (Constructor->isCopyConstructor() && 854f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 855f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // Turn this into a "standard" conversion sequence, so that it 856f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // gets ranked with standard conversion sequences. 857f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.setStandard(); 858f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Standard.setAsIdentityConversion(); 859f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Standard.setFromType(From->getType()); 860f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Standard.setAllToTypes(ToType); 861f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Standard.CopyConstructor = Constructor; 862f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall if (ToCanon != FromCanon) 863f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Standard.Second = ICK_Derived_To_Base; 864f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall } 865f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall } 866f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall 867f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // C++ [over.best.ics]p4: 868f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // However, when considering the argument of a user-defined 869f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // conversion function that is a candidate by 13.3.1.3 when 870f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // invoked for the copying of the temporary in the second step 871f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 872f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // 13.3.1.6 in all cases, only standard conversion sequences and 873f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall // ellipsis conversion sequences are allowed. 874f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall if (SuppressUserConversions && ICS.isUserDefined()) { 875f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 876f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall } 877f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 878f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.setAmbiguous(); 879f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Ambiguous.setFromType(From->getType()); 880f871d0cc377a1367b519a6cce26be74607566ebaJohn McCall ICS.Ambiguous.setToType(ToType); 8815f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 8825f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer Cand != Conversions.end(); ++Cand) 8835f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer if (Cand->Viable) 8845f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer ICS.Ambiguous.addConversion(Cand->Function); 8852de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } else { 8862de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 8872de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } 8882de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 8892de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return ICS; 8902de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 8912de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 8922de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallImplicitConversionSequence 8932de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallSema::TryImplicitConversion(Expr *From, QualType ToType, 8942de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool SuppressUserConversions, 8952de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool AllowExplicit, 8962de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool InOverloadResolution, 8972de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool CStyle, 8982de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool AllowObjCWritebackConversion) { 8992de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return clang::TryImplicitConversion(*this, From, ToType, 9002de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall SuppressUserConversions, AllowExplicit, 9012de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall InOverloadResolution, CStyle, 9022de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall AllowObjCWritebackConversion); 9032de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 9042de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 9052de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// PerformImplicitConversion - Perform an implicit conversion of the 9062de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// expression From to the type ToType. Returns the 9072de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// converted expression. Flavor is the kind of conversion we're 9082de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// performing, used in the error message. If @p AllowExplicit, 9092de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// explicit user-defined conversions are permitted. 9102de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallExprResult 9112de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallSema::PerformImplicitConversion(Expr *From, QualType ToType, 9122de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall AssignmentAction Action, bool AllowExplicit) { 9132de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall ImplicitConversionSequence ICS; 9142de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 9152de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 9162de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 9175f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid SpencerExprResult 918baf534875ed0a55c6342636ff3f4602b8ac22b69Douglas GregorSema::PerformImplicitConversion(Expr *From, QualType ToType, 919baf534875ed0a55c6342636ff3f4602b8ac22b69Douglas Gregor AssignmentAction Action, bool AllowExplicit, 9205f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer ImplicitConversionSequence& ICS) { 9215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer // Objective-C ARC: Determine whether we will allow the writeback conversion. 9222de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool AllowObjCWritebackConversion 923063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor = getLangOptions().ObjCAutoRefCount && 924063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor (Action == AA_Passing || Action == AA_Sending); 925b7beee9f2b52f34a3b0800a5f0038f0e4295b260Chris Lattner 9262de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 9272de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall ICS = clang::TryImplicitConversion(*this, From, ToType, 9282de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall /*SuppressUserConversions=*/false, 9292de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall AllowExplicit, 9302de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall /*InOverloadResolution=*/false, 9312de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall /*CStyle=*/false, 9322de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall AllowObjCWritebackConversion); 9332de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return PerformImplicitConversion(From, ToType, ICS, Action); 9342de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall} 9352de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 9362de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// \brief Determine whether the conversion from FromType to ToType is a valid 9372de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall/// conversion that strips "noreturn" off the nested function type. 9382de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCallbool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 9392de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall QualType &ResultTy) { 9402de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (Context.hasSameUnqualifiedType(FromType, ToType)) 9412de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return false; 9422de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 9432de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 9442de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // where F adds one of the following at most once: 9452de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // - a pointer 9462de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // - a member pointer 9472de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // - a block pointer 9482de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall CanQualType CanTo = Context.getCanonicalType(ToType); 9492de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall CanQualType CanFrom = Context.getCanonicalType(FromType); 9502de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall Type::TypeClass TyClass = CanTo->getTypeClass(); 9512de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (TyClass != CanFrom->getTypeClass()) return false; 9522de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 9532de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (TyClass == Type::Pointer) { 9542de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 9552de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 9562de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } else if (TyClass == Type::BlockPointer) { 957063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 958063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 959063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor } else if (TyClass == Type::MemberPointer) { 960063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 961063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 962063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor } else { 963063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor return false; 964063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor } 965063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor 966063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor TyClass = CanTo->getTypeClass(); 967063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor if (TyClass != CanFrom->getTypeClass()) return false; 968063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 969063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor return false; 970063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor } 971063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor 972063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor const FunctionType *FromFn = cast<FunctionType>(CanFrom); 973063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 974063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor if (!EInfo.getNoReturn()) return false; 975063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor 976063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 977063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor assert(QualType(FromFn, 0).isCanonical()); 978063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor if (QualType(FromFn, 0) != CanTo) return false; 979063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor 980063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor ResultTy = ToType; 981063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor return true; 982063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor} 983063daf6e196c51f162e0485478355d8e280eef5cDouglas Gregor 984709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek/// \brief Determine whether the conversion from FromType to ToType is a valid 985418f6c7d142e5ff4607f70cd8431d008442bafe9Chris Lattner/// vector conversion. 9864c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor/// 98773460a32bc5299a5927d23d2e464d72af796eabfDouglas Gregor/// \param ICK Will be set to the vector conversion kind, if this is a vector 988709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek/// conversion. 9891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpstatic bool IsVectorConversion(ASTContext &Context, QualType FromType, 990c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt QualType ToType, ImplicitConversionKind &ICK) { 991c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // We need at least one of these types to be a vector type to have a vector 992ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek // conversion. 993ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek if (!ToType->isVectorType() && !FromType->isVectorType()) 99473460a32bc5299a5927d23d2e464d72af796eabfDouglas Gregor return false; 995ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek 99673460a32bc5299a5927d23d2e464d72af796eabfDouglas Gregor // Identical types require no conversions. 99773460a32bc5299a5927d23d2e464d72af796eabfDouglas Gregor if (Context.hasSameUnqualifiedType(FromType, ToType)) 998c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return false; 999709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek 100066b5a8a39088598c01a9fa6f032dc908612dc8ecAnders Carlsson // There are no conversions between extended vector types, only identity. 10015f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer if (ToType->isExtVectorType()) { 1002709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek // There are no conversions between extended vector types other than the 1003ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek // identity conversion. 1004709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek if (FromType->isExtVectorType()) 1005fa2192042f223b5122a9e17719930f77634fd31fDouglas Gregor return false; 1006fa2192042f223b5122a9e17719930f77634fd31fDouglas Gregor 1007709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek // Vector splat from any arithmetic type to a vector. 1008709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek if (FromType->isArithmeticType()) { 10094c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor ICK = ICK_Vector_Splat; 10104c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor return true; 1011709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek } 1012ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek } 1013709210feee317b8d6690dd1d15c2b74cfe55e261Ted Kremenek 1014ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek // We can perform the conversion between vector types in the following cases: 1015ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek // 1)vector types are equivalent AltiVec and GCC vector types 10164c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor // 2)lax vector conversions are permitted and the vector types are of the 10171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // same size 10184c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor if (ToType->isVectorType() && FromType->isVectorType()) { 10194c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor if (Context.areCompatibleVectorTypes(FromType, ToType) || 10204c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor (Context.getLangOptions().LaxVectorConversions && 10214c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 10224c67834407ca6ab344dcf44fc599ad4938cfa96dDouglas Gregor ICK = ICK_Vector_Conversion; 1023bfdcae678d44906293e21c0cddc6537f3ee8b5a4Steve Naroff return true; 10244eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff } 10254eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff } 10266217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek 1027183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall return false; 10284eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff} 10294eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff 10301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// IsStandardConversion - Determines whether there is a standard 10311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 103256ee6896f2efebffb4a2cce5a7610cdf1eddbbbeSteve Naroff/// expression From to the type ToType. Standard conversion sequences 10331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// only consider non-class types; for conversions that involve class 10347297134f128423fce2e88f92421ed135bded7d4eDouglas Gregor/// types, use TryImplicitConversion. If a conversion exists, SCS will 10357297134f128423fce2e88f92421ed135bded7d4eDouglas Gregor/// contain the standard conversion sequence required to perform this 10361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// conversion and this routine will return true. Otherwise, this 10371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// routine will return false and the value of SCS is unspecified. 10387297134f128423fce2e88f92421ed135bded7d4eDouglas Gregorstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 103956ee6896f2efebffb4a2cce5a7610cdf1eddbbbeSteve Naroff bool InOverloadResolution, 104056ee6896f2efebffb4a2cce5a7610cdf1eddbbbeSteve Naroff StandardConversionSequence &SCS, 10415f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer bool CStyle, 10425f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer bool AllowObjCWritebackConversion) { 10435f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer QualType FromType = From->getType(); 10445f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer 1045026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // Standard conversions (C++ [conv]) 1046026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.setAsIdentityConversion(); 1047026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.DeprecatedStringLiteralToCharPtr = false; 1048026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.IncompatibleObjC = false; 1049026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.setFromType(FromType); 1050df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump SCS.CopyConstructor = 0; 1051ffce2df6ae280d354d51371282a579df1eb86876Anders Carlsson 1052ffce2df6ae280d354d51371282a579df1eb86876Anders Carlsson // There are no standard conversions for class types in C++, so 1053ffce2df6ae280d354d51371282a579df1eb86876Anders Carlsson // abort early. When overloading in C, however, we do permit 1054ffce2df6ae280d354d51371282a579df1eb86876Anders Carlsson if (FromType->isRecordType() || ToType->isRecordType()) { 10551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump if (S.getLangOptions().CPlusPlus) 10565f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer return false; 10575f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer 10580faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall // When we're overloading in C, we allow, as standard conversions, 10590faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall } 1060026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner 1061026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // The first conversion can be an lvalue-to-rvalue conversion, 1062026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // array-to-pointer conversion, or function-to-pointer conversion 10635f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer // (C++ 4p1). 1064026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner 1065df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump if (FromType == S.Context.OverloadTy) { 10665f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer DeclAccessPair AccessPair; 10675f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer if (FunctionDecl *Fn 10681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 10695f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer AccessPair)) { 1070026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // We were able to resolve the address of the overloaded function, 10712de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // so we can convert to the type of that function. 10722de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall FromType = Fn->getType(); 10732de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 10742de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // we can sometimes resolve &foo<int> regardless of ToType, so check 1075026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // if the type matches (identity) or we are converting to bool 10762de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (!S.Context.hasSameUnqualifiedType( 10775f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1078df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump QualType resultTy; 1079026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // if the function type matches except for [[noreturn]], it's ok 1080026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner if (!S.IsNoReturnConversion(FromType, 10812de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 10822de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // otherwise, only a boolean conversion is standard 10835f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer if (!ToType->isBooleanType()) 1084df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump return false; 1085df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump } 1086026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner 1087026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // Check if the "from" expression is taking the address of an overloaded 10882de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // function and recompute the FromType accordingly. Take advantage of the 1089df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump // fact that non-static member functions *must* have such an address-of 10905f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer // expression. 1091026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1092026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner if (Method && !Method->isStatic()) { 1093026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner assert(isa<UnaryOperator>(From->IgnoreParens()) && 10945f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer "Non-unary operator on non-static member address"); 1095e7716e6133e23e4a89248a65a388bc840d8c130cChris Lattner assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1096026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner == UO_AddrOf && 1097c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek "Non-address-of operator on non-static member address"); 1098c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek const Type *ClassType 1099c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 110025973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis FromType = S.Context.getMemberPointerType(FromType, ClassType); 110125973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis } else if (isa<UnaryOperator>(From->IgnoreParens())) { 11022de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1103c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek UO_AddrOf && 1104c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek "Non-address-of operator for overloaded function expression"); 1105c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek FromType = S.Context.getPointerType(FromType); 1106c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek } 1107c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek 1108c46a246f5fb00bf8448a1081e7d7e73bb6dbfbf5Ted Kremenek // Check that we've computed the proper type after overload resolution. 110925973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis assert(S.Context.hasSameType( 111025973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis FromType, 11112de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 11122de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } else { 111325973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis return false; 111425973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis } 111525973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis } 111625973455aed1cdc9c40b208c792b5db4f8f1297dArgyrios Kyrtzidis // Lvalue-to-rvalue conversion (C++ 4.1): 1117bf0ee354163f87623a4b60412544243911332343John McCall // An lvalue (3.10) of a non-function, non-array type T can be 1118026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // converted to an rvalue. 1119026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner bool argIsLValue = From->isLValue(); 1120026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner if (argIsLValue && 1121026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner !FromType->isFunctionType() && !FromType->isArrayType() && 1122026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1123026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.First = ICK_Lvalue_To_Rvalue; 1124e7716e6133e23e4a89248a65a388bc840d8c130cChris Lattner 1125eb14fe839ec24c2ca14e5f094be147a34e3d3339Chris Lattner // If T is a non-class type, the type of the rvalue is the 1126c6dfe194f623b02c123759f235b504d4850fc178Douglas Gregor // cv-unqualified version of T. Otherwise, the type of the rvalue 1127026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 11285f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer // just strip the qualifiers because they don't matter. 1129ab38e4b50268633f037a10841fdfb612513f8d33Fariborz Jahanian FromType = FromType.getUnqualifiedType(); 1130026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner } else if (FromType->isArrayType()) { 1131026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // Array-to-pointer conversion (C++ 4.2) 1132ab38e4b50268633f037a10841fdfb612513f8d33Fariborz Jahanian SCS.First = ICK_Array_To_Pointer; 11331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump 1134df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump // An lvalue or rvalue of type "array of N T" or "array of unknown 1135026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // bound of T" can be converted to an rvalue of type "pointer to 1136df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump // T" (C++ 4.2p1). 1137ab38e4b50268633f037a10841fdfb612513f8d33Fariborz Jahanian FromType = S.Context.getArrayDecayedType(FromType); 1138ab38e4b50268633f037a10841fdfb612513f8d33Fariborz Jahanian 11395f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1140026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // This conversion is deprecated. (C++ D.4). 1141026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.DeprecatedStringLiteralToCharPtr = true; 1142df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump 1143026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // For the purpose of ranking in overload resolution 1144026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // (13.3.3.1.1), this conversion is considered an 1145026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // array-to-pointer conversion followed by a qualification 1146026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // conversion (4.4). (C++ 4.2p2) 1147026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.Second = ICK_Identity; 11481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump SCS.Third = ICK_Qualification; 11495f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer SCS.QualificationIncludesObjCLifetime = false; 11505f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer SCS.setAllToTypes(FromType); 1151026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner return true; 1152df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump } 1153026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner } else if (FromType->isFunctionType() && argIsLValue) { 1154026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // Function-to-pointer conversion (C++ 4.3). 1155026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.First = ICK_Function_To_Pointer; 1156026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner 1157026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // An lvalue of function type T can be converted to an rvalue of 1158211f6adf1301a1461015fb6cb08a05f0a35b65f3Eli Friedman // type "pointer to T." The result is a pointer to the 11595f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer // function. (C++ 4.3p1). 1160852871abbff45f1c1d3787755a27fce08365b166Eli Friedman FromType = S.Context.getPointerType(FromType); 1161852871abbff45f1c1d3787755a27fce08365b166Eli Friedman } else { 1162026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // We don't require any conversions for the first step. 1163026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.First = ICK_Identity; 1164d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes } 1165026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.setToType(0, FromType); 1166026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner 1167bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // The second conversion can be an integral promotion, floating 1168bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // point promotion, integral conversion, floating point conversion, 1169bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // floating-integral conversion, pointer conversion, 1170bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1171bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // For overloading in C, this can also be a "compatible-type" 1172bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // conversion. 1173bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner bool IncompatibleObjC = false; 1174bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner ImplicitConversionKind SecondICK = ICK_Identity; 1175bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1176bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // The unqualified versions of the types are the same: there's no 1177bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner // conversion to do. 1178bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner SCS.Second = ICK_Identity; 1179bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1180026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // Integral promotion (C++ 4.5). 1181026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.Second = ICK_Integral_Promotion; 1182026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner FromType = ToType.getUnqualifiedType(); 118358beed91d468863b8c85bce43425422703838d27Anders Carlsson } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 118458beed91d468863b8c85bce43425422703838d27Anders Carlsson // Floating point promotion (C++ 4.6). 118558beed91d468863b8c85bce43425422703838d27Anders Carlsson SCS.Second = ICK_Floating_Promotion; 118658beed91d468863b8c85bce43425422703838d27Anders Carlsson FromType = ToType.getUnqualifiedType(); 118758beed91d468863b8c85bce43425422703838d27Anders Carlsson } else if (S.IsComplexPromotion(FromType, ToType)) { 1188f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian // Complex promotion (Clang extension) 1189f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian SCS.Second = ICK_Complex_Promotion; 1190f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian FromType = ToType.getUnqualifiedType(); 1191f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian } else if (ToType->isBooleanType() && 1192f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian (FromType->isArithmeticType() || 1193f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian FromType->isAnyPointerType() || 1194f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian FromType->isBlockPointerType() || 1195026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner FromType->isMemberPointerType() || 1196f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian FromType->isNullPtrType())) { 11971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // Boolean conversions (C++ 4.12). 119809105f52b1f28cbb1374c27c3c70f5517e2c465dFariborz Jahanian SCS.Second = ICK_Boolean_Conversion; 1199a50089ec68a583d13718107c1b0c898f0903709eChris Lattner FromType = S.Context.BoolTy; 12001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump } else if (FromType->isIntegralOrUnscopedEnumerationType() && 120109105f52b1f28cbb1374c27c3c70f5517e2c465dFariborz Jahanian ToType->isIntegralType(S.Context)) { 1202a50089ec68a583d13718107c1b0c898f0903709eChris Lattner // Integral conversions (C++ 4.7). 1203154440e6a8fa6ac5bca395876d79b530b39a2c1cFariborz Jahanian SCS.Second = ICK_Integral_Conversion; 1204154440e6a8fa6ac5bca395876d79b530b39a2c1cFariborz Jahanian FromType = ToType.getUnqualifiedType(); 1205154440e6a8fa6ac5bca395876d79b530b39a2c1cFariborz Jahanian } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1206154440e6a8fa6ac5bca395876d79b530b39a2c1cFariborz Jahanian // Complex conversions (C99 6.3.1.6) 12075e94a0d82b1f49be41c35a73106b219e3f588c8cChris Lattner SCS.Second = ICK_Complex_Conversion; 12085e94a0d82b1f49be41c35a73106b219e3f588c8cChris Lattner FromType = ToType.getUnqualifiedType(); 12095e94a0d82b1f49be41c35a73106b219e3f588c8cChris Lattner } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1210a50089ec68a583d13718107c1b0c898f0903709eChris Lattner (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1211a50089ec68a583d13718107c1b0c898f0903709eChris Lattner // Complex-real conversions (C99 6.3.1.7) 1212a50089ec68a583d13718107c1b0c898f0903709eChris Lattner SCS.Second = ICK_Complex_Real; 1213611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner FromType = ToType.getUnqualifiedType(); 1214611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1215611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner // Floating point conversions (C++ 4.8). 1216611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner SCS.Second = ICK_Floating_Conversion; 1217611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner FromType = ToType.getUnqualifiedType(); 1218611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner } else if ((FromType->isRealFloatingType() && 1219611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner ToType->isIntegralType(S.Context)) || 1220611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner (FromType->isIntegralOrUnscopedEnumerationType() && 1221611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner ToType->isRealFloatingType())) { 1222df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump // Floating-integral conversions (C++ 4.9). 12231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump SCS.Second = ICK_Floating_Integral; 12240faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall FromType = ToType.getUnqualifiedType(); 12250faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1226026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.Second = ICK_Block_Pointer_Conversion; 1227026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner } else if (AllowObjCWritebackConversion && 1228026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1229611b2eccaf3869f32de51ecc02985426d1c0aaefChris Lattner SCS.Second = ICK_Writeback_Conversion; 12306eec8e883de118b431e3ead5b1e604a6ac68ff6bDouglas Gregor } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1231fb84664349ca6f37f5ec4df440f6c362cca62470Chris Lattner FromType, IncompatibleObjC)) { 1232fb84664349ca6f37f5ec4df440f6c362cca62470Chris Lattner // Pointer conversions (C++ 4.10). 1233026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.Second = ICK_Pointer_Conversion; 1234fb84664349ca6f37f5ec4df440f6c362cca62470Chris Lattner SCS.IncompatibleObjC = IncompatibleObjC; 1235026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner FromType = FromType.getUnqualifiedType(); 1236026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1237026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner InOverloadResolution, FromType)) { 123858beed91d468863b8c85bce43425422703838d27Anders Carlsson // Pointer to member conversions (4.11). 12390faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall SCS.Second = ICK_Pointer_Member; 12400faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 124158beed91d468863b8c85bce43425422703838d27Anders Carlsson SCS.Second = SecondICK; 1242c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt FromType = ToType.getUnqualifiedType(); 124358beed91d468863b8c85bce43425422703838d27Anders Carlsson } else if (!S.getLangOptions().CPlusPlus && 124458beed91d468863b8c85bce43425422703838d27Anders Carlsson S.Context.typesAreCompatible(ToType, FromType)) { 12452de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // Compatible conversions (Clang extension for C function overloading) 12462de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall SCS.Second = ICK_Compatible_Conversion; 1247df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump FromType = ToType.getUnqualifiedType(); 1248df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1249026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner // Treat a conversion that strips "noreturn" as an identity conversion. 1250026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner SCS.Second = ICK_NoReturn_Adjustment; 1251026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner } else if (IsTransparentUnionStandardConversion(S, From, ToType, 125258beed91d468863b8c85bce43425422703838d27Anders Carlsson InOverloadResolution, 12531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump SCS, CStyle)) { 12544be1f47de20525ad90f02ba8682a7e2cbd3205d1Eli Friedman SCS.Second = ICK_TransparentUnionConversion; 12554be1f47de20525ad90f02ba8682a7e2cbd3205d1Eli Friedman FromType = ToType; 1256df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump } else { 1257df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump // No second conversion required. 12584be1f47de20525ad90f02ba8682a7e2cbd3205d1Eli Friedman SCS.Second = ICK_Identity; 125904421087832a031c90bd58f128c7c0e741db8dd2Chris Lattner } 1260df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump SCS.setToType(1, FromType); 1261df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump 12624c5d320a7581f4b80b151630c91cea5727fa9923Sebastian Redl QualType CanonFrom; 12634c5d320a7581f4b80b151630c91cea5727fa9923Sebastian Redl QualType CanonTo; 12644c5d320a7581f4b80b151630c91cea5727fa9923Sebastian Redl // The third conversion can be a qualification conversion (C++ 4p1). 12654c5d320a7581f4b80b151630c91cea5727fa9923Sebastian Redl bool ObjCLifetimeConversion; 12664c5d320a7581f4b80b151630c91cea5727fa9923Sebastian Redl if (S.IsQualificationConversion(FromType, ToType, CStyle, 1267026dc96ac6ece60da5e1b98e2a71bd0ff0939fd8Chris Lattner ObjCLifetimeConversion)) { 12682d46eb21eb2c904831b0e9f75ab3523384c70e66Anders Carlsson SCS.Third = ICK_Qualification; 1269df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1270df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump FromType = ToType; 12716b1d283fe879fb11d7ce7a69feecf66e77b0eaf3Anders Carlsson CanonFrom = S.Context.getCanonicalType(FromType); 1272df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump CanonTo = S.Context.getCanonicalType(ToType); 1273df317bf71653eeb235da8337b1e8e790f9653aa4Mike Stump } else { 12744c5d320a7581f4b80b151630c91cea5727fa9923Sebastian Redl // No conversion required 12755f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer SCS.Third = ICK_Identity; 12765f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer 127744baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian // C++ [over.best.ics]p6: 12787f4f86a2167abc116275e49c81350fc3225485e5Fariborz Jahanian // [...] Any difference in top-level cv-qualification is 1279102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian // subsumed by the initialization itself and does not constitute 128044baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian // a conversion. [...] 128144baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian CanonFrom = S.Context.getCanonicalType(FromType); 128244baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian CanonTo = S.Context.getCanonicalType(ToType); 128344baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian if (CanonFrom.getLocalUnqualifiedType() 128444baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian == CanonTo.getLocalUnqualifiedType() && 1285207c5210eb0ac7b632609f0c006eb97ef2738948Fariborz Jahanian (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1286102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 128744baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1288102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian FromType = ToType; 128944baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian CanonFrom = CanonTo; 1290102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian } 129106b89124a9a5971a0528cc9da6817740bac43164Fariborz Jahanian } 1292102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian SCS.setToType(2, FromType); 1293a2813cec2605ce7878d1b13471d685f689b251afDouglas Gregor 129444baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian // If we have not converted the argument type to the parameter type, 1295102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian // this is a bad conversion sequence. 1296102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian if (CanonFrom != CanonTo) 1297102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian return false; 1298102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian 129959a53fa3f8ea73bae52ea36d0038f76e9f10729cFariborz Jahanian return true; 130059a53fa3f8ea73bae52ea36d0038f76e9f10729cFariborz Jahanian} 13017e88a60d38b36695520e4f8d9279766ef111a662Daniel Dunbar 13020953e767ff7817f97b3ab20896b229891eeff45bJohn McCallstatic bool 1303102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz JahanianIsTransparentUnionStandardConversion(Sema &S, Expr* From, 130444baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian QualType &ToType, 130544baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian bool InOverloadResolution, 130683f6faf37d9bf58986bedc9bc0ea897a56b4dbadDouglas Gregor StandardConversionSequence &SCS, 130744baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian bool CStyle) { 1308102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian 130944baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian const RecordType *UT = ToType->getAsUnionType(); 131044baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1311102e390bcb5a1fb1a8fdbc8505e6dfd905374bbdFariborz Jahanian return false; 131244baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian // The field to initialize within the transparent union. 131344baa8abba2a1552b6b50bf750a8750ab9da9f76Fariborz Jahanian RecordDecl *UD = UT->getDecl(); 13144e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek // It's compatible if the expression matches any of the fields. 13154e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek for (RecordDecl::field_iterator it = UD->field_begin(), 13164e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek itend = UD->field_end(); 13174e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek it != itend; ++it) { 13181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 13194e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek CStyle, /*ObjCWritebackConversion=*/false)) { 13204e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek ToType = it->getType(); 13214e99a5fc3b203397a91136c6e695e405fb8fc606Ted Kremenek return true; 132256f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner } 132356f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner } 132456f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner return false; 132556f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner} 132656f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner 132756f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner/// IsIntegralPromotion - Determines whether the conversion from the 132856f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner/// expression From (whose potentially-adjusted type is FromType) to 132956f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner/// ToType is an integral promotion (C++ 4.5). If so, returns true and 133056f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner/// sets PromotedType to the promoted type. 133156f349400c5932a196509c0480ff6f99a9a0b48fChris Lattnerbool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 133256f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner const BuiltinType *To = ToType->getAs<BuiltinType>(); 133356f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner // All integers are built-in. 133456f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner if (!To) { 133556f349400c5932a196509c0480ff6f99a9a0b48fChris Lattner return false; 13362fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall } 13372fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall 13382fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall // An rvalue of type char, signed char, unsigned char, short int, or 13392fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall // unsigned short int can be converted to an rvalue of type int if 13402fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall // int can represent all the values of the source type; otherwise, 13412fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall // the source rvalue can be converted to an rvalue of type unsigned 13422fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall // int (C++ 4.5p1). 13432fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 13442fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall !FromType->isEnumeralType()) { 13452fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall if (// We can promote any signed, promotable integer type to an int 13462fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall (FromType->isSignedIntegerType() || 13472fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall // We can promote any unsigned integer type whose size is 1348ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // less than int to an int. 1349ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner (!FromType->isSignedIntegerType() && 1350ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1351ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner return To->getKind() == BuiltinType::Int; 1352ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner } 1353ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner 1354ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner return To->getKind() == BuiltinType::UInt; 1355ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner } 1356ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner 1357ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // C++0x [conv.prom]p3: 13581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // A prvalue of an unscoped enumeration type whose underlying type is not 1359ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1360ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // following types that can represent all the values of the enumeration 13612ade35e2cfd554e49d35a52047cea98a82787af9Douglas Gregor // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1362ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // unsigned int, long int, unsigned long int, long long int, or unsigned 13631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // long long int. If none of the types in that list can represent all the 1364ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1365ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // type can be converted to an rvalue a prvalue of the extended integer type 1366ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // with lowest integer conversion rank (4.13) greater than the rank of long 1367ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // long in which all the values of the enumeration can be represented. If 13681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // there are two such extended types, the signed one is chosen. 13699d3347a5887d2d25afe8b0bd35783a72ec86cce2Douglas Gregor if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 13709d3347a5887d2d25afe8b0bd35783a72ec86cce2Douglas Gregor // C++0x 7.2p9: Note that this implicit enum to int conversion is not 13719d3347a5887d2d25afe8b0bd35783a72ec86cce2Douglas Gregor // provided for a scoped enumeration. 13729d3347a5887d2d25afe8b0bd35783a72ec86cce2Douglas Gregor if (FromEnumType->getDecl()->isScoped()) 1373ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner return false; 1374ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner 1375ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // We have already pre-calculated the promotion type, so this is trivial. 1376ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner if (ToType->isIntegerType() && 1377ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner !RequireCompleteType(From->getLocStart(), FromType, PDiag())) 13781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump return Context.hasSameUnqualifiedType(ToType, 1379ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner FromEnumType->getDecl()->getPromotionType()); 1380ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner } 1381ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner 1382ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // C++0x [conv.prom]p2: 13836eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 13846eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // to an rvalue a prvalue of the first of the following types that can 13856eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // represent all the values of its underlying type: int, unsigned int, 13866eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // long int, unsigned long int, long long int, or unsigned long long int. 1387c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // If none of the types in that list can represent all the values of its 13886eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // underlying type, an rvalue a prvalue of type char16_t, char32_t, 13896eef519fc8a97bb7ca6066f23d35e10f06b2c1b5Douglas Gregor // or wchar_t can be converted to an rvalue a prvalue of its underlying 1390ecdd84147c0765caa999ddc22dde25b42712bb4dChris Lattner // type. 13912f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (FromType->isAnyCharacterType() && !FromType->isCharType() && 13922f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor ToType->isIntegerType()) { 13932f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // Determine whether the type we're converting from is signed or 13942f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // unsigned. 13952de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall bool FromIsSigned = FromType->isSignedIntegerType(); 13962f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor uint64_t FromSize = Context.getTypeSize(FromType); 13972f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor 13982f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // The types we'll try to promote to, in the appropriate 13992f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // order. Try each of these types. 14002f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor QualType PromoteTypes[6] = { 14012f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor Context.IntTy, Context.UnsignedIntTy, 14022f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor Context.LongTy, Context.UnsignedLongTy , 14032f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor Context.LongLongTy, Context.UnsignedLongLongTy 14042f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor }; 14052de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall for (int Idx = 0; Idx < 6; ++Idx) { 14062f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 14072f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (FromSize < ToSize || 14082f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor (FromSize == ToSize && 14092f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1410c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // We found the type that we can promote to. If this is the 14112f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // type we wanted, we have a promotion. Otherwise, no 14122f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // promotion. 14132f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 14142f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14152f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14162f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14172f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor 14182f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // An rvalue for an integral bit-field (9.6) can be converted to an 14192f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // rvalue of type int if int can represent all the values of the 14202f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // bit-field; otherwise, it can be converted to unsigned int if 14212f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // unsigned int can represent all the values of the bit-field. If 14222de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // the bit-field is larger yet, no integral promotion applies to 14232de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // it. If the bit-field has an enumerated type, it is treated as any 14242f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // other value of that type for promotion purposes (C++ 4.5p3). 14252f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // FIXME: We should delay checking of bit-fields until we actually perform the 14262f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // conversion. 14272f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor using llvm::APSInt; 14282f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (From) 14292f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (FieldDecl *MemberDecl = From->getBitField()) { 14302f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor APSInt BitWidth; 14312de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall if (FromType->isIntegralType(Context) && 14322f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 14332f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 14342f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor ToSize = Context.getTypeSize(ToType); 14352f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor 14362de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // Are we promoting to an int from a bitfield that fits in an int? 14372f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (BitWidth < ToSize || 14382f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 14392f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor return To->getKind() == BuiltinType::Int; 14402f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14412f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor 14422f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // Are we promoting to an unsigned int from an unsigned bitfield 14432f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // that fits into an unsigned int? 14442f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 14452f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor return To->getKind() == BuiltinType::UInt; 14462f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14472f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor 14482f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor return false; 14492f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14502f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor } 14512f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor 14522f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // An rvalue of type bool can be converted to an rvalue of type int, 14532f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor // with false becoming zero and true becoming one (C++ 4.5p4). 14542f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 14552f59979a7cc7929f53c9984423b0abeb83113442Douglas Gregor return true; 1456898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor } 1457898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor 1458898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor return false; 1459898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor} 1460898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor 1461898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor/// IsFloatingPointPromotion - Determines whether the conversion from 1462898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1463898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor/// returns true and sets PromotedType to the promoted type. 1464898574e7496ba8fd76290079d3a9d06954992734Douglas Gregorbool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1465898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor /// An rvalue of type float can be converted to an rvalue of type 1466898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor /// double. (C++ 4.6p1). 1467898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1468898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1469898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor if (FromBuiltin->getKind() == BuiltinType::Float && 1470898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor ToBuiltin->getKind() == BuiltinType::Double) 1471898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor return true; 1472898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor 1473898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor // C99 6.3.1.5p1: 1474898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor // When a float is promoted to double or long double, or a 1475898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor // double is promoted to long double [...]. 14764204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall if (!getLangOptions().CPlusPlus && 1477c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman (FromBuiltin->getKind() == BuiltinType::Float || 1478c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman FromBuiltin->getKind() == BuiltinType::Double) && 1479c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1480c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman return true; 1481c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman } 1482c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman 14834204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall return false; 14844204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall} 14854204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall 14864204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// \brief Determine if a conversion is a complex promotion. 14874204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// 14884204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// A complex promotion is defined as a complex -> complex conversion 14894204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// where the conversion between the underlying real types is a 14901f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli Friedman/// floating-point or integral promotion. 1491e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlssonbool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1492c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1493e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson if (!FromComplex) 149414108da7f7fc059772711e4ffee1322a27b152a7Steve Naroff return false; 1495eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner 1496e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1497b4b9b15c597a923a03ad0a33cdc49b67e5cc4450John McCall if (!ToComplex) 1498b4b9b15c597a923a03ad0a33cdc49b67e5cc4450John McCall return false; 1499b4b9b15c597a923a03ad0a33cdc49b67e5cc4450John McCall 15004204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall return IsFloatingPointPromotion(FromComplex->getElementType(), 15014204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall ToComplex->getElementType()) || 15024204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall IsIntegralPromotion(0, FromComplex->getElementType(), 1503b4b9b15c597a923a03ad0a33cdc49b67e5cc4450John McCall ToComplex->getElementType()); 15044204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall} 15054204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall 15064204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 15074204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// the pointer type FromPtr to a pointer to type ToPointee, with the 15084204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// same type qualifiers as FromPtr has on its pointee type. ToType, 15094204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// if non-empty, will be a pointer to ToType that may or may not have 15104204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall/// the right set of qualifiers on its pointee. 1511b4b9b15c597a923a03ad0a33cdc49b67e5cc4450John McCall/// 151259b5da6d853b4368b984700315adf7b37de05764Nate Begemanstatic QualType 15131f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli FriedmanBuildSimilarlyQualifiedPointerType(const Type *FromPtr, 15141f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli Friedman QualType ToPointee, QualType ToType, 15151f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli Friedman ASTContext &Context, 151659b5da6d853b4368b984700315adf7b37de05764Nate Begeman bool StripObjCLifetime = false) { 15174204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall assert((FromPtr->getTypeClass() == Type::Pointer || 151859b5da6d853b4368b984700315adf7b37de05764Nate Begeman FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1519e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson "Invalid similarly-qualified pointer type"); 15201f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli Friedman 15211f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli Friedman /// Conversions to 'id' subsume cv-qualifier conversions. 15221f4a6db271f389d6ab3cb1bc28cb5c23a7828602Eli Friedman if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1523e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson return ToType.getUnqualifiedType(); 1524e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson 1525e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson QualType CanonFromPointee 15264204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall = Context.getCanonicalType(FromPtr->getPointeeType()); 1527e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1528e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson Qualifiers Quals = CanonFromPointee.getQualifiers(); 1529c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman 1530e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson if (StripObjCLifetime) 15313498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor Quals.removeObjCLifetime(); 15323498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor 15333ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner // Exact qualifier match -> return the pointer type we're converting to. 15344204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall if (CanonToPointee.getLocalQualifiers() == Quals) { 15354204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall // ToType is exactly what we need. Return it. 1536c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman if (!ToType.isNull()) 1537c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman return ToType.getUnqualifiedType(); 15382de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall 15394204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall // Build a pointer to ToPointee. It has the right qualifiers 1540c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman // already. 1541c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman if (isa<ObjCObjectPointerType>(ToType)) 15423ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner return Context.getObjCObjectPointerType(ToPointee); 15433ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner return Context.getPointerType(ToPointee); 15443ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner } 15453ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner 15462de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall // Just build a canonical type that has the right qualifiers. 15473ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner QualType QualifiedCanonToPointee 15483ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 15493ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner 15503ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner if (isa<ObjCObjectPointerType>(ToType)) 15513ae9f48ae0d07a5aa352bf03c944f557a5ac4c95Chris Lattner return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 15524204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall return Context.getPointerType(QualifiedCanonToPointee); 1553b4b9b15c597a923a03ad0a33cdc49b67e5cc4450John McCall} 155481045d8dcd967def69d8e0945566214a9fe9ffccChris Lattner 1555c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedmanstatic bool isNullPointerConstantForConversion(Expr *Expr, 1556c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman bool InOverloadResolution, 1557c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman ASTContext &Context) { 1558c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman // Handle value-dependent integral null pointer constants correctly. 1559c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 15604204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall if (Expr->isValueDependent() && !Expr->isTypeDependent() && 15614204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1562c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return !InOverloadResolution; 1563430656e1c392dcd9f17fe91a495421d69fca1bc8Chris Lattner 1564430656e1c392dcd9f17fe91a495421d69fca1bc8Chris Lattner return Expr->isNullPointerConstant(Context, 1565430656e1c392dcd9f17fe91a495421d69fca1bc8Chris Lattner InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1566430656e1c392dcd9f17fe91a495421d69fca1bc8Chris Lattner : Expr::NPC_ValueDependentIsNull); 15674204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall} 15684204f07fc8bffe6d320b2de95fea274ccf37a17bJohn McCall 1569c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt/// IsPointerConversion - Determines whether the conversion of the 1570c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman/// expression From, which has the (possibly adjusted) type FromType, 1571e8a32b855ce4e8580a191f8d29d2f3f459834302Anders Carlsson/// can be converted to the type ToType via a pointer conversion (C++ 1572c39dc9a25a9d74a5302e8567a4d3fc008212024cEli Friedman/// 4.10). If so, returns true and places the converted type (that 157338374b05791ee93300b9fbe8ceb3957f54184b37Steve Naroff/// might differ from ToType in its cv-qualifiers at some level) into 157438374b05791ee93300b9fbe8ceb3957f54184b37Steve Naroff/// ConvertedType. 15755f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// 15765f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// This routine also supports conversions to and from block pointers 15775f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1578ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// pointers to interfaces. FIXME: Once we've determined the 1579ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// appropriate overloading rules for Objective-C, we may want to 1580ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// split the Objective-C checks into a different routine; however, 1581ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// GCC seems to consider all of these conversions to be pointer 1582ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// conversions, so for now they live here. IncompatibleObjC will be 1583ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// set if the conversion is an allowed Objective-C conversion that 1584ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor/// should result in a warning. 1585c302113179a1c2b1254224ea9b6f5316ceeb375cSean Huntbool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1586ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor bool InOverloadResolution, 15879d3347a5887d2d25afe8b0bd35783a72ec86cce2Douglas Gregor QualType& ConvertedType, 1588c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt bool &IncompatibleObjC) { 1589ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor IncompatibleObjC = false; 1590ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1591ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor IncompatibleObjC)) 1592ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor return true; 1593f515b2268f829adfbfdb751f54d102b53ed0285cDaniel Dunbar 15940777972d38a3125efed962b045704c30ae6965cfSebastian Redl // Conversion from a null pointer constant to any Objective-C pointer type. 15950835a3cdeefe714b4959d31127ea155e56393125Argyrios Kyrtzidis if (ToType->isObjCObjectPointerType() && 15966215dee86c0e715b9f2b0d401ab2a5fcf629f1afSebastian Redl isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 15970777972d38a3125efed962b045704c30ae6965cfSebastian Redl ConvertedType = ToType; 15986217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek return true; 15990777972d38a3125efed962b045704c30ae6965cfSebastian Redl } 16000953e767ff7817f97b3ab20896b229891eeff45bJohn McCall 16010777972d38a3125efed962b045704c30ae6965cfSebastian Redl // Blocks: Block pointers can be converted to void*. 16020777972d38a3125efed962b045704c30ae6965cfSebastian Redl if (FromType->isBlockPointerType() && ToType->isPointerType() && 1603ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 16040777972d38a3125efed962b045704c30ae6965cfSebastian Redl ConvertedType = ToType; 16055f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer return true; 1606aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff } 1607aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff // Blocks: A null pointer constant can be converted to a block 1608ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor // pointer type. 1609aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff if (ToType->isBlockPointerType() && 1610aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1611aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff ConvertedType = ToType; 1612ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor return true; 16131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump } 16148123a95c33b792d35c2e4992ba6e27882748fb0dChris Lattner 161504421087832a031c90bd58f128c7c0e741db8dd2Chris Lattner // If the left-hand-side is nullptr_t, the right side can be a null 1616ce94049b69f75b44c18584fe79cd238978b6b0d5Douglas Gregor // pointer constant. 16172d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor if (ToType->isNullPtrType() && 16182d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 16192d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor ConvertedType = ToType; 1620aaffbf7c790a324ed114184db771aae2d2e9151cSteve Naroff return true; 16212d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor } 16226e8ed16ffef02b82995a90bdcf10ffff7d63839aSebastian Redl 16236e8ed16ffef02b82995a90bdcf10ffff7d63839aSebastian Redl const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 16246e8ed16ffef02b82995a90bdcf10ffff7d63839aSebastian Redl if (!ToTypePtr) 16256e8ed16ffef02b82995a90bdcf10ffff7d63839aSebastian Redl return false; 1626aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff 1627c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 162856fc0d18caf9c829647a5e3ce35197f0d7e0feeeFariborz Jahanian if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1629aa58f00ebba5f14955001736b7aea20bb5bd91e6Steve Naroff ConvertedType = ToType; 16301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump return true; 16315f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer } 16325f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer 163309de1767990d4828bcaf0dd22033a5dddeecbe08Eli Friedman // Beyond this point, both types need to be pointers 163409de1767990d4828bcaf0dd22033a5dddeecbe08Eli Friedman // , including objective-c pointers. 16355f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer QualType ToPointeeType = ToTypePtr->getPointeeType(); 163631a458462c6cf417a84e0c47852b18fb22d79acbSteve Naroff if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 163733bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor !getLangOptions().ObjCAutoRefCount) { 16386f4a69a3107e7ff1569c747f7c6bdf7cff8cbf55Douglas Gregor ConvertedType = BuildSimilarlyQualifiedPointerType( 163933bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor FromType->getAs<ObjCObjectPointerType>(), 1640de4b1d86bf48bc2a84bddf6b188f6da53eaea845Douglas Gregor ToPointeeType, 16415baba9d98364a3525d6afa15a04cdad82fd6dd30John McCall ToType, Context); 16422de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall return true; 1643de4b1d86bf48bc2a84bddf6b188f6da53eaea845Douglas Gregor } 1644de4b1d86bf48bc2a84bddf6b188f6da53eaea845Douglas Gregor const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1645de4b1d86bf48bc2a84bddf6b188f6da53eaea845Douglas Gregor if (!FromTypePtr) 1646de4b1d86bf48bc2a84bddf6b188f6da53eaea845Douglas Gregor return false; 1647de4b1d86bf48bc2a84bddf6b188f6da53eaea845Douglas Gregor 164827c8dc06f65d7abcf6a7e7f64a7960c9a150ca01Douglas Gregor QualType FromPointeeType = FromTypePtr->getPointeeType(); 164986f194083504938df72135b5b66bf0c5cafd9498Douglas Gregor 165033bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor // If the unqualified pointee types are the same, this can't be a 165133bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor // pointer conversion, so don't do all of the work below. 165233bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 165333bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor return false; 165433bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor 165533bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor // An rvalue of type "pointer to cv T," where T is an object type, 165633bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor // can be converted to an rvalue of type "pointer to cv void" (C++ 165733bbbc5ec8269bc2cde5b84f970fa49319a30267Douglas Gregor // 4.10p2). 165827c8dc06f65d7abcf6a7e7f64a7960c9a150ca01Douglas Gregor if (FromPointeeType->isIncompleteOrObjectType() && 165927c8dc06f65d7abcf6a7e7f64a7960c9a150ca01Douglas Gregor ToPointeeType->isVoidType()) { 1660093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1661093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson ToPointeeType, 1662c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ToType, Context, 1663093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson /*StripObjCLifetime=*/true); 16645baba9d98364a3525d6afa15a04cdad82fd6dd30John McCall return true; 16652de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall } 1666093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson 1667093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson // MSVC allows implicit function to void* type conversion. 1668093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() && 1669093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson ToPointeeType->isVoidType()) { 1670c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1671093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson ToPointeeType, 1672093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson ToType, Context); 1673093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson return true; 1674093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson } 1675093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson 1676093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson // When we're overloading in C, we allow a special kind of pointer 1677093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson // conversion for compatible-but-not-identical pointee types. 1678093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson if (!getLangOptions().CPlusPlus && 1679093802675b1548f2a5f44c29938d65cce00d58bbAnders Carlsson Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 16802140e904dbe53657339cb5b1cc13de563ca0d1fcChris Lattner ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 16812140e904dbe53657339cb5b1cc13de563ca0d1fcChris Lattner ToPointeeType, 16822140e904dbe53657339cb5b1cc13de563ca0d1fcChris Lattner ToType, Context); 16832140e904dbe53657339cb5b1cc13de563ca0d1fcChris Lattner return true; 16842140e904dbe53657339cb5b1cc13de563ca0d1fcChris Lattner } 16852140e904dbe53657339cb5b1cc13de563ca0d1fcChris Lattner 1686213541a68a3e137d11d2cefb612c6cdb410d7e8eNate Begeman // C++ [conv.ptr]p3: 1687183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall // 16888a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman // An rvalue of type "pointer to cv D," where D is a class type, 16898a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman // can be converted to an rvalue of type "pointer to cv B," where 16904d0ac88428b3ed7c6f3a2f4e758ea5424ecd70aeChris Lattner // B is a base class (clause 10) of D. If B is an inaccessible 16914d0ac88428b3ed7c6f3a2f4e758ea5424ecd70aeChris Lattner // (clause 11) or ambiguous (10.2) base class of D, a program that 16928a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman // necessitates this conversion is ill-formed. The result of the 1693213541a68a3e137d11d2cefb612c6cdb410d7e8eNate Begeman // conversion is a pointer to the base class sub-object of the 1694a2b34eb7d19d1d199a244da20afe12353e3593acDaniel Dunbar // derived class object. The null pointer value is converted to 1695a2b34eb7d19d1d199a244da20afe12353e3593acDaniel Dunbar // the null pointer value of the destination type. 169601eb9b9683535d8a65c704ad2c545903409e2d36Daniel Dunbar // 1697190d6a25393995b42e32086949a68285ee423fb9Nate Begeman // Note that we do not check for ambiguity or inaccessibility 1698190d6a25393995b42e32086949a68285ee423fb9Nate Begeman // here. That is handled by CheckPointerConversion. 1699150274299b0bc2efda45783f99bef3f9f6e807acDaniel Dunbar if (getLangOptions().CPlusPlus && 1700190d6a25393995b42e32086949a68285ee423fb9Nate Begeman FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 17011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 1702190d6a25393995b42e32086949a68285ee423fb9Nate Begeman !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) && 1703150274299b0bc2efda45783f99bef3f9f6e807acDaniel Dunbar IsDerivedFrom(FromPointeeType, ToPointeeType)) { 1704150274299b0bc2efda45783f99bef3f9f6e807acDaniel Dunbar ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 17051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump ToPointeeType, 1706150274299b0bc2efda45783f99bef3f9f6e807acDaniel Dunbar ToType, Context); 1707150274299b0bc2efda45783f99bef3f9f6e807acDaniel Dunbar return true; 1708fec0b49c3fa621fbf63e420f3d54a5bb3a0265d2Steve Naroff } 1709150274299b0bc2efda45783f99bef3f9f6e807acDaniel Dunbar 1710fec0b49c3fa621fbf63e420f3d54a5bb3a0265d2Steve Naroff if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 1711fec0b49c3fa621fbf63e420f3d54a5bb3a0265d2Steve Naroff Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 1712b8f849da3cedee2f61ad98389115ddd04e439d60Chris Lattner ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 17138a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman ToPointeeType, 17143b8d116703db8018f855cbb4733ace426422623bNate Begeman ToType, Context); 17153b8d116703db8018f855cbb4733ace426422623bNate Begeman return true; 17164b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar } 17174b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar 17184b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar return false; 17191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump} 17204b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar 17214b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar/// \brief Adopt the given qualifiers for the given type. 17224b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbarstatic QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 17234b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar Qualifiers TQs = T.getQualifiers(); 17241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump 17258a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman // Check whether qualifiers already match. 17268a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman if (TQs == Qs) 17271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump return T; 17288a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman 17298a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman if (Qs.compatiblyIncludes(TQs)) 17308a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman return Context.getQualifiedType(T, Qs); 17318a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman 17328a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 17338a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman} 17348a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman 17358a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman/// isObjCPointerConversion - Determines whether this is an 17368a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 17374b55b24410a2739c589c4b9e84a364161c9a17e5Daniel Dunbar/// with the same arguments and return values. 1738b8f849da3cedee2f61ad98389115ddd04e439d60Chris Lattnerbool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 17393b8d116703db8018f855cbb4733ace426422623bNate Begeman QualType& ConvertedType, 1740b8f849da3cedee2f61ad98389115ddd04e439d60Chris Lattner bool &IncompatibleObjC) { 17418a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman if (!getLangOptions().ObjC1) 17428a99764f9b778a54e7440b1ee06a1e48f25d76d8Nate Begeman return false; 174304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 174404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // The set of qualifiers on the type we're converting from. 174504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor Qualifiers FromQualifiers = FromType.getQualifiers(); 174604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 174704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // First, we handle all conversions on ObjC object pointer types. 1748c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt const ObjCObjectPointerType* ToObjCPtr = 174904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToType->getAs<ObjCObjectPointerType>(); 175004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor const ObjCObjectPointerType *FromObjCPtr = 175104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor FromType->getAs<ObjCObjectPointerType>(); 175204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 175392e986e0adb79e8a47f738bd608e6c97c547641dDouglas Gregor if (ToObjCPtr && FromObjCPtr) { 175404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // If the pointee types are the same (ignoring qualifications), 175504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // then this is not a pointer conversion. 175604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 175704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor FromObjCPtr->getPointeeType())) 1758c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return false; 1759c2350e553b853ad00914faf23fa731e5fc4a8a5cDouglas Gregor 176004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Check for compatible 176104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Objective C++: We're able to convert between "id" or "Class" and a 176204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // pointer to any interface (in both directions). 176304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 176404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 176504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return true; 176604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 176704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Conversions with Objective-C's id<...>. 1768c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt if ((FromObjCPtr->isObjCQualifiedIdType() || 176904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToObjCPtr->isObjCQualifiedIdType()) && 177004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 177104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor /*compare=*/false)) { 177204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 1773c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return true; 177404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 177504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Objective C++: We're able to convert from a pointer to an 177604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // interface to a pointer to a different interface. 177704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 1778c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 177904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 178004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (getLangOptions().CPlusPlus && LHS && RHS && 178104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 178204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor FromObjCPtr->getPointeeType())) 178304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return false; 178404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 178504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToObjCPtr->getPointeeType(), 178604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToType, Context); 178704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 1788c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return true; 178904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 179004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 179104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 179292e986e0adb79e8a47f738bd608e6c97c547641dDouglas Gregor // Okay: this is some kind of implicit downcast of Objective-C 1793c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // interfaces, which is permitted. However, we're going to 179404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // complain about it. 179504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor IncompatibleObjC = true; 179604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 179704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToObjCPtr->getPointeeType(), 1798c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ToType, Context); 179904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 180004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return true; 180104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 180204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 180304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Beyond this point, both types need to be C pointers or block pointers. 180404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor QualType ToPointeeType; 180504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 180604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToPointeeType = ToCPtr->getPointeeType(); 180704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor else if (const BlockPointerType *ToBlockPtr = 180804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToType->getAs<BlockPointerType>()) { 180904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Objective C++: We're able to convert from a pointer to any object 1810c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // to a block pointer type. 181104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 181204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 181304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return true; 1814c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt } 181504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToPointeeType = ToBlockPtr->getPointeeType(); 181604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 181704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor else if (FromType->getAs<BlockPointerType>() && 1818c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 181904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Objective C++: We're able to convert from a block pointer type to a 182004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // pointer to any object. 182104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 182204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return true; 182304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 182404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor else 1825c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt return false; 182604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 182704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor QualType FromPointeeType; 182804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 1829c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt FromPointeeType = FromCPtr->getPointeeType(); 183004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor else if (const BlockPointerType *FromBlockPtr = 183104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor FromType->getAs<BlockPointerType>()) 1832c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt FromPointeeType = FromBlockPtr->getPointeeType(); 183304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor else 183404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return false; 183504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 183604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // If we have pointers to pointers, recursively check whether this 183704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // is an Objective-C conversion. 183804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 1839c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 184004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor IncompatibleObjC)) { 184104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // We always complain about this conversion. 184204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor IncompatibleObjC = true; 1843c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ConvertedType = Context.getPointerType(ConvertedType); 184404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 184504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return true; 1846c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt } 184704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Allow conversion of pointee being objective-c pointer to another one; 184804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // as in I* to id. 184904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (FromPointeeType->getAs<ObjCObjectPointerType>() && 1850c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt ToPointeeType->getAs<ObjCObjectPointerType>() && 185104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1852c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt IncompatibleObjC)) { 185304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 185404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = Context.getPointerType(ConvertedType); 185504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 185604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return true; 1857c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt } 185804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 185904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // If we have pointers to functions or blocks, check whether the only 186004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // differences in the argument and result types are in Objective-C 186104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // pointer conversions. If so, we permit the conversion (but 1862c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt // complain about it). 186304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor const FunctionProtoType *FromFunctionType 186404badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor = FromPointeeType->getAs<FunctionProtoType>(); 186504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor const FunctionProtoType *ToFunctionType 186604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor = ToPointeeType->getAs<FunctionProtoType>(); 186704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (FromFunctionType && ToFunctionType) { 186804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // If the function types are exactly the same, this isn't an 186904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Objective-C pointer conversion. 187004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (Context.getCanonicalType(FromPointeeType) 187104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor == Context.getCanonicalType(ToPointeeType)) 18724df728e368fa1f65ffc57572fed613dcca5b4fe8Ted Kremenek return false; 187304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 1874c12c5bba6ceb6acd4e51e7a0fc03257da9cfd44eJohn McCall // Perform the quick checks that will tell us whether these 1875c12c5bba6ceb6acd4e51e7a0fc03257da9cfd44eJohn McCall // function types are obviously different. 1876c12c5bba6ceb6acd4e51e7a0fc03257da9cfd44eJohn McCall if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 187704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 18784df728e368fa1f65ffc57572fed613dcca5b4fe8Ted Kremenek FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 187904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return false; 188004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor 188104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor bool HasObjCConversion = false; 188204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor if (Context.getCanonicalType(FromFunctionType->getResultType()) 188304badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor == Context.getCanonicalType(ToFunctionType->getResultType())) { 1884c2350e553b853ad00914faf23fa731e5fc4a8a5cDouglas Gregor // Okay, the types match exactly. Nothing to do. 188504badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 188604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToFunctionType->getResultType(), 188704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ConvertedType, IncompatibleObjC)) { 188804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // Okay, we have an Objective-C pointer conversion. 188904badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor HasObjCConversion = true; 189004badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } else { 18910389e6bd0159bfdd08f7c50a37543b6e3adf0c33Chris Lattner // Function types are too different. Abort. 189204badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor return false; 1893eb3b324800598cc3d5385fbad95ae5cff2c79113Ted Kremenek } 18940389e6bd0159bfdd08f7c50a37543b6e3adf0c33Chris Lattner 189527437caadea35f84d550cd29f024fcf3ea240eecChris Lattner // Check argument types. 18969a901bb63990574ff0bcc12ff851d7a71cff8ddbEli Friedman for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 189727437caadea35f84d550cd29f024fcf3ea240eecChris Lattner ArgIdx != NumArgs; ++ArgIdx) { 189827437caadea35f84d550cd29f024fcf3ea240eecChris Lattner QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 1899888376a2bbcfc2f047902249f8455918e2489ae1Nate Begeman QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 1900888376a2bbcfc2f047902249f8455918e2489ae1Nate Begeman if (Context.getCanonicalType(FromArgType) 1901888376a2bbcfc2f047902249f8455918e2489ae1Nate Begeman == Context.getCanonicalType(ToArgType)) { 1902888376a2bbcfc2f047902249f8455918e2489ae1Nate Begeman // Okay, the types match exactly. Nothing to do. 1903888376a2bbcfc2f047902249f8455918e2489ae1Nate Begeman } else if (isObjCPointerConversion(FromArgType, ToArgType, 190494cd5d1397bb1a8bcd109602aa38dd787b164c22Douglas Gregor ConvertedType, IncompatibleObjC)) { 190594cd5d1397bb1a8bcd109602aa38dd787b164c22Douglas Gregor // Okay, we have an Objective-C pointer conversion. 19061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump HasObjCConversion = true; 1907888376a2bbcfc2f047902249f8455918e2489ae1Nate Begeman } else { 190877ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek // Argument types are too different. Abort. 190905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return false; 191005c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor } 191105c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor } 191205c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 191305c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (HasObjCConversion) { 191405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // We had an Objective-C conversion. Allow this pointer 191505c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // conversion, but complain about it. 191605c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 191705c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor IncompatibleObjC = true; 191805c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return true; 191905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor } 1920c302113179a1c2b1254224ea9b6f5316ceeb375cSean Hunt } 1921319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor 1922ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor return false; 19231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump} 1924ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor 19251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// \brief Determine whether this is an Objective-C writeback conversion, 19269ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor/// used for parameter passing when performing automatic reference counting. 19279ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor/// 19281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// \param FromType The type we're converting form. 19299ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor/// 19301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// \param ToType The type we're converting to. 19311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// 1932319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor/// \param ConvertedType The type that will be produced after applying 19339ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor/// this conversion. 19349ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregorbool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 19359ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor QualType &ConvertedType) { 19369ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor if (!getLangOptions().ObjCAutoRefCount || 19379ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor Context.hasSameUnqualifiedType(FromType, ToType)) 19389ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor return false; 19399ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor 19409ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 19419ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor QualType ToPointee; 1942ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 19439ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor ToPointee = ToPointer->getPointeeType(); 19449ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor else 19459ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor return false; 19469ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor 19471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump Qualifiers ToQuals = ToPointee.getQualifiers(); 19489ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor if (!ToPointee->isObjCLifetimeType() || 19499ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 19509ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor !ToQuals.withoutObjCGLifetime().empty()) 19519ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor return false; 19529ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor 19539ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor // Argument must be a pointer to __strong to __weak. 19549ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor QualType FromPointee; 19559ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 19561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump FromPointee = FromPointer->getPointeeType(); 19579ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor else 19589ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor return false; 19599ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor 19609ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor Qualifiers FromQuals = FromPointee.getQualifiers(); 19619ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor if (!FromPointee->isObjCLifetimeType() || 19629ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 19639ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 19649ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor return false; 19659ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor 19669ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor // Make sure that we have compatible qualifiers. 1967ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 1968ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor if (!ToQuals.compatiblyIncludes(FromQuals)) 196905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return false; 19701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump 197105c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // Remove qualifiers from the pointee type we're converting from; they 197205c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // aren't used in the compatibility check belong, and we'll be adding back 197305c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // qualifiers (with __autoreleasing) if the compatibility check succeeds. 197405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor FromPointee = FromPointee.getUnqualifiedType(); 1975c0ac4923f08b25ae973a8ee7942cf3eb89da57b7Steve Naroff 1976c0ac4923f08b25ae973a8ee7942cf3eb89da57b7Steve Naroff // The unqualified form of the pointee types must be compatible. 1977319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor ToPointee = ToPointee.getUnqualifiedType(); 19789ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor bool IncompatibleObjC; 19799ea62768fca25d829d80199cf4f8cf0f4dd39251Douglas Gregor if (Context.typesAreCompatible(FromPointee, ToPointee)) 198005c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor FromPointee = ToPointee; 198105c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 19821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump IncompatibleObjC)) 1983d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor return false; 1984d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor 1985d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor /// \brief Construct the type we're converting to, which is a pointer to 1986d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor /// __autoreleasing pointee. 1987d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 1988d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor ConvertedType = Context.getPointerType(FromPointee); 1989319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor return true; 1990319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor} 1991d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor 1992319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregorbool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 1993d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor QualType& ConvertedType) { 1994d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor QualType ToPointeeType; 1995d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor if (const BlockPointerType *ToBlockPtr = 1996d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor ToType->getAs<BlockPointerType>()) 1997d077d759d0c7fceee98f4e77b6423a3f11cfc849Douglas Gregor ToPointeeType = ToBlockPtr->getPointeeType(); 199805c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor else 199905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return false; 2000d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner 2001d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner QualType FromPointeeType; 200205c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (const BlockPointerType *FromBlockPtr = 2003eeae8f072748affce25ab4064982626361293390Douglas Gregor FromType->getAs<BlockPointerType>()) 200405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor FromPointeeType = FromBlockPtr->getPointeeType(); 200505c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor else 200605c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return false; 200705c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // We have pointer to blocks, check whether the only 2008d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner // differences in the argument and result types are in Objective-C 2009d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner // pointer conversions. If so, we permit the conversion. 201005c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 201105c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor const FunctionProtoType *FromFunctionType 201205c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor = FromPointeeType->getAs<FunctionProtoType>(); 201305c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor const FunctionProtoType *ToFunctionType 201405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor = ToPointeeType->getAs<FunctionProtoType>(); 201505c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 201605c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (!FromFunctionType || !ToFunctionType) 201705c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return false; 201805c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 201905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (Context.hasSameType(FromPointeeType, ToPointeeType)) 202005c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return true; 202105c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 20221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // Perform the quick checks that will tell us whether these 202305c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // function types are obviously different. 202405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 202505c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 202605c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor return false; 202705c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 202805c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 202905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 203005c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (FromEInfo != ToEInfo) 20311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump return false; 203205c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 203305c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor bool IncompatibleObjC = false; 203405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor if (Context.hasSameType(FromFunctionType->getResultType(), 203505c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor ToFunctionType->getResultType())) { 203605c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor // Okay, the types match exactly. Nothing to do. 203705c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor } else { 203805c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor QualType RHS = FromFunctionType->getResultType(); 2039ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor QualType LHS = ToFunctionType->getResultType(); 2040ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) && 2041319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor !RHS.hasQualifiers() && LHS.hasQualifiers()) 20421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump LHS = LHS.getUnqualifiedType(); 2043ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor 2044ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor if (Context.hasSameType(RHS,LHS)) { 2045ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor // OK exact match. 2046ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor } else if (isObjCPointerConversion(RHS, LHS, 2047ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor ConvertedType, IncompatibleObjC)) { 2048ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor if (IncompatibleObjC) 2049ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor return false; 2050ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor // Okay, we have an Objective-C pointer conversion. 2051ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor } 2052ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor else 2053ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor return false; 2054ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor } 2055ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor 20561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // Check argument types. 2057319d57f21600dd2c4d52ccc27bd12ce260b174e7Douglas Gregor for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2058ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor ArgIdx != NumArgs; ++ArgIdx) { 2059ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor IncompatibleObjC = false; 2060ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2061ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2062ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor if (Context.hasSameType(FromArgType, ToArgType)) { 2063ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor // Okay, the types match exactly. Nothing to do. 2064ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor } else if (isObjCPointerConversion(ToArgType, FromArgType, 2065ffb4b6e299069139908540ce97be4462e16b53a4Douglas Gregor ConvertedType, IncompatibleObjC)) { 20661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump if (IncompatibleObjC) 20672ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman return false; 20682ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman // Okay, we have an Objective-C pointer conversion. 20692ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman } else 20702ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman // Argument types are too different. Abort. 20711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump return false; 20722ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman } 20731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump ConvertedType = ToType; 20742ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman return true; 20752ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman} 20762ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman 20772ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman/// FunctionArgTypesAreEqual - This routine checks two function proto types 20782ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman/// for equlity of their argument types. Caller has already checked that 207905c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// they have same number of arguments. This routine assumes that Objective-C 2080ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek/// pointer types which only differ in their protocol qualifiers are equal. 2081ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenekbool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2082ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek const FunctionProtoType *NewType) { 2083ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek if (!getLangOptions().ObjC1) 2084ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 2085ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek NewType->arg_type_begin()); 2086ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek 2087ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2088ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek N = NewType->arg_type_begin(), 2089ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2090ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek QualType ToType = (*O); 2091ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek QualType FromType = (*N); 2092ce2fc3a343ea6098a96d587071cee7299f11957aTed Kremenek if (ToType != FromType) { 209377ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 209477ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (const PointerType *PTFr = FromType->getAs<PointerType>()) 209577ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 209677ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek PTFr->getPointeeType()->isObjCQualifiedIdType()) || 20979ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek (PTTo->getPointeeType()->isObjCQualifiedClassType() && 20989ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek PTFr->getPointeeType()->isObjCQualifiedClassType())) 209977ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek continue; 21007779db42c94405ecbd6ee45efb293483fa6cbeffSteve Naroff } 21015549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek else if (const ObjCObjectPointerType *PTTo = 21025549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek ToType->getAs<ObjCObjectPointerType>()) { 21037779db42c94405ecbd6ee45efb293483fa6cbeffSteve Naroff if (const ObjCObjectPointerType *PTFr = 2104e3e9add4fd788927df6f545570e7838db59c01d7Steve Naroff FromType->getAs<ObjCObjectPointerType>()) 21055549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl()) 21065549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek continue; 2107ae7840776d6cd31b4d7a4a345b61bcbb3744df6cSteve Naroff } 210809105f52b1f28cbb1374c27c3c70f5517e2c465dFariborz Jahanian return false; 21091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump } 21102fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall } 21112fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall return true; 21122fc46bf1a9bc31d50f82de37c70ea257d3cded27John McCall} 2113154440e6a8fa6ac5bca395876d79b530b39a2c1cFariborz Jahanian 21141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// CheckPointerConversion - Check the pointer conversion from the 21151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// expression From to the type ToType. This routine checks for 2116154440e6a8fa6ac5bca395876d79b530b39a2c1cFariborz Jahanian/// ambiguous or inaccessible derived-to-base pointer 21175daf570d0ce027e18ed5f9d66e6b2a14a40b720dFariborz Jahanian/// conversions for which IsPointerConversion has already returned 2118cd9b46e5442a3ef17f83f75177d8545cb5b3e2b9Douglas Gregor/// true. It returns true and produces a diagnostic if there was an 2119cd9b46e5442a3ef17f83f75177d8545cb5b3e2b9Douglas Gregor/// error, or returns false otherwise. 2120cd9b46e5442a3ef17f83f75177d8545cb5b3e2b9Douglas Gregorbool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2121cd9b46e5442a3ef17f83f75177d8545cb5b3e2b9Douglas Gregor CastKind &Kind, 2122f242b1b0c4e998911cb96b2ba7e27ab4a5abaed3Steve Naroff CXXCastPath& BasePath, 2123f242b1b0c4e998911cb96b2ba7e27ab4a5abaed3Steve Naroff bool IgnoreBaseAccess) { 2124f242b1b0c4e998911cb96b2ba7e27ab4a5abaed3Steve Naroff QualType FromType = From->getType(); 2125f242b1b0c4e998911cb96b2ba7e27ab4a5abaed3Steve Naroff bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2126d9f6910f4ef37c0e8eeee2a01287d9572c3176efChris Lattner 2127d9f6910f4ef37c0e8eeee2a01287d9572c3176efChris Lattner Kind = CK_BitCast; 2128d9f6910f4ef37c0e8eeee2a01287d9572c3176efChris Lattner 212977ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (!IsCStyleOrFunctionalCast && 213077ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) && 21319ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 21329ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek DiagRuntimeBehavior(From->getExprLoc(), From, 213377ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek PDiag(diag::warn_impcast_bool_to_null_pointer) 213477ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek << ToType << From->getSourceRange()); 2135d603eaa682cecac2c10771a700cb83aa301653b4Chris Lattner 21369ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) 213777ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 213877ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek QualType FromPointeeType = FromPtrType->getPointeeType(), 21399ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek ToPointeeType = ToPtrType->getPointeeType(); 21409ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek 214177ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 21425d66145eed1c319df5a69977cb8ff74f597ea544Chris Lattner !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 21435549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek // We must have a derived-to-base conversion. Check an 21445549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek // ambiguous or inaccessible conversion. 21455d66145eed1c319df5a69977cb8ff74f597ea544Chris Lattner if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 214677ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek From->getExprLoc(), 21479ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek From->getSourceRange(), &BasePath, 21489ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek IgnoreBaseAccess)) 214977ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek return true; 215077ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek 21515549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek // The conversion was successful. 21525549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek Kind = CK_DerivedToBase; 215377ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek } 215477ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek } 21555549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek if (const ObjCObjectPointerType *FromPtrType = 21565549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek FromType->getAs<ObjCObjectPointerType>()) { 215777ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (const ObjCObjectPointerType *ToPtrType = 21588ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor ToType->getAs<ObjCObjectPointerType>()) { 21598ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // Objective-C++ conversions are always okay. 21608ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // FIXME: We should have a different class of conversions for the 21618ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor // Objective-C++ implicit conversions. 21628ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 21638ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor return false; 21648ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor } 21658ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor } 21668ecdb65716cd7914ffb2eeee993fa9039fcd31e8Douglas Gregor 21670518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl // We shouldn't fall into this case unless it's valid for other 21681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // reasons. 21690518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 21700518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl Kind = CK_NullToPointer; 21710518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl 21720518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl return false; 21730518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl} 21740518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl 21750518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl/// IsMemberPointerConversion - Determines whether the conversion of the 21760518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl/// expression From, which has the (possibly adjusted) type FromType, can be 21770518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2178d457589fc69dc7a9c80cd74d317c0b81a35a27c9Sebastian Redl/// If so, returns true and places the converted type (that might differ from 21799ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek/// ToType in its cv-qualifiers at some level) into ConvertedType. 21800518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redlbool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 21810518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl QualType ToType, 21820518999d3adcc289997bd974dce90cc97f5c1c44Sebastian Redl bool InOverloadResolution, 2183d457589fc69dc7a9c80cd74d317c0b81a35a27c9Sebastian Redl QualType &ConvertedType) { 21849ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 218577ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (!ToTypePtr) 218677ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek return false; 21871237c673c07f9d827129ba02720108816abde562Ted Kremenek 21885549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 218977ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek if (From->isNullPointerConstant(Context, 21901237c673c07f9d827129ba02720108816abde562Ted Kremenek InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 21915549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek : Expr::NPC_ValueDependentIsNull)) { 219277ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek ConvertedType = ToType; 219377ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek return true; 219477ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek } 21951237c673c07f9d827129ba02720108816abde562Ted Kremenek 21965549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek // Otherwise, both types have to be member pointers. 219777ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 21981237c673c07f9d827129ba02720108816abde562Ted Kremenek if (!FromTypePtr) 21995549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek return false; 220077ed8e4edf6ed78c53fb20ec3210aff2a59c9d87Ted Kremenek 22011237c673c07f9d827129ba02720108816abde562Ted Kremenek // A pointer to member of B can be converted to a pointer to member of D, 22021237c673c07f9d827129ba02720108816abde562Ted Kremenek // where D is derived from B (C++ 4.11p2). 22035549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek QualType FromClass(FromTypePtr->getClass(), 0); 22045549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek QualType ToClass(ToTypePtr->getClass(), 0); 22051237c673c07f9d827129ba02720108816abde562Ted Kremenek 2206213541a68a3e137d11d2cefb612c6cdb410d7e8eNate Begeman if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 22075549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) && 22085549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek IsDerivedFrom(ToClass, FromClass)) { 22091237c673c07f9d827129ba02720108816abde562Ted Kremenek ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 22101237c673c07f9d827129ba02720108816abde562Ted Kremenek ToClass.getTypePtr()); 22115549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek return true; 22125549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek } 22131237c673c07f9d827129ba02720108816abde562Ted Kremenek 22141237c673c07f9d827129ba02720108816abde562Ted Kremenek return false; 22155549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek} 22165549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek 22171237c673c07f9d827129ba02720108816abde562Ted Kremenek/// CheckMemberPointerConversion - Check the member pointer conversion from the 22181237c673c07f9d827129ba02720108816abde562Ted Kremenek/// expression From to the type ToType. This routine checks for ambiguous or 22191237c673c07f9d827129ba02720108816abde562Ted Kremenek/// virtual or inaccessible base-to-derived member pointer conversions 22205549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek/// for which IsMemberPointerConversion has already returned true. It returns 22211237c673c07f9d827129ba02720108816abde562Ted Kremenek/// true and produces a diagnostic if there was an error, or returns false 22221237c673c07f9d827129ba02720108816abde562Ted Kremenek/// otherwise. 22235549976193e34417d4474a5f4a514268ef6666c7Ted Kremenekbool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 22241237c673c07f9d827129ba02720108816abde562Ted Kremenek CastKind &Kind, 22251237c673c07f9d827129ba02720108816abde562Ted Kremenek CXXCastPath &BasePath, 22261237c673c07f9d827129ba02720108816abde562Ted Kremenek bool IgnoreBaseAccess) { 22271237c673c07f9d827129ba02720108816abde562Ted Kremenek QualType FromType = From->getType(); 22285549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 22291237c673c07f9d827129ba02720108816abde562Ted Kremenek if (!FromPtrType) { 22301237c673c07f9d827129ba02720108816abde562Ted Kremenek // This must be a null pointer to member pointer conversion 22315549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek assert(From->isNullPointerConstant(Context, 22321237c673c07f9d827129ba02720108816abde562Ted Kremenek Expr::NPC_ValueDependentIsNull) && 22331237c673c07f9d827129ba02720108816abde562Ted Kremenek "Expr must be null pointer constant!"); 22341237c673c07f9d827129ba02720108816abde562Ted Kremenek Kind = CK_NullToMemberPointer; 22359ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek return false; 22369ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek } 22371237c673c07f9d827129ba02720108816abde562Ted Kremenek 22381237c673c07f9d827129ba02720108816abde562Ted Kremenek const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 22395549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek assert(ToPtrType && "No member pointer cast has a target type " 22405549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek "that is not a member pointer."); 22411237c673c07f9d827129ba02720108816abde562Ted Kremenek 22421237c673c07f9d827129ba02720108816abde562Ted Kremenek QualType FromClass = QualType(FromPtrType->getClass(), 0); 22439ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek QualType ToClass = QualType(ToPtrType->getClass(), 0); 22449ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek 22459ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek // FIXME: What about dependent types? 22469ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek assert(FromClass->isRecordType() && "Pointer into non-class."); 22479ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek assert(ToClass->isRecordType() && "Pointer into non-class."); 22489ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek 22499ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 22501237c673c07f9d827129ba02720108816abde562Ted Kremenek /*DetectVirtual=*/true); 22511237c673c07f9d827129ba02720108816abde562Ted Kremenek bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 22525549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek assert(DerivationOkay && 22535549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek "Should not have been called if derivation isn't OK."); 22542d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor (void)DerivationOkay; 22552d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor 22562d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 22572d8b273470684a9cd47f0ce24743cc1f71ef7cbcDouglas Gregor getUnqualifiedType())) { 22581237c673c07f9d827129ba02720108816abde562Ted Kremenek std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2259d38617c8a50f9729c254ab76cd359af797c6739bEli Friedman Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2260d38617c8a50f9729c254ab76cd359af797c6739bEli Friedman << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 22615549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek return true; 2262d38617c8a50f9729c254ab76cd359af797c6739bEli Friedman } 2263d38617c8a50f9729c254ab76cd359af797c6739bEli Friedman 22645549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2265d38617c8a50f9729c254ab76cd359af797c6739bEli Friedman Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2266d38617c8a50f9729c254ab76cd359af797c6739bEli Friedman << FromClass << ToClass << QualType(VBase, 0) 22677c50aca2fe36f6daa9bf1c8c428f30e72f96470aAnders Carlsson << From->getSourceRange(); 22685549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek return true; 22695549976193e34417d4474a5f4a514268ef6666c7Ted Kremenek } 22707c50aca2fe36f6daa9bf1c8c428f30e72f96470aAnders Carlsson 227166b5a8a39088598c01a9fa6f032dc908612dc8ecAnders Carlsson if (!IgnoreBaseAccess) 2272ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2273ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek Paths.front(), 2274ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek diag::err_downcast_from_inaccessible_base); 2275ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek 2276ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek // Must be a base to derived member conversion. 2277ba7bc5584b8d46f4e8deb3a9d363256908fa86eaTed Kremenek BuildBasePathArray(Paths, BasePath); 227866b5a8a39088598c01a9fa6f032dc908612dc8ecAnders Carlsson Kind = CK_BaseToDerivedMemberPointer; 22793498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor return false; 228005c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor} 228105c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor 228205c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// IsQualificationConversion - Determines whether the conversion from 228305c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// an rvalue of type FromType to ToType is a qualification conversion 228405c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// (C++ 4.4). 228505c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// 228605c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 228705c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// when the qualification conversion involves a change in the Objective-C 228805c13a3411782108d65aab3c77b1a231a4963bc0Douglas Gregor/// object lifetime. 22893498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregorbool 22901eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpSema::IsQualificationConversion(QualType FromType, QualType ToType, 22911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump bool CStyle, bool &ObjCLifetimeConversion) { 22923498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor FromType = Context.getCanonicalType(FromType); 22933498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor ToType = Context.getCanonicalType(ToType); 22941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump ObjCLifetimeConversion = false; 22951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump 22963498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor // If FromType and ToType are the same type, this is not a 22973498bdb9e9cb300de74c7b51c92608e2902b2348Douglas Gregor // qualification conversion. 22982ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 22992ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman return false; 23002ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman 23012ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman // (C++ 4.4p4): 23022ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman // A conversion can add cv-qualifiers at levels other than the first 23032ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman // in multi-level pointers, subject to the following rules: [...] 23042ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman bool PreviousToQualsIncludeConst = true; 23052ef13e5abef0570a9f567b4671367275c05d4d34Nate Begeman bool UnwrappedAnyPointer = false; 23061237c673c07f9d827129ba02720108816abde562Ted Kremenek while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 23071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // Within each iteration of the loop, we check the qualifiers to 2308c6c16af963eddc3e9b75b5d2614d069e1162fe27Chris Lattner // determine if this still looks like a qualification 23099ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek // conversion. Then, if all is well, we unwrap one more level of 23109ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek // pointers or pointers-to-members and do it all again 2311c6c16af963eddc3e9b75b5d2614d069e1162fe27Chris Lattner // until there are no more pointers or pointers-to-members left to 23129ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek // unwrap. 23131237c673c07f9d827129ba02720108816abde562Ted Kremenek UnwrappedAnyPointer = true; 23141237c673c07f9d827129ba02720108816abde562Ted Kremenek 23159ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek Qualifiers FromQuals = FromType.getQualifiers(); 23169ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek Qualifiers ToQuals = ToType.getQualifiers(); 23171237c673c07f9d827129ba02720108816abde562Ted Kremenek 2318b62f6813406a03bf8a371c4e46c9fad51d102121Fariborz Jahanian // Objective-C ARC: 23191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump // Check Objective-C lifetime conversions. 23209ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 23219ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek UnwrappedAnyPointer) { 23229ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 23239ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek ObjCLifetimeConversion = true; 23249ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek FromQuals.removeObjCLifetime(); 2325b62f6813406a03bf8a371c4e46c9fad51d102121Fariborz Jahanian ToQuals.removeObjCLifetime(); 2326390d50a725497e99247dc104a7d2c2a255d3af14Fariborz Jahanian } else { 23279ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek // Qualification conversions cannot cast between different 23289ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek // Objective-C lifetime qualifiers. 23299ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek return false; 23309ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek } 23319ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek } 23329ac5928abeb3a47592201e1c30fe2930c20a507eTed Kremenek 2333390d50a725497e99247dc104a7d2c2a255d3af14Fariborz Jahanian // Allow addition/removal of GC attributes but not changing GC attributes. 2334563477da25f824e37c535131695dc4dc9b68c465Steve Naroff if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 23351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 233604badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor FromQuals.removeObjCGCAttr(); 233704badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor ToQuals.removeObjCGCAttr(); 233804badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor } 2339563477da25f824e37c535131695dc4dc9b68c465Steve Naroff 2340563477da25f824e37c535131695dc4dc9b68c465Steve Naroff // -- for every j > 0, if const is in cv 1,j then const is in cv 234104badcf84c8d504d8491c7c7e29b58f52cb16640Douglas Gregor // 2,j, and similarly for volatile. 2342563477da25f824e37c535131695dc4dc9b68c465Steve Naroff if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2343563477da25f824e37c535131695dc4dc9b68c465Steve Naroff return false; 23444eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff 234556ee6896f2efebffb4a2cce5a7610cdf1eddbbbeSteve Naroff // -- if the cv 1,j and cv 2,j are different, then const is in 234656ee6896f2efebffb4a2cce5a7610cdf1eddbbbeSteve Naroff // every cv for 0 < k < j. 23474eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 23489da13f9ddb2567e36f4bbee7b3c32f54aeb76d5bTed Kremenek && !PreviousToQualsIncludeConst) 23499da13f9ddb2567e36f4bbee7b3c32f54aeb76d5bTed Kremenek return false; 2350 2351 // Keep track of whether all prior cv-qualifiers in the "to" type 2352 // include const. 2353 PreviousToQualsIncludeConst 2354 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2355 } 2356 2357 // We are left with FromType and ToType being the pointee types 2358 // after unwrapping the original FromType and ToType the same number 2359 // of types. If we unwrapped any pointers, and if FromType and 2360 // ToType have the same unqualified type (since we checked 2361 // qualifiers above), then this is a qualification conversion. 2362 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2363} 2364 2365/// Determines whether there is a user-defined conversion sequence 2366/// (C++ [over.ics.user]) that converts expression From to the type 2367/// ToType. If such a conversion exists, User will contain the 2368/// user-defined conversion sequence that performs such a conversion 2369/// and this routine will return true. Otherwise, this routine returns 2370/// false and User is unspecified. 2371/// 2372/// \param AllowExplicit true if the conversion should consider C++0x 2373/// "explicit" conversion functions as well as non-explicit conversion 2374/// functions (C++0x [class.conv.fct]p2). 2375static OverloadingResult 2376IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2377 UserDefinedConversionSequence& User, 2378 OverloadCandidateSet& CandidateSet, 2379 bool AllowExplicit) { 2380 // Whether we will only visit constructors. 2381 bool ConstructorsOnly = false; 2382 2383 // If the type we are conversion to is a class type, enumerate its 2384 // constructors. 2385 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2386 // C++ [over.match.ctor]p1: 2387 // When objects of class type are direct-initialized (8.5), or 2388 // copy-initialized from an expression of the same or a 2389 // derived class type (8.5), overload resolution selects the 2390 // constructor. [...] For copy-initialization, the candidate 2391 // functions are all the converting constructors (12.3.1) of 2392 // that class. The argument list is the expression-list within 2393 // the parentheses of the initializer. 2394 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2395 (From->getType()->getAs<RecordType>() && 2396 S.IsDerivedFrom(From->getType(), ToType))) 2397 ConstructorsOnly = true; 2398 2399 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()); 2400 // RequireCompleteType may have returned true due to some invalid decl 2401 // during template instantiation, but ToType may be complete enough now 2402 // to try to recover. 2403 if (ToType->isIncompleteType()) { 2404 // We're not going to find any constructors. 2405 } else if (CXXRecordDecl *ToRecordDecl 2406 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2407 DeclContext::lookup_iterator Con, ConEnd; 2408 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2409 Con != ConEnd; ++Con) { 2410 NamedDecl *D = *Con; 2411 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2412 2413 // Find the constructor (which may be a template). 2414 CXXConstructorDecl *Constructor = 0; 2415 FunctionTemplateDecl *ConstructorTmpl 2416 = dyn_cast<FunctionTemplateDecl>(D); 2417 if (ConstructorTmpl) 2418 Constructor 2419 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2420 else 2421 Constructor = cast<CXXConstructorDecl>(D); 2422 2423 if (!Constructor->isInvalidDecl() && 2424 Constructor->isConvertingConstructor(AllowExplicit)) { 2425 if (ConstructorTmpl) 2426 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2427 /*ExplicitArgs*/ 0, 2428 &From, 1, CandidateSet, 2429 /*SuppressUserConversions=*/ 2430 !ConstructorsOnly); 2431 else 2432 // Allow one user-defined conversion when user specifies a 2433 // From->ToType conversion via an static cast (c-style, etc). 2434 S.AddOverloadCandidate(Constructor, FoundDecl, 2435 &From, 1, CandidateSet, 2436 /*SuppressUserConversions=*/ 2437 !ConstructorsOnly); 2438 } 2439 } 2440 } 2441 } 2442 2443 // Enumerate conversion functions, if we're allowed to. 2444 if (ConstructorsOnly) { 2445 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 2446 S.PDiag(0) << From->getSourceRange())) { 2447 // No conversion functions from incomplete types. 2448 } else if (const RecordType *FromRecordType 2449 = From->getType()->getAs<RecordType>()) { 2450 if (CXXRecordDecl *FromRecordDecl 2451 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 2452 // Add all of the conversion functions as candidates. 2453 const UnresolvedSetImpl *Conversions 2454 = FromRecordDecl->getVisibleConversionFunctions(); 2455 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2456 E = Conversions->end(); I != E; ++I) { 2457 DeclAccessPair FoundDecl = I.getPair(); 2458 NamedDecl *D = FoundDecl.getDecl(); 2459 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 2460 if (isa<UsingShadowDecl>(D)) 2461 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2462 2463 CXXConversionDecl *Conv; 2464 FunctionTemplateDecl *ConvTemplate; 2465 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 2466 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2467 else 2468 Conv = cast<CXXConversionDecl>(D); 2469 2470 if (AllowExplicit || !Conv->isExplicit()) { 2471 if (ConvTemplate) 2472 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 2473 ActingContext, From, ToType, 2474 CandidateSet); 2475 else 2476 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 2477 From, ToType, CandidateSet); 2478 } 2479 } 2480 } 2481 } 2482 2483 OverloadCandidateSet::iterator Best; 2484 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2485 case OR_Success: 2486 // Record the standard conversion we used and the conversion function. 2487 if (CXXConstructorDecl *Constructor 2488 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 2489 S.MarkDeclarationReferenced(From->getLocStart(), Constructor); 2490 2491 // C++ [over.ics.user]p1: 2492 // If the user-defined conversion is specified by a 2493 // constructor (12.3.1), the initial standard conversion 2494 // sequence converts the source type to the type required by 2495 // the argument of the constructor. 2496 // 2497 QualType ThisType = Constructor->getThisType(S.Context); 2498 if (Best->Conversions[0].isEllipsis()) 2499 User.EllipsisConversion = true; 2500 else { 2501 User.Before = Best->Conversions[0].Standard; 2502 User.EllipsisConversion = false; 2503 } 2504 User.ConversionFunction = Constructor; 2505 User.FoundConversionFunction = Best->FoundDecl.getDecl(); 2506 User.After.setAsIdentityConversion(); 2507 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2508 User.After.setAllToTypes(ToType); 2509 return OR_Success; 2510 } else if (CXXConversionDecl *Conversion 2511 = dyn_cast<CXXConversionDecl>(Best->Function)) { 2512 S.MarkDeclarationReferenced(From->getLocStart(), Conversion); 2513 2514 // C++ [over.ics.user]p1: 2515 // 2516 // [...] If the user-defined conversion is specified by a 2517 // conversion function (12.3.2), the initial standard 2518 // conversion sequence converts the source type to the 2519 // implicit object parameter of the conversion function. 2520 User.Before = Best->Conversions[0].Standard; 2521 User.ConversionFunction = Conversion; 2522 User.FoundConversionFunction = Best->FoundDecl.getDecl(); 2523 User.EllipsisConversion = false; 2524 2525 // C++ [over.ics.user]p2: 2526 // The second standard conversion sequence converts the 2527 // result of the user-defined conversion to the target type 2528 // for the sequence. Since an implicit conversion sequence 2529 // is an initialization, the special rules for 2530 // initialization by user-defined conversion apply when 2531 // selecting the best user-defined conversion for a 2532 // user-defined conversion sequence (see 13.3.3 and 2533 // 13.3.3.1). 2534 User.After = Best->FinalConversion; 2535 return OR_Success; 2536 } else { 2537 llvm_unreachable("Not a constructor or conversion function?"); 2538 return OR_No_Viable_Function; 2539 } 2540 2541 case OR_No_Viable_Function: 2542 return OR_No_Viable_Function; 2543 case OR_Deleted: 2544 // No conversion here! We're done. 2545 return OR_Deleted; 2546 2547 case OR_Ambiguous: 2548 return OR_Ambiguous; 2549 } 2550 2551 return OR_No_Viable_Function; 2552} 2553 2554bool 2555Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 2556 ImplicitConversionSequence ICS; 2557 OverloadCandidateSet CandidateSet(From->getExprLoc()); 2558 OverloadingResult OvResult = 2559 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 2560 CandidateSet, false); 2561 if (OvResult == OR_Ambiguous) 2562 Diag(From->getSourceRange().getBegin(), 2563 diag::err_typecheck_ambiguous_condition) 2564 << From->getType() << ToType << From->getSourceRange(); 2565 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 2566 Diag(From->getSourceRange().getBegin(), 2567 diag::err_typecheck_nonviable_condition) 2568 << From->getType() << ToType << From->getSourceRange(); 2569 else 2570 return false; 2571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1); 2572 return true; 2573} 2574 2575/// CompareImplicitConversionSequences - Compare two implicit 2576/// conversion sequences to determine whether one is better than the 2577/// other or if they are indistinguishable (C++ 13.3.3.2). 2578static ImplicitConversionSequence::CompareKind 2579CompareImplicitConversionSequences(Sema &S, 2580 const ImplicitConversionSequence& ICS1, 2581 const ImplicitConversionSequence& ICS2) 2582{ 2583 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 2584 // conversion sequences (as defined in 13.3.3.1) 2585 // -- a standard conversion sequence (13.3.3.1.1) is a better 2586 // conversion sequence than a user-defined conversion sequence or 2587 // an ellipsis conversion sequence, and 2588 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 2589 // conversion sequence than an ellipsis conversion sequence 2590 // (13.3.3.1.3). 2591 // 2592 // C++0x [over.best.ics]p10: 2593 // For the purpose of ranking implicit conversion sequences as 2594 // described in 13.3.3.2, the ambiguous conversion sequence is 2595 // treated as a user-defined sequence that is indistinguishable 2596 // from any other user-defined conversion sequence. 2597 if (ICS1.getKindRank() < ICS2.getKindRank()) 2598 return ImplicitConversionSequence::Better; 2599 else if (ICS2.getKindRank() < ICS1.getKindRank()) 2600 return ImplicitConversionSequence::Worse; 2601 2602 // The following checks require both conversion sequences to be of 2603 // the same kind. 2604 if (ICS1.getKind() != ICS2.getKind()) 2605 return ImplicitConversionSequence::Indistinguishable; 2606 2607 // Two implicit conversion sequences of the same form are 2608 // indistinguishable conversion sequences unless one of the 2609 // following rules apply: (C++ 13.3.3.2p3): 2610 if (ICS1.isStandard()) 2611 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard); 2612 else if (ICS1.isUserDefined()) { 2613 // User-defined conversion sequence U1 is a better conversion 2614 // sequence than another user-defined conversion sequence U2 if 2615 // they contain the same user-defined conversion function or 2616 // constructor and if the second standard conversion sequence of 2617 // U1 is better than the second standard conversion sequence of 2618 // U2 (C++ 13.3.3.2p3). 2619 if (ICS1.UserDefined.ConversionFunction == 2620 ICS2.UserDefined.ConversionFunction) 2621 return CompareStandardConversionSequences(S, 2622 ICS1.UserDefined.After, 2623 ICS2.UserDefined.After); 2624 } 2625 2626 return ImplicitConversionSequence::Indistinguishable; 2627} 2628 2629static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 2630 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 2631 Qualifiers Quals; 2632 T1 = Context.getUnqualifiedArrayType(T1, Quals); 2633 T2 = Context.getUnqualifiedArrayType(T2, Quals); 2634 } 2635 2636 return Context.hasSameUnqualifiedType(T1, T2); 2637} 2638 2639// Per 13.3.3.2p3, compare the given standard conversion sequences to 2640// determine if one is a proper subset of the other. 2641static ImplicitConversionSequence::CompareKind 2642compareStandardConversionSubsets(ASTContext &Context, 2643 const StandardConversionSequence& SCS1, 2644 const StandardConversionSequence& SCS2) { 2645 ImplicitConversionSequence::CompareKind Result 2646 = ImplicitConversionSequence::Indistinguishable; 2647 2648 // the identity conversion sequence is considered to be a subsequence of 2649 // any non-identity conversion sequence 2650 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 2651 return ImplicitConversionSequence::Better; 2652 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 2653 return ImplicitConversionSequence::Worse; 2654 2655 if (SCS1.Second != SCS2.Second) { 2656 if (SCS1.Second == ICK_Identity) 2657 Result = ImplicitConversionSequence::Better; 2658 else if (SCS2.Second == ICK_Identity) 2659 Result = ImplicitConversionSequence::Worse; 2660 else 2661 return ImplicitConversionSequence::Indistinguishable; 2662 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 2663 return ImplicitConversionSequence::Indistinguishable; 2664 2665 if (SCS1.Third == SCS2.Third) { 2666 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 2667 : ImplicitConversionSequence::Indistinguishable; 2668 } 2669 2670 if (SCS1.Third == ICK_Identity) 2671 return Result == ImplicitConversionSequence::Worse 2672 ? ImplicitConversionSequence::Indistinguishable 2673 : ImplicitConversionSequence::Better; 2674 2675 if (SCS2.Third == ICK_Identity) 2676 return Result == ImplicitConversionSequence::Better 2677 ? ImplicitConversionSequence::Indistinguishable 2678 : ImplicitConversionSequence::Worse; 2679 2680 return ImplicitConversionSequence::Indistinguishable; 2681} 2682 2683/// \brief Determine whether one of the given reference bindings is better 2684/// than the other based on what kind of bindings they are. 2685static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 2686 const StandardConversionSequence &SCS2) { 2687 // C++0x [over.ics.rank]p3b4: 2688 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 2689 // implicit object parameter of a non-static member function declared 2690 // without a ref-qualifier, and *either* S1 binds an rvalue reference 2691 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 2692 // lvalue reference to a function lvalue and S2 binds an rvalue 2693 // reference*. 2694 // 2695 // FIXME: Rvalue references. We're going rogue with the above edits, 2696 // because the semantics in the current C++0x working paper (N3225 at the 2697 // time of this writing) break the standard definition of std::forward 2698 // and std::reference_wrapper when dealing with references to functions. 2699 // Proposed wording changes submitted to CWG for consideration. 2700 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 2701 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 2702 return false; 2703 2704 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 2705 SCS2.IsLvalueReference) || 2706 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 2707 !SCS2.IsLvalueReference); 2708} 2709 2710/// CompareStandardConversionSequences - Compare two standard 2711/// conversion sequences to determine whether one is better than the 2712/// other or if they are indistinguishable (C++ 13.3.3.2p3). 2713static ImplicitConversionSequence::CompareKind 2714CompareStandardConversionSequences(Sema &S, 2715 const StandardConversionSequence& SCS1, 2716 const StandardConversionSequence& SCS2) 2717{ 2718 // Standard conversion sequence S1 is a better conversion sequence 2719 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 2720 2721 // -- S1 is a proper subsequence of S2 (comparing the conversion 2722 // sequences in the canonical form defined by 13.3.3.1.1, 2723 // excluding any Lvalue Transformation; the identity conversion 2724 // sequence is considered to be a subsequence of any 2725 // non-identity conversion sequence) or, if not that, 2726 if (ImplicitConversionSequence::CompareKind CK 2727 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 2728 return CK; 2729 2730 // -- the rank of S1 is better than the rank of S2 (by the rules 2731 // defined below), or, if not that, 2732 ImplicitConversionRank Rank1 = SCS1.getRank(); 2733 ImplicitConversionRank Rank2 = SCS2.getRank(); 2734 if (Rank1 < Rank2) 2735 return ImplicitConversionSequence::Better; 2736 else if (Rank2 < Rank1) 2737 return ImplicitConversionSequence::Worse; 2738 2739 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 2740 // are indistinguishable unless one of the following rules 2741 // applies: 2742 2743 // A conversion that is not a conversion of a pointer, or 2744 // pointer to member, to bool is better than another conversion 2745 // that is such a conversion. 2746 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 2747 return SCS2.isPointerConversionToBool() 2748 ? ImplicitConversionSequence::Better 2749 : ImplicitConversionSequence::Worse; 2750 2751 // C++ [over.ics.rank]p4b2: 2752 // 2753 // If class B is derived directly or indirectly from class A, 2754 // conversion of B* to A* is better than conversion of B* to 2755 // void*, and conversion of A* to void* is better than conversion 2756 // of B* to void*. 2757 bool SCS1ConvertsToVoid 2758 = SCS1.isPointerConversionToVoidPointer(S.Context); 2759 bool SCS2ConvertsToVoid 2760 = SCS2.isPointerConversionToVoidPointer(S.Context); 2761 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 2762 // Exactly one of the conversion sequences is a conversion to 2763 // a void pointer; it's the worse conversion. 2764 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 2765 : ImplicitConversionSequence::Worse; 2766 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 2767 // Neither conversion sequence converts to a void pointer; compare 2768 // their derived-to-base conversions. 2769 if (ImplicitConversionSequence::CompareKind DerivedCK 2770 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 2771 return DerivedCK; 2772 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 2773 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 2774 // Both conversion sequences are conversions to void 2775 // pointers. Compare the source types to determine if there's an 2776 // inheritance relationship in their sources. 2777 QualType FromType1 = SCS1.getFromType(); 2778 QualType FromType2 = SCS2.getFromType(); 2779 2780 // Adjust the types we're converting from via the array-to-pointer 2781 // conversion, if we need to. 2782 if (SCS1.First == ICK_Array_To_Pointer) 2783 FromType1 = S.Context.getArrayDecayedType(FromType1); 2784 if (SCS2.First == ICK_Array_To_Pointer) 2785 FromType2 = S.Context.getArrayDecayedType(FromType2); 2786 2787 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 2788 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 2789 2790 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 2791 return ImplicitConversionSequence::Better; 2792 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 2793 return ImplicitConversionSequence::Worse; 2794 2795 // Objective-C++: If one interface is more specific than the 2796 // other, it is the better one. 2797 const ObjCObjectPointerType* FromObjCPtr1 2798 = FromType1->getAs<ObjCObjectPointerType>(); 2799 const ObjCObjectPointerType* FromObjCPtr2 2800 = FromType2->getAs<ObjCObjectPointerType>(); 2801 if (FromObjCPtr1 && FromObjCPtr2) { 2802 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 2803 FromObjCPtr2); 2804 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 2805 FromObjCPtr1); 2806 if (AssignLeft != AssignRight) { 2807 return AssignLeft? ImplicitConversionSequence::Better 2808 : ImplicitConversionSequence::Worse; 2809 } 2810 } 2811 } 2812 2813 // Compare based on qualification conversions (C++ 13.3.3.2p3, 2814 // bullet 3). 2815 if (ImplicitConversionSequence::CompareKind QualCK 2816 = CompareQualificationConversions(S, SCS1, SCS2)) 2817 return QualCK; 2818 2819 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 2820 // Check for a better reference binding based on the kind of bindings. 2821 if (isBetterReferenceBindingKind(SCS1, SCS2)) 2822 return ImplicitConversionSequence::Better; 2823 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 2824 return ImplicitConversionSequence::Worse; 2825 2826 // C++ [over.ics.rank]p3b4: 2827 // -- S1 and S2 are reference bindings (8.5.3), and the types to 2828 // which the references refer are the same type except for 2829 // top-level cv-qualifiers, and the type to which the reference 2830 // initialized by S2 refers is more cv-qualified than the type 2831 // to which the reference initialized by S1 refers. 2832 QualType T1 = SCS1.getToType(2); 2833 QualType T2 = SCS2.getToType(2); 2834 T1 = S.Context.getCanonicalType(T1); 2835 T2 = S.Context.getCanonicalType(T2); 2836 Qualifiers T1Quals, T2Quals; 2837 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 2838 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 2839 if (UnqualT1 == UnqualT2) { 2840 // Objective-C++ ARC: If the references refer to objects with different 2841 // lifetimes, prefer bindings that don't change lifetime. 2842 if (SCS1.ObjCLifetimeConversionBinding != 2843 SCS2.ObjCLifetimeConversionBinding) { 2844 return SCS1.ObjCLifetimeConversionBinding 2845 ? ImplicitConversionSequence::Worse 2846 : ImplicitConversionSequence::Better; 2847 } 2848 2849 // If the type is an array type, promote the element qualifiers to the 2850 // type for comparison. 2851 if (isa<ArrayType>(T1) && T1Quals) 2852 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 2853 if (isa<ArrayType>(T2) && T2Quals) 2854 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 2855 if (T2.isMoreQualifiedThan(T1)) 2856 return ImplicitConversionSequence::Better; 2857 else if (T1.isMoreQualifiedThan(T2)) 2858 return ImplicitConversionSequence::Worse; 2859 } 2860 } 2861 2862 return ImplicitConversionSequence::Indistinguishable; 2863} 2864 2865/// CompareQualificationConversions - Compares two standard conversion 2866/// sequences to determine whether they can be ranked based on their 2867/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 2868ImplicitConversionSequence::CompareKind 2869CompareQualificationConversions(Sema &S, 2870 const StandardConversionSequence& SCS1, 2871 const StandardConversionSequence& SCS2) { 2872 // C++ 13.3.3.2p3: 2873 // -- S1 and S2 differ only in their qualification conversion and 2874 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 2875 // cv-qualification signature of type T1 is a proper subset of 2876 // the cv-qualification signature of type T2, and S1 is not the 2877 // deprecated string literal array-to-pointer conversion (4.2). 2878 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 2879 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 2880 return ImplicitConversionSequence::Indistinguishable; 2881 2882 // FIXME: the example in the standard doesn't use a qualification 2883 // conversion (!) 2884 QualType T1 = SCS1.getToType(2); 2885 QualType T2 = SCS2.getToType(2); 2886 T1 = S.Context.getCanonicalType(T1); 2887 T2 = S.Context.getCanonicalType(T2); 2888 Qualifiers T1Quals, T2Quals; 2889 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 2890 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 2891 2892 // If the types are the same, we won't learn anything by unwrapped 2893 // them. 2894 if (UnqualT1 == UnqualT2) 2895 return ImplicitConversionSequence::Indistinguishable; 2896 2897 // If the type is an array type, promote the element qualifiers to the type 2898 // for comparison. 2899 if (isa<ArrayType>(T1) && T1Quals) 2900 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 2901 if (isa<ArrayType>(T2) && T2Quals) 2902 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 2903 2904 ImplicitConversionSequence::CompareKind Result 2905 = ImplicitConversionSequence::Indistinguishable; 2906 2907 // Objective-C++ ARC: 2908 // Prefer qualification conversions not involving a change in lifetime 2909 // to qualification conversions that do not change lifetime. 2910 if (SCS1.QualificationIncludesObjCLifetime != 2911 SCS2.QualificationIncludesObjCLifetime) { 2912 Result = SCS1.QualificationIncludesObjCLifetime 2913 ? ImplicitConversionSequence::Worse 2914 : ImplicitConversionSequence::Better; 2915 } 2916 2917 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 2918 // Within each iteration of the loop, we check the qualifiers to 2919 // determine if this still looks like a qualification 2920 // conversion. Then, if all is well, we unwrap one more level of 2921 // pointers or pointers-to-members and do it all again 2922 // until there are no more pointers or pointers-to-members left 2923 // to unwrap. This essentially mimics what 2924 // IsQualificationConversion does, but here we're checking for a 2925 // strict subset of qualifiers. 2926 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 2927 // The qualifiers are the same, so this doesn't tell us anything 2928 // about how the sequences rank. 2929 ; 2930 else if (T2.isMoreQualifiedThan(T1)) { 2931 // T1 has fewer qualifiers, so it could be the better sequence. 2932 if (Result == ImplicitConversionSequence::Worse) 2933 // Neither has qualifiers that are a subset of the other's 2934 // qualifiers. 2935 return ImplicitConversionSequence::Indistinguishable; 2936 2937 Result = ImplicitConversionSequence::Better; 2938 } else if (T1.isMoreQualifiedThan(T2)) { 2939 // T2 has fewer qualifiers, so it could be the better sequence. 2940 if (Result == ImplicitConversionSequence::Better) 2941 // Neither has qualifiers that are a subset of the other's 2942 // qualifiers. 2943 return ImplicitConversionSequence::Indistinguishable; 2944 2945 Result = ImplicitConversionSequence::Worse; 2946 } else { 2947 // Qualifiers are disjoint. 2948 return ImplicitConversionSequence::Indistinguishable; 2949 } 2950 2951 // If the types after this point are equivalent, we're done. 2952 if (S.Context.hasSameUnqualifiedType(T1, T2)) 2953 break; 2954 } 2955 2956 // Check that the winning standard conversion sequence isn't using 2957 // the deprecated string literal array to pointer conversion. 2958 switch (Result) { 2959 case ImplicitConversionSequence::Better: 2960 if (SCS1.DeprecatedStringLiteralToCharPtr) 2961 Result = ImplicitConversionSequence::Indistinguishable; 2962 break; 2963 2964 case ImplicitConversionSequence::Indistinguishable: 2965 break; 2966 2967 case ImplicitConversionSequence::Worse: 2968 if (SCS2.DeprecatedStringLiteralToCharPtr) 2969 Result = ImplicitConversionSequence::Indistinguishable; 2970 break; 2971 } 2972 2973 return Result; 2974} 2975 2976/// CompareDerivedToBaseConversions - Compares two standard conversion 2977/// sequences to determine whether they can be ranked based on their 2978/// various kinds of derived-to-base conversions (C++ 2979/// [over.ics.rank]p4b3). As part of these checks, we also look at 2980/// conversions between Objective-C interface types. 2981ImplicitConversionSequence::CompareKind 2982CompareDerivedToBaseConversions(Sema &S, 2983 const StandardConversionSequence& SCS1, 2984 const StandardConversionSequence& SCS2) { 2985 QualType FromType1 = SCS1.getFromType(); 2986 QualType ToType1 = SCS1.getToType(1); 2987 QualType FromType2 = SCS2.getFromType(); 2988 QualType ToType2 = SCS2.getToType(1); 2989 2990 // Adjust the types we're converting from via the array-to-pointer 2991 // conversion, if we need to. 2992 if (SCS1.First == ICK_Array_To_Pointer) 2993 FromType1 = S.Context.getArrayDecayedType(FromType1); 2994 if (SCS2.First == ICK_Array_To_Pointer) 2995 FromType2 = S.Context.getArrayDecayedType(FromType2); 2996 2997 // Canonicalize all of the types. 2998 FromType1 = S.Context.getCanonicalType(FromType1); 2999 ToType1 = S.Context.getCanonicalType(ToType1); 3000 FromType2 = S.Context.getCanonicalType(FromType2); 3001 ToType2 = S.Context.getCanonicalType(ToType2); 3002 3003 // C++ [over.ics.rank]p4b3: 3004 // 3005 // If class B is derived directly or indirectly from class A and 3006 // class C is derived directly or indirectly from B, 3007 // 3008 // Compare based on pointer conversions. 3009 if (SCS1.Second == ICK_Pointer_Conversion && 3010 SCS2.Second == ICK_Pointer_Conversion && 3011 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3012 FromType1->isPointerType() && FromType2->isPointerType() && 3013 ToType1->isPointerType() && ToType2->isPointerType()) { 3014 QualType FromPointee1 3015 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3016 QualType ToPointee1 3017 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3018 QualType FromPointee2 3019 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3020 QualType ToPointee2 3021 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3022 3023 // -- conversion of C* to B* is better than conversion of C* to A*, 3024 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3025 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3026 return ImplicitConversionSequence::Better; 3027 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3028 return ImplicitConversionSequence::Worse; 3029 } 3030 3031 // -- conversion of B* to A* is better than conversion of C* to A*, 3032 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3033 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3034 return ImplicitConversionSequence::Better; 3035 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3036 return ImplicitConversionSequence::Worse; 3037 } 3038 } else if (SCS1.Second == ICK_Pointer_Conversion && 3039 SCS2.Second == ICK_Pointer_Conversion) { 3040 const ObjCObjectPointerType *FromPtr1 3041 = FromType1->getAs<ObjCObjectPointerType>(); 3042 const ObjCObjectPointerType *FromPtr2 3043 = FromType2->getAs<ObjCObjectPointerType>(); 3044 const ObjCObjectPointerType *ToPtr1 3045 = ToType1->getAs<ObjCObjectPointerType>(); 3046 const ObjCObjectPointerType *ToPtr2 3047 = ToType2->getAs<ObjCObjectPointerType>(); 3048 3049 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3050 // Apply the same conversion ranking rules for Objective-C pointer types 3051 // that we do for C++ pointers to class types. However, we employ the 3052 // Objective-C pseudo-subtyping relationship used for assignment of 3053 // Objective-C pointer types. 3054 bool FromAssignLeft 3055 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3056 bool FromAssignRight 3057 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3058 bool ToAssignLeft 3059 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3060 bool ToAssignRight 3061 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3062 3063 // A conversion to an a non-id object pointer type or qualified 'id' 3064 // type is better than a conversion to 'id'. 3065 if (ToPtr1->isObjCIdType() && 3066 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3067 return ImplicitConversionSequence::Worse; 3068 if (ToPtr2->isObjCIdType() && 3069 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3070 return ImplicitConversionSequence::Better; 3071 3072 // A conversion to a non-id object pointer type is better than a 3073 // conversion to a qualified 'id' type 3074 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3075 return ImplicitConversionSequence::Worse; 3076 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3077 return ImplicitConversionSequence::Better; 3078 3079 // A conversion to an a non-Class object pointer type or qualified 'Class' 3080 // type is better than a conversion to 'Class'. 3081 if (ToPtr1->isObjCClassType() && 3082 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3083 return ImplicitConversionSequence::Worse; 3084 if (ToPtr2->isObjCClassType() && 3085 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3086 return ImplicitConversionSequence::Better; 3087 3088 // A conversion to a non-Class object pointer type is better than a 3089 // conversion to a qualified 'Class' type. 3090 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3091 return ImplicitConversionSequence::Worse; 3092 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3093 return ImplicitConversionSequence::Better; 3094 3095 // -- "conversion of C* to B* is better than conversion of C* to A*," 3096 if (S.Context.hasSameType(FromType1, FromType2) && 3097 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3098 (ToAssignLeft != ToAssignRight)) 3099 return ToAssignLeft? ImplicitConversionSequence::Worse 3100 : ImplicitConversionSequence::Better; 3101 3102 // -- "conversion of B* to A* is better than conversion of C* to A*," 3103 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3104 (FromAssignLeft != FromAssignRight)) 3105 return FromAssignLeft? ImplicitConversionSequence::Better 3106 : ImplicitConversionSequence::Worse; 3107 } 3108 } 3109 3110 // Ranking of member-pointer types. 3111 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3112 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3113 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3114 const MemberPointerType * FromMemPointer1 = 3115 FromType1->getAs<MemberPointerType>(); 3116 const MemberPointerType * ToMemPointer1 = 3117 ToType1->getAs<MemberPointerType>(); 3118 const MemberPointerType * FromMemPointer2 = 3119 FromType2->getAs<MemberPointerType>(); 3120 const MemberPointerType * ToMemPointer2 = 3121 ToType2->getAs<MemberPointerType>(); 3122 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3123 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3124 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3125 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3126 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3127 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3128 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3129 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3130 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3131 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3132 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3133 return ImplicitConversionSequence::Worse; 3134 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3135 return ImplicitConversionSequence::Better; 3136 } 3137 // conversion of B::* to C::* is better than conversion of A::* to C::* 3138 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3139 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3140 return ImplicitConversionSequence::Better; 3141 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3142 return ImplicitConversionSequence::Worse; 3143 } 3144 } 3145 3146 if (SCS1.Second == ICK_Derived_To_Base) { 3147 // -- conversion of C to B is better than conversion of C to A, 3148 // -- binding of an expression of type C to a reference of type 3149 // B& is better than binding an expression of type C to a 3150 // reference of type A&, 3151 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3152 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3153 if (S.IsDerivedFrom(ToType1, ToType2)) 3154 return ImplicitConversionSequence::Better; 3155 else if (S.IsDerivedFrom(ToType2, ToType1)) 3156 return ImplicitConversionSequence::Worse; 3157 } 3158 3159 // -- conversion of B to A is better than conversion of C to A. 3160 // -- binding of an expression of type B to a reference of type 3161 // A& is better than binding an expression of type C to a 3162 // reference of type A&, 3163 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3164 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3165 if (S.IsDerivedFrom(FromType2, FromType1)) 3166 return ImplicitConversionSequence::Better; 3167 else if (S.IsDerivedFrom(FromType1, FromType2)) 3168 return ImplicitConversionSequence::Worse; 3169 } 3170 } 3171 3172 return ImplicitConversionSequence::Indistinguishable; 3173} 3174 3175/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3176/// determine whether they are reference-related, 3177/// reference-compatible, reference-compatible with added 3178/// qualification, or incompatible, for use in C++ initialization by 3179/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3180/// type, and the first type (T1) is the pointee type of the reference 3181/// type being initialized. 3182Sema::ReferenceCompareResult 3183Sema::CompareReferenceRelationship(SourceLocation Loc, 3184 QualType OrigT1, QualType OrigT2, 3185 bool &DerivedToBase, 3186 bool &ObjCConversion, 3187 bool &ObjCLifetimeConversion) { 3188 assert(!OrigT1->isReferenceType() && 3189 "T1 must be the pointee type of the reference type"); 3190 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3191 3192 QualType T1 = Context.getCanonicalType(OrigT1); 3193 QualType T2 = Context.getCanonicalType(OrigT2); 3194 Qualifiers T1Quals, T2Quals; 3195 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3196 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3197 3198 // C++ [dcl.init.ref]p4: 3199 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3200 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3201 // T1 is a base class of T2. 3202 DerivedToBase = false; 3203 ObjCConversion = false; 3204 ObjCLifetimeConversion = false; 3205 if (UnqualT1 == UnqualT2) { 3206 // Nothing to do. 3207 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) && 3208 IsDerivedFrom(UnqualT2, UnqualT1)) 3209 DerivedToBase = true; 3210 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3211 UnqualT2->isObjCObjectOrInterfaceType() && 3212 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3213 ObjCConversion = true; 3214 else 3215 return Ref_Incompatible; 3216 3217 // At this point, we know that T1 and T2 are reference-related (at 3218 // least). 3219 3220 // If the type is an array type, promote the element qualifiers to the type 3221 // for comparison. 3222 if (isa<ArrayType>(T1) && T1Quals) 3223 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3224 if (isa<ArrayType>(T2) && T2Quals) 3225 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3226 3227 // C++ [dcl.init.ref]p4: 3228 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3229 // reference-related to T2 and cv1 is the same cv-qualification 3230 // as, or greater cv-qualification than, cv2. For purposes of 3231 // overload resolution, cases for which cv1 is greater 3232 // cv-qualification than cv2 are identified as 3233 // reference-compatible with added qualification (see 13.3.3.2). 3234 // 3235 // Note that we also require equivalence of Objective-C GC and address-space 3236 // qualifiers when performing these computations, so that e.g., an int in 3237 // address space 1 is not reference-compatible with an int in address 3238 // space 2. 3239 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3240 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3241 T1Quals.removeObjCLifetime(); 3242 T2Quals.removeObjCLifetime(); 3243 ObjCLifetimeConversion = true; 3244 } 3245 3246 if (T1Quals == T2Quals) 3247 return Ref_Compatible; 3248 else if (T1Quals.compatiblyIncludes(T2Quals)) 3249 return Ref_Compatible_With_Added_Qualification; 3250 else 3251 return Ref_Related; 3252} 3253 3254/// \brief Look for a user-defined conversion to an value reference-compatible 3255/// with DeclType. Return true if something definite is found. 3256static bool 3257FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3258 QualType DeclType, SourceLocation DeclLoc, 3259 Expr *Init, QualType T2, bool AllowRvalues, 3260 bool AllowExplicit) { 3261 assert(T2->isRecordType() && "Can only find conversions of record types."); 3262 CXXRecordDecl *T2RecordDecl 3263 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3264 3265 OverloadCandidateSet CandidateSet(DeclLoc); 3266 const UnresolvedSetImpl *Conversions 3267 = T2RecordDecl->getVisibleConversionFunctions(); 3268 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3269 E = Conversions->end(); I != E; ++I) { 3270 NamedDecl *D = *I; 3271 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3272 if (isa<UsingShadowDecl>(D)) 3273 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3274 3275 FunctionTemplateDecl *ConvTemplate 3276 = dyn_cast<FunctionTemplateDecl>(D); 3277 CXXConversionDecl *Conv; 3278 if (ConvTemplate) 3279 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3280 else 3281 Conv = cast<CXXConversionDecl>(D); 3282 3283 // If this is an explicit conversion, and we're not allowed to consider 3284 // explicit conversions, skip it. 3285 if (!AllowExplicit && Conv->isExplicit()) 3286 continue; 3287 3288 if (AllowRvalues) { 3289 bool DerivedToBase = false; 3290 bool ObjCConversion = false; 3291 bool ObjCLifetimeConversion = false; 3292 if (!ConvTemplate && 3293 S.CompareReferenceRelationship( 3294 DeclLoc, 3295 Conv->getConversionType().getNonReferenceType() 3296 .getUnqualifiedType(), 3297 DeclType.getNonReferenceType().getUnqualifiedType(), 3298 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3299 Sema::Ref_Incompatible) 3300 continue; 3301 } else { 3302 // If the conversion function doesn't return a reference type, 3303 // it can't be considered for this conversion. An rvalue reference 3304 // is only acceptable if its referencee is a function type. 3305 3306 const ReferenceType *RefType = 3307 Conv->getConversionType()->getAs<ReferenceType>(); 3308 if (!RefType || 3309 (!RefType->isLValueReferenceType() && 3310 !RefType->getPointeeType()->isFunctionType())) 3311 continue; 3312 } 3313 3314 if (ConvTemplate) 3315 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 3316 Init, DeclType, CandidateSet); 3317 else 3318 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 3319 DeclType, CandidateSet); 3320 } 3321 3322 OverloadCandidateSet::iterator Best; 3323 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3324 case OR_Success: 3325 // C++ [over.ics.ref]p1: 3326 // 3327 // [...] If the parameter binds directly to the result of 3328 // applying a conversion function to the argument 3329 // expression, the implicit conversion sequence is a 3330 // user-defined conversion sequence (13.3.3.1.2), with the 3331 // second standard conversion sequence either an identity 3332 // conversion or, if the conversion function returns an 3333 // entity of a type that is a derived class of the parameter 3334 // type, a derived-to-base Conversion. 3335 if (!Best->FinalConversion.DirectBinding) 3336 return false; 3337 3338 if (Best->Function) 3339 S.MarkDeclarationReferenced(DeclLoc, Best->Function); 3340 ICS.setUserDefined(); 3341 ICS.UserDefined.Before = Best->Conversions[0].Standard; 3342 ICS.UserDefined.After = Best->FinalConversion; 3343 ICS.UserDefined.ConversionFunction = Best->Function; 3344 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl(); 3345 ICS.UserDefined.EllipsisConversion = false; 3346 assert(ICS.UserDefined.After.ReferenceBinding && 3347 ICS.UserDefined.After.DirectBinding && 3348 "Expected a direct reference binding!"); 3349 return true; 3350 3351 case OR_Ambiguous: 3352 ICS.setAmbiguous(); 3353 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3354 Cand != CandidateSet.end(); ++Cand) 3355 if (Cand->Viable) 3356 ICS.Ambiguous.addConversion(Cand->Function); 3357 return true; 3358 3359 case OR_No_Viable_Function: 3360 case OR_Deleted: 3361 // There was no suitable conversion, or we found a deleted 3362 // conversion; continue with other checks. 3363 return false; 3364 } 3365 3366 return false; 3367} 3368 3369/// \brief Compute an implicit conversion sequence for reference 3370/// initialization. 3371static ImplicitConversionSequence 3372TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType, 3373 SourceLocation DeclLoc, 3374 bool SuppressUserConversions, 3375 bool AllowExplicit) { 3376 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 3377 3378 // Most paths end in a failed conversion. 3379 ImplicitConversionSequence ICS; 3380 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 3381 3382 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 3383 QualType T2 = Init->getType(); 3384 3385 // If the initializer is the address of an overloaded function, try 3386 // to resolve the overloaded function. If all goes well, T2 is the 3387 // type of the resulting function. 3388 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 3389 DeclAccessPair Found; 3390 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 3391 false, Found)) 3392 T2 = Fn->getType(); 3393 } 3394 3395 // Compute some basic properties of the types and the initializer. 3396 bool isRValRef = DeclType->isRValueReferenceType(); 3397 bool DerivedToBase = false; 3398 bool ObjCConversion = false; 3399 bool ObjCLifetimeConversion = false; 3400 Expr::Classification InitCategory = Init->Classify(S.Context); 3401 Sema::ReferenceCompareResult RefRelationship 3402 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 3403 ObjCConversion, ObjCLifetimeConversion); 3404 3405 3406 // C++0x [dcl.init.ref]p5: 3407 // A reference to type "cv1 T1" is initialized by an expression 3408 // of type "cv2 T2" as follows: 3409 3410 // -- If reference is an lvalue reference and the initializer expression 3411 if (!isRValRef) { 3412 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 3413 // reference-compatible with "cv2 T2," or 3414 // 3415 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 3416 if (InitCategory.isLValue() && 3417 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 3418 // C++ [over.ics.ref]p1: 3419 // When a parameter of reference type binds directly (8.5.3) 3420 // to an argument expression, the implicit conversion sequence 3421 // is the identity conversion, unless the argument expression 3422 // has a type that is a derived class of the parameter type, 3423 // in which case the implicit conversion sequence is a 3424 // derived-to-base Conversion (13.3.3.1). 3425 ICS.setStandard(); 3426 ICS.Standard.First = ICK_Identity; 3427 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 3428 : ObjCConversion? ICK_Compatible_Conversion 3429 : ICK_Identity; 3430 ICS.Standard.Third = ICK_Identity; 3431 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 3432 ICS.Standard.setToType(0, T2); 3433 ICS.Standard.setToType(1, T1); 3434 ICS.Standard.setToType(2, T1); 3435 ICS.Standard.ReferenceBinding = true; 3436 ICS.Standard.DirectBinding = true; 3437 ICS.Standard.IsLvalueReference = !isRValRef; 3438 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3439 ICS.Standard.BindsToRvalue = false; 3440 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3441 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 3442 ICS.Standard.CopyConstructor = 0; 3443 3444 // Nothing more to do: the inaccessibility/ambiguity check for 3445 // derived-to-base conversions is suppressed when we're 3446 // computing the implicit conversion sequence (C++ 3447 // [over.best.ics]p2). 3448 return ICS; 3449 } 3450 3451 // -- has a class type (i.e., T2 is a class type), where T1 is 3452 // not reference-related to T2, and can be implicitly 3453 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 3454 // is reference-compatible with "cv3 T3" 92) (this 3455 // conversion is selected by enumerating the applicable 3456 // conversion functions (13.3.1.6) and choosing the best 3457 // one through overload resolution (13.3)), 3458 if (!SuppressUserConversions && T2->isRecordType() && 3459 !S.RequireCompleteType(DeclLoc, T2, 0) && 3460 RefRelationship == Sema::Ref_Incompatible) { 3461 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 3462 Init, T2, /*AllowRvalues=*/false, 3463 AllowExplicit)) 3464 return ICS; 3465 } 3466 } 3467 3468 // -- Otherwise, the reference shall be an lvalue reference to a 3469 // non-volatile const type (i.e., cv1 shall be const), or the reference 3470 // shall be an rvalue reference. 3471 // 3472 // We actually handle one oddity of C++ [over.ics.ref] at this 3473 // point, which is that, due to p2 (which short-circuits reference 3474 // binding by only attempting a simple conversion for non-direct 3475 // bindings) and p3's strange wording, we allow a const volatile 3476 // reference to bind to an rvalue. Hence the check for the presence 3477 // of "const" rather than checking for "const" being the only 3478 // qualifier. 3479 // This is also the point where rvalue references and lvalue inits no longer 3480 // go together. 3481 if (!isRValRef && !T1.isConstQualified()) 3482 return ICS; 3483 3484 // -- If the initializer expression 3485 // 3486 // -- is an xvalue, class prvalue, array prvalue or function 3487 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 3488 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 3489 (InitCategory.isXValue() || 3490 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 3491 (InitCategory.isLValue() && T2->isFunctionType()))) { 3492 ICS.setStandard(); 3493 ICS.Standard.First = ICK_Identity; 3494 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 3495 : ObjCConversion? ICK_Compatible_Conversion 3496 : ICK_Identity; 3497 ICS.Standard.Third = ICK_Identity; 3498 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 3499 ICS.Standard.setToType(0, T2); 3500 ICS.Standard.setToType(1, T1); 3501 ICS.Standard.setToType(2, T1); 3502 ICS.Standard.ReferenceBinding = true; 3503 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 3504 // binding unless we're binding to a class prvalue. 3505 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 3506 // allow the use of rvalue references in C++98/03 for the benefit of 3507 // standard library implementors; therefore, we need the xvalue check here. 3508 ICS.Standard.DirectBinding = 3509 S.getLangOptions().CPlusPlus0x || 3510 (InitCategory.isPRValue() && !T2->isRecordType()); 3511 ICS.Standard.IsLvalueReference = !isRValRef; 3512 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3513 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 3514 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3515 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 3516 ICS.Standard.CopyConstructor = 0; 3517 return ICS; 3518 } 3519 3520 // -- has a class type (i.e., T2 is a class type), where T1 is not 3521 // reference-related to T2, and can be implicitly converted to 3522 // an xvalue, class prvalue, or function lvalue of type 3523 // "cv3 T3", where "cv1 T1" is reference-compatible with 3524 // "cv3 T3", 3525 // 3526 // then the reference is bound to the value of the initializer 3527 // expression in the first case and to the result of the conversion 3528 // in the second case (or, in either case, to an appropriate base 3529 // class subobject). 3530 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 3531 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 3532 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 3533 Init, T2, /*AllowRvalues=*/true, 3534 AllowExplicit)) { 3535 // In the second case, if the reference is an rvalue reference 3536 // and the second standard conversion sequence of the 3537 // user-defined conversion sequence includes an lvalue-to-rvalue 3538 // conversion, the program is ill-formed. 3539 if (ICS.isUserDefined() && isRValRef && 3540 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 3541 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 3542 3543 return ICS; 3544 } 3545 3546 // -- Otherwise, a temporary of type "cv1 T1" is created and 3547 // initialized from the initializer expression using the 3548 // rules for a non-reference copy initialization (8.5). The 3549 // reference is then bound to the temporary. If T1 is 3550 // reference-related to T2, cv1 must be the same 3551 // cv-qualification as, or greater cv-qualification than, 3552 // cv2; otherwise, the program is ill-formed. 3553 if (RefRelationship == Sema::Ref_Related) { 3554 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3555 // we would be reference-compatible or reference-compatible with 3556 // added qualification. But that wasn't the case, so the reference 3557 // initialization fails. 3558 // 3559 // Note that we only want to check address spaces and cvr-qualifiers here. 3560 // ObjC GC and lifetime qualifiers aren't important. 3561 Qualifiers T1Quals = T1.getQualifiers(); 3562 Qualifiers T2Quals = T2.getQualifiers(); 3563 T1Quals.removeObjCGCAttr(); 3564 T1Quals.removeObjCLifetime(); 3565 T2Quals.removeObjCGCAttr(); 3566 T2Quals.removeObjCLifetime(); 3567 if (!T1Quals.compatiblyIncludes(T2Quals)) 3568 return ICS; 3569 } 3570 3571 // If at least one of the types is a class type, the types are not 3572 // related, and we aren't allowed any user conversions, the 3573 // reference binding fails. This case is important for breaking 3574 // recursion, since TryImplicitConversion below will attempt to 3575 // create a temporary through the use of a copy constructor. 3576 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 3577 (T1->isRecordType() || T2->isRecordType())) 3578 return ICS; 3579 3580 // If T1 is reference-related to T2 and the reference is an rvalue 3581 // reference, the initializer expression shall not be an lvalue. 3582 if (RefRelationship >= Sema::Ref_Related && 3583 isRValRef && Init->Classify(S.Context).isLValue()) 3584 return ICS; 3585 3586 // C++ [over.ics.ref]p2: 3587 // When a parameter of reference type is not bound directly to 3588 // an argument expression, the conversion sequence is the one 3589 // required to convert the argument expression to the 3590 // underlying type of the reference according to 3591 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3592 // to copy-initializing a temporary of the underlying type with 3593 // the argument expression. Any difference in top-level 3594 // cv-qualification is subsumed by the initialization itself 3595 // and does not constitute a conversion. 3596 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 3597 /*AllowExplicit=*/false, 3598 /*InOverloadResolution=*/false, 3599 /*CStyle=*/false, 3600 /*AllowObjCWritebackConversion=*/false); 3601 3602 // Of course, that's still a reference binding. 3603 if (ICS.isStandard()) { 3604 ICS.Standard.ReferenceBinding = true; 3605 ICS.Standard.IsLvalueReference = !isRValRef; 3606 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3607 ICS.Standard.BindsToRvalue = true; 3608 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3609 ICS.Standard.ObjCLifetimeConversionBinding = false; 3610 } else if (ICS.isUserDefined()) { 3611 ICS.UserDefined.After.ReferenceBinding = true; 3612 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 3613 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 3614 ICS.UserDefined.After.BindsToRvalue = true; 3615 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3616 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 3617 } 3618 3619 return ICS; 3620} 3621 3622/// TryCopyInitialization - Try to copy-initialize a value of type 3623/// ToType from the expression From. Return the implicit conversion 3624/// sequence required to pass this argument, which may be a bad 3625/// conversion sequence (meaning that the argument cannot be passed to 3626/// a parameter of this type). If @p SuppressUserConversions, then we 3627/// do not permit any user-defined conversion sequences. 3628static ImplicitConversionSequence 3629TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 3630 bool SuppressUserConversions, 3631 bool InOverloadResolution, 3632 bool AllowObjCWritebackConversion) { 3633 if (ToType->isReferenceType()) 3634 return TryReferenceInit(S, From, ToType, 3635 /*FIXME:*/From->getLocStart(), 3636 SuppressUserConversions, 3637 /*AllowExplicit=*/false); 3638 3639 return TryImplicitConversion(S, From, ToType, 3640 SuppressUserConversions, 3641 /*AllowExplicit=*/false, 3642 InOverloadResolution, 3643 /*CStyle=*/false, 3644 AllowObjCWritebackConversion); 3645} 3646 3647static bool TryCopyInitialization(const CanQualType FromQTy, 3648 const CanQualType ToQTy, 3649 Sema &S, 3650 SourceLocation Loc, 3651 ExprValueKind FromVK) { 3652 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 3653 ImplicitConversionSequence ICS = 3654 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 3655 3656 return !ICS.isBad(); 3657} 3658 3659/// TryObjectArgumentInitialization - Try to initialize the object 3660/// parameter of the given member function (@c Method) from the 3661/// expression @p From. 3662static ImplicitConversionSequence 3663TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 3664 Expr::Classification FromClassification, 3665 CXXMethodDecl *Method, 3666 CXXRecordDecl *ActingContext) { 3667 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 3668 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 3669 // const volatile object. 3670 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 3671 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 3672 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 3673 3674 // Set up the conversion sequence as a "bad" conversion, to allow us 3675 // to exit early. 3676 ImplicitConversionSequence ICS; 3677 3678 // We need to have an object of class type. 3679 QualType FromType = OrigFromType; 3680 if (const PointerType *PT = FromType->getAs<PointerType>()) { 3681 FromType = PT->getPointeeType(); 3682 3683 // When we had a pointer, it's implicitly dereferenced, so we 3684 // better have an lvalue. 3685 assert(FromClassification.isLValue()); 3686 } 3687 3688 assert(FromType->isRecordType()); 3689 3690 // C++0x [over.match.funcs]p4: 3691 // For non-static member functions, the type of the implicit object 3692 // parameter is 3693 // 3694 // - "lvalue reference to cv X" for functions declared without a 3695 // ref-qualifier or with the & ref-qualifier 3696 // - "rvalue reference to cv X" for functions declared with the && 3697 // ref-qualifier 3698 // 3699 // where X is the class of which the function is a member and cv is the 3700 // cv-qualification on the member function declaration. 3701 // 3702 // However, when finding an implicit conversion sequence for the argument, we 3703 // are not allowed to create temporaries or perform user-defined conversions 3704 // (C++ [over.match.funcs]p5). We perform a simplified version of 3705 // reference binding here, that allows class rvalues to bind to 3706 // non-constant references. 3707 3708 // First check the qualifiers. 3709 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 3710 if (ImplicitParamType.getCVRQualifiers() 3711 != FromTypeCanon.getLocalCVRQualifiers() && 3712 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 3713 ICS.setBad(BadConversionSequence::bad_qualifiers, 3714 OrigFromType, ImplicitParamType); 3715 return ICS; 3716 } 3717 3718 // Check that we have either the same type or a derived type. It 3719 // affects the conversion rank. 3720 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 3721 ImplicitConversionKind SecondKind; 3722 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 3723 SecondKind = ICK_Identity; 3724 } else if (S.IsDerivedFrom(FromType, ClassType)) 3725 SecondKind = ICK_Derived_To_Base; 3726 else { 3727 ICS.setBad(BadConversionSequence::unrelated_class, 3728 FromType, ImplicitParamType); 3729 return ICS; 3730 } 3731 3732 // Check the ref-qualifier. 3733 switch (Method->getRefQualifier()) { 3734 case RQ_None: 3735 // Do nothing; we don't care about lvalueness or rvalueness. 3736 break; 3737 3738 case RQ_LValue: 3739 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 3740 // non-const lvalue reference cannot bind to an rvalue 3741 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 3742 ImplicitParamType); 3743 return ICS; 3744 } 3745 break; 3746 3747 case RQ_RValue: 3748 if (!FromClassification.isRValue()) { 3749 // rvalue reference cannot bind to an lvalue 3750 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 3751 ImplicitParamType); 3752 return ICS; 3753 } 3754 break; 3755 } 3756 3757 // Success. Mark this as a reference binding. 3758 ICS.setStandard(); 3759 ICS.Standard.setAsIdentityConversion(); 3760 ICS.Standard.Second = SecondKind; 3761 ICS.Standard.setFromType(FromType); 3762 ICS.Standard.setAllToTypes(ImplicitParamType); 3763 ICS.Standard.ReferenceBinding = true; 3764 ICS.Standard.DirectBinding = true; 3765 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 3766 ICS.Standard.BindsToFunctionLvalue = false; 3767 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 3768 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 3769 = (Method->getRefQualifier() == RQ_None); 3770 return ICS; 3771} 3772 3773/// PerformObjectArgumentInitialization - Perform initialization of 3774/// the implicit object parameter for the given Method with the given 3775/// expression. 3776ExprResult 3777Sema::PerformObjectArgumentInitialization(Expr *From, 3778 NestedNameSpecifier *Qualifier, 3779 NamedDecl *FoundDecl, 3780 CXXMethodDecl *Method) { 3781 QualType FromRecordType, DestType; 3782 QualType ImplicitParamRecordType = 3783 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 3784 3785 Expr::Classification FromClassification; 3786 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 3787 FromRecordType = PT->getPointeeType(); 3788 DestType = Method->getThisType(Context); 3789 FromClassification = Expr::Classification::makeSimpleLValue(); 3790 } else { 3791 FromRecordType = From->getType(); 3792 DestType = ImplicitParamRecordType; 3793 FromClassification = From->Classify(Context); 3794 } 3795 3796 // Note that we always use the true parent context when performing 3797 // the actual argument initialization. 3798 ImplicitConversionSequence ICS 3799 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 3800 Method, Method->getParent()); 3801 if (ICS.isBad()) { 3802 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 3803 Qualifiers FromQs = FromRecordType.getQualifiers(); 3804 Qualifiers ToQs = DestType.getQualifiers(); 3805 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 3806 if (CVR) { 3807 Diag(From->getSourceRange().getBegin(), 3808 diag::err_member_function_call_bad_cvr) 3809 << Method->getDeclName() << FromRecordType << (CVR - 1) 3810 << From->getSourceRange(); 3811 Diag(Method->getLocation(), diag::note_previous_decl) 3812 << Method->getDeclName(); 3813 return ExprError(); 3814 } 3815 } 3816 3817 return Diag(From->getSourceRange().getBegin(), 3818 diag::err_implicit_object_parameter_init) 3819 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 3820 } 3821 3822 if (ICS.Standard.Second == ICK_Derived_To_Base) { 3823 ExprResult FromRes = 3824 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 3825 if (FromRes.isInvalid()) 3826 return ExprError(); 3827 From = FromRes.take(); 3828 } 3829 3830 if (!Context.hasSameType(From->getType(), DestType)) 3831 From = ImpCastExprToType(From, DestType, CK_NoOp, 3832 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take(); 3833 return Owned(From); 3834} 3835 3836/// TryContextuallyConvertToBool - Attempt to contextually convert the 3837/// expression From to bool (C++0x [conv]p3). 3838static ImplicitConversionSequence 3839TryContextuallyConvertToBool(Sema &S, Expr *From) { 3840 // FIXME: This is pretty broken. 3841 return TryImplicitConversion(S, From, S.Context.BoolTy, 3842 // FIXME: Are these flags correct? 3843 /*SuppressUserConversions=*/false, 3844 /*AllowExplicit=*/true, 3845 /*InOverloadResolution=*/false, 3846 /*CStyle=*/false, 3847 /*AllowObjCWritebackConversion=*/false); 3848} 3849 3850/// PerformContextuallyConvertToBool - Perform a contextual conversion 3851/// of the expression From to bool (C++0x [conv]p3). 3852ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 3853 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 3854 if (!ICS.isBad()) 3855 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 3856 3857 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 3858 return Diag(From->getSourceRange().getBegin(), 3859 diag::err_typecheck_bool_condition) 3860 << From->getType() << From->getSourceRange(); 3861 return ExprError(); 3862} 3863 3864/// TryContextuallyConvertToObjCId - Attempt to contextually convert the 3865/// expression From to 'id'. 3866static ImplicitConversionSequence 3867TryContextuallyConvertToObjCId(Sema &S, Expr *From) { 3868 QualType Ty = S.Context.getObjCIdType(); 3869 return TryImplicitConversion(S, From, Ty, 3870 // FIXME: Are these flags correct? 3871 /*SuppressUserConversions=*/false, 3872 /*AllowExplicit=*/true, 3873 /*InOverloadResolution=*/false, 3874 /*CStyle=*/false, 3875 /*AllowObjCWritebackConversion=*/false); 3876} 3877 3878/// PerformContextuallyConvertToObjCId - Perform a contextual conversion 3879/// of the expression From to 'id'. 3880ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) { 3881 QualType Ty = Context.getObjCIdType(); 3882 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From); 3883 if (!ICS.isBad()) 3884 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 3885 return ExprError(); 3886} 3887 3888/// \brief Attempt to convert the given expression to an integral or 3889/// enumeration type. 3890/// 3891/// This routine will attempt to convert an expression of class type to an 3892/// integral or enumeration type, if that class type only has a single 3893/// conversion to an integral or enumeration type. 3894/// 3895/// \param Loc The source location of the construct that requires the 3896/// conversion. 3897/// 3898/// \param FromE The expression we're converting from. 3899/// 3900/// \param NotIntDiag The diagnostic to be emitted if the expression does not 3901/// have integral or enumeration type. 3902/// 3903/// \param IncompleteDiag The diagnostic to be emitted if the expression has 3904/// incomplete class type. 3905/// 3906/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 3907/// explicit conversion function (because no implicit conversion functions 3908/// were available). This is a recovery mode. 3909/// 3910/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 3911/// showing which conversion was picked. 3912/// 3913/// \param AmbigDiag The diagnostic to be emitted if there is more than one 3914/// conversion function that could convert to integral or enumeration type. 3915/// 3916/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 3917/// usable conversion function. 3918/// 3919/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 3920/// function, which may be an extension in this case. 3921/// 3922/// \returns The expression, converted to an integral or enumeration type if 3923/// successful. 3924ExprResult 3925Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 3926 const PartialDiagnostic &NotIntDiag, 3927 const PartialDiagnostic &IncompleteDiag, 3928 const PartialDiagnostic &ExplicitConvDiag, 3929 const PartialDiagnostic &ExplicitConvNote, 3930 const PartialDiagnostic &AmbigDiag, 3931 const PartialDiagnostic &AmbigNote, 3932 const PartialDiagnostic &ConvDiag) { 3933 // We can't perform any more checking for type-dependent expressions. 3934 if (From->isTypeDependent()) 3935 return Owned(From); 3936 3937 // If the expression already has integral or enumeration type, we're golden. 3938 QualType T = From->getType(); 3939 if (T->isIntegralOrEnumerationType()) 3940 return Owned(From); 3941 3942 // FIXME: Check for missing '()' if T is a function type? 3943 3944 // If we don't have a class type in C++, there's no way we can get an 3945 // expression of integral or enumeration type. 3946 const RecordType *RecordTy = T->getAs<RecordType>(); 3947 if (!RecordTy || !getLangOptions().CPlusPlus) { 3948 Diag(Loc, NotIntDiag) 3949 << T << From->getSourceRange(); 3950 return Owned(From); 3951 } 3952 3953 // We must have a complete class type. 3954 if (RequireCompleteType(Loc, T, IncompleteDiag)) 3955 return Owned(From); 3956 3957 // Look for a conversion to an integral or enumeration type. 3958 UnresolvedSet<4> ViableConversions; 3959 UnresolvedSet<4> ExplicitConversions; 3960 const UnresolvedSetImpl *Conversions 3961 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 3962 3963 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3964 E = Conversions->end(); 3965 I != E; 3966 ++I) { 3967 if (CXXConversionDecl *Conversion 3968 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) 3969 if (Conversion->getConversionType().getNonReferenceType() 3970 ->isIntegralOrEnumerationType()) { 3971 if (Conversion->isExplicit()) 3972 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 3973 else 3974 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 3975 } 3976 } 3977 3978 switch (ViableConversions.size()) { 3979 case 0: 3980 if (ExplicitConversions.size() == 1) { 3981 DeclAccessPair Found = ExplicitConversions[0]; 3982 CXXConversionDecl *Conversion 3983 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3984 3985 // The user probably meant to invoke the given explicit 3986 // conversion; use it. 3987 QualType ConvTy 3988 = Conversion->getConversionType().getNonReferenceType(); 3989 std::string TypeStr; 3990 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy); 3991 3992 Diag(Loc, ExplicitConvDiag) 3993 << T << ConvTy 3994 << FixItHint::CreateInsertion(From->getLocStart(), 3995 "static_cast<" + TypeStr + ">(") 3996 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 3997 ")"); 3998 Diag(Conversion->getLocation(), ExplicitConvNote) 3999 << ConvTy->isEnumeralType() << ConvTy; 4000 4001 // If we aren't in a SFINAE context, build a call to the 4002 // explicit conversion function. 4003 if (isSFINAEContext()) 4004 return ExprError(); 4005 4006 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 4007 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion); 4008 if (Result.isInvalid()) 4009 return ExprError(); 4010 4011 From = Result.get(); 4012 } 4013 4014 // We'll complain below about a non-integral condition type. 4015 break; 4016 4017 case 1: { 4018 // Apply this conversion. 4019 DeclAccessPair Found = ViableConversions[0]; 4020 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 4021 4022 CXXConversionDecl *Conversion 4023 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 4024 QualType ConvTy 4025 = Conversion->getConversionType().getNonReferenceType(); 4026 if (ConvDiag.getDiagID()) { 4027 if (isSFINAEContext()) 4028 return ExprError(); 4029 4030 Diag(Loc, ConvDiag) 4031 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange(); 4032 } 4033 4034 ExprResult Result = BuildCXXMemberCallExpr(From, Found, 4035 cast<CXXConversionDecl>(Found->getUnderlyingDecl())); 4036 if (Result.isInvalid()) 4037 return ExprError(); 4038 4039 From = Result.get(); 4040 break; 4041 } 4042 4043 default: 4044 Diag(Loc, AmbigDiag) 4045 << T << From->getSourceRange(); 4046 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 4047 CXXConversionDecl *Conv 4048 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 4049 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 4050 Diag(Conv->getLocation(), AmbigNote) 4051 << ConvTy->isEnumeralType() << ConvTy; 4052 } 4053 return Owned(From); 4054 } 4055 4056 if (!From->getType()->isIntegralOrEnumerationType()) 4057 Diag(Loc, NotIntDiag) 4058 << From->getType() << From->getSourceRange(); 4059 4060 return Owned(From); 4061} 4062 4063/// AddOverloadCandidate - Adds the given function to the set of 4064/// candidate functions, using the given function call arguments. If 4065/// @p SuppressUserConversions, then don't allow user-defined 4066/// conversions via constructors or conversion operators. 4067/// 4068/// \para PartialOverloading true if we are performing "partial" overloading 4069/// based on an incomplete set of function arguments. This feature is used by 4070/// code completion. 4071void 4072Sema::AddOverloadCandidate(FunctionDecl *Function, 4073 DeclAccessPair FoundDecl, 4074 Expr **Args, unsigned NumArgs, 4075 OverloadCandidateSet& CandidateSet, 4076 bool SuppressUserConversions, 4077 bool PartialOverloading) { 4078 const FunctionProtoType* Proto 4079 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 4080 assert(Proto && "Functions without a prototype cannot be overloaded"); 4081 assert(!Function->getDescribedFunctionTemplate() && 4082 "Use AddTemplateOverloadCandidate for function templates"); 4083 4084 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 4085 if (!isa<CXXConstructorDecl>(Method)) { 4086 // If we get here, it's because we're calling a member function 4087 // that is named without a member access expression (e.g., 4088 // "this->f") that was either written explicitly or created 4089 // implicitly. This can happen with a qualified call to a member 4090 // function, e.g., X::f(). We use an empty type for the implied 4091 // object argument (C++ [over.call.func]p3), and the acting context 4092 // is irrelevant. 4093 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 4094 QualType(), Expr::Classification::makeSimpleLValue(), 4095 Args, NumArgs, CandidateSet, 4096 SuppressUserConversions); 4097 return; 4098 } 4099 // We treat a constructor like a non-member function, since its object 4100 // argument doesn't participate in overload resolution. 4101 } 4102 4103 if (!CandidateSet.isNewCandidate(Function)) 4104 return; 4105 4106 // Overload resolution is always an unevaluated context. 4107 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4108 4109 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 4110 // C++ [class.copy]p3: 4111 // A member function template is never instantiated to perform the copy 4112 // of a class object to an object of its class type. 4113 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 4114 if (NumArgs == 1 && 4115 Constructor->isSpecializationCopyingObject() && 4116 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 4117 IsDerivedFrom(Args[0]->getType(), ClassType))) 4118 return; 4119 } 4120 4121 // Add this candidate 4122 CandidateSet.push_back(OverloadCandidate()); 4123 OverloadCandidate& Candidate = CandidateSet.back(); 4124 Candidate.FoundDecl = FoundDecl; 4125 Candidate.Function = Function; 4126 Candidate.Viable = true; 4127 Candidate.IsSurrogate = false; 4128 Candidate.IgnoreObjectArgument = false; 4129 Candidate.ExplicitCallArguments = NumArgs; 4130 4131 unsigned NumArgsInProto = Proto->getNumArgs(); 4132 4133 // (C++ 13.3.2p2): A candidate function having fewer than m 4134 // parameters is viable only if it has an ellipsis in its parameter 4135 // list (8.3.5). 4136 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 4137 !Proto->isVariadic()) { 4138 Candidate.Viable = false; 4139 Candidate.FailureKind = ovl_fail_too_many_arguments; 4140 return; 4141 } 4142 4143 // (C++ 13.3.2p2): A candidate function having more than m parameters 4144 // is viable only if the (m+1)st parameter has a default argument 4145 // (8.3.6). For the purposes of overload resolution, the 4146 // parameter list is truncated on the right, so that there are 4147 // exactly m parameters. 4148 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 4149 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 4150 // Not enough arguments. 4151 Candidate.Viable = false; 4152 Candidate.FailureKind = ovl_fail_too_few_arguments; 4153 return; 4154 } 4155 4156 // Determine the implicit conversion sequences for each of the 4157 // arguments. 4158 Candidate.Conversions.resize(NumArgs); 4159 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4160 if (ArgIdx < NumArgsInProto) { 4161 // (C++ 13.3.2p3): for F to be a viable function, there shall 4162 // exist for each argument an implicit conversion sequence 4163 // (13.3.3.1) that converts that argument to the corresponding 4164 // parameter of F. 4165 QualType ParamType = Proto->getArgType(ArgIdx); 4166 Candidate.Conversions[ArgIdx] 4167 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4168 SuppressUserConversions, 4169 /*InOverloadResolution=*/true, 4170 /*AllowObjCWritebackConversion=*/ 4171 getLangOptions().ObjCAutoRefCount); 4172 if (Candidate.Conversions[ArgIdx].isBad()) { 4173 Candidate.Viable = false; 4174 Candidate.FailureKind = ovl_fail_bad_conversion; 4175 break; 4176 } 4177 } else { 4178 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4179 // argument for which there is no corresponding parameter is 4180 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4181 Candidate.Conversions[ArgIdx].setEllipsis(); 4182 } 4183 } 4184} 4185 4186/// \brief Add all of the function declarations in the given function set to 4187/// the overload canddiate set. 4188void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 4189 Expr **Args, unsigned NumArgs, 4190 OverloadCandidateSet& CandidateSet, 4191 bool SuppressUserConversions) { 4192 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 4193 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 4194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4195 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 4196 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 4197 cast<CXXMethodDecl>(FD)->getParent(), 4198 Args[0]->getType(), Args[0]->Classify(Context), 4199 Args + 1, NumArgs - 1, 4200 CandidateSet, SuppressUserConversions); 4201 else 4202 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet, 4203 SuppressUserConversions); 4204 } else { 4205 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 4206 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 4207 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 4208 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 4209 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 4210 /*FIXME: explicit args */ 0, 4211 Args[0]->getType(), 4212 Args[0]->Classify(Context), 4213 Args + 1, NumArgs - 1, 4214 CandidateSet, 4215 SuppressUserConversions); 4216 else 4217 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 4218 /*FIXME: explicit args */ 0, 4219 Args, NumArgs, CandidateSet, 4220 SuppressUserConversions); 4221 } 4222 } 4223} 4224 4225/// AddMethodCandidate - Adds a named decl (which is some kind of 4226/// method) as a method candidate to the given overload set. 4227void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 4228 QualType ObjectType, 4229 Expr::Classification ObjectClassification, 4230 Expr **Args, unsigned NumArgs, 4231 OverloadCandidateSet& CandidateSet, 4232 bool SuppressUserConversions) { 4233 NamedDecl *Decl = FoundDecl.getDecl(); 4234 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 4235 4236 if (isa<UsingShadowDecl>(Decl)) 4237 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 4238 4239 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 4240 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 4241 "Expected a member function template"); 4242 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 4243 /*ExplicitArgs*/ 0, 4244 ObjectType, ObjectClassification, Args, NumArgs, 4245 CandidateSet, 4246 SuppressUserConversions); 4247 } else { 4248 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 4249 ObjectType, ObjectClassification, Args, NumArgs, 4250 CandidateSet, SuppressUserConversions); 4251 } 4252} 4253 4254/// AddMethodCandidate - Adds the given C++ member function to the set 4255/// of candidate functions, using the given function call arguments 4256/// and the object argument (@c Object). For example, in a call 4257/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 4258/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 4259/// allow user-defined conversions via constructors or conversion 4260/// operators. 4261void 4262Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 4263 CXXRecordDecl *ActingContext, QualType ObjectType, 4264 Expr::Classification ObjectClassification, 4265 Expr **Args, unsigned NumArgs, 4266 OverloadCandidateSet& CandidateSet, 4267 bool SuppressUserConversions) { 4268 const FunctionProtoType* Proto 4269 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 4270 assert(Proto && "Methods without a prototype cannot be overloaded"); 4271 assert(!isa<CXXConstructorDecl>(Method) && 4272 "Use AddOverloadCandidate for constructors"); 4273 4274 if (!CandidateSet.isNewCandidate(Method)) 4275 return; 4276 4277 // Overload resolution is always an unevaluated context. 4278 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4279 4280 // Add this candidate 4281 CandidateSet.push_back(OverloadCandidate()); 4282 OverloadCandidate& Candidate = CandidateSet.back(); 4283 Candidate.FoundDecl = FoundDecl; 4284 Candidate.Function = Method; 4285 Candidate.IsSurrogate = false; 4286 Candidate.IgnoreObjectArgument = false; 4287 Candidate.ExplicitCallArguments = NumArgs; 4288 4289 unsigned NumArgsInProto = Proto->getNumArgs(); 4290 4291 // (C++ 13.3.2p2): A candidate function having fewer than m 4292 // parameters is viable only if it has an ellipsis in its parameter 4293 // list (8.3.5). 4294 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 4295 Candidate.Viable = false; 4296 Candidate.FailureKind = ovl_fail_too_many_arguments; 4297 return; 4298 } 4299 4300 // (C++ 13.3.2p2): A candidate function having more than m parameters 4301 // is viable only if the (m+1)st parameter has a default argument 4302 // (8.3.6). For the purposes of overload resolution, the 4303 // parameter list is truncated on the right, so that there are 4304 // exactly m parameters. 4305 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 4306 if (NumArgs < MinRequiredArgs) { 4307 // Not enough arguments. 4308 Candidate.Viable = false; 4309 Candidate.FailureKind = ovl_fail_too_few_arguments; 4310 return; 4311 } 4312 4313 Candidate.Viable = true; 4314 Candidate.Conversions.resize(NumArgs + 1); 4315 4316 if (Method->isStatic() || ObjectType.isNull()) 4317 // The implicit object argument is ignored. 4318 Candidate.IgnoreObjectArgument = true; 4319 else { 4320 // Determine the implicit conversion sequence for the object 4321 // parameter. 4322 Candidate.Conversions[0] 4323 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 4324 Method, ActingContext); 4325 if (Candidate.Conversions[0].isBad()) { 4326 Candidate.Viable = false; 4327 Candidate.FailureKind = ovl_fail_bad_conversion; 4328 return; 4329 } 4330 } 4331 4332 // Determine the implicit conversion sequences for each of the 4333 // arguments. 4334 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4335 if (ArgIdx < NumArgsInProto) { 4336 // (C++ 13.3.2p3): for F to be a viable function, there shall 4337 // exist for each argument an implicit conversion sequence 4338 // (13.3.3.1) that converts that argument to the corresponding 4339 // parameter of F. 4340 QualType ParamType = Proto->getArgType(ArgIdx); 4341 Candidate.Conversions[ArgIdx + 1] 4342 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4343 SuppressUserConversions, 4344 /*InOverloadResolution=*/true, 4345 /*AllowObjCWritebackConversion=*/ 4346 getLangOptions().ObjCAutoRefCount); 4347 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 4348 Candidate.Viable = false; 4349 Candidate.FailureKind = ovl_fail_bad_conversion; 4350 break; 4351 } 4352 } else { 4353 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4354 // argument for which there is no corresponding parameter is 4355 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4356 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 4357 } 4358 } 4359} 4360 4361/// \brief Add a C++ member function template as a candidate to the candidate 4362/// set, using template argument deduction to produce an appropriate member 4363/// function template specialization. 4364void 4365Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 4366 DeclAccessPair FoundDecl, 4367 CXXRecordDecl *ActingContext, 4368 TemplateArgumentListInfo *ExplicitTemplateArgs, 4369 QualType ObjectType, 4370 Expr::Classification ObjectClassification, 4371 Expr **Args, unsigned NumArgs, 4372 OverloadCandidateSet& CandidateSet, 4373 bool SuppressUserConversions) { 4374 if (!CandidateSet.isNewCandidate(MethodTmpl)) 4375 return; 4376 4377 // C++ [over.match.funcs]p7: 4378 // In each case where a candidate is a function template, candidate 4379 // function template specializations are generated using template argument 4380 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 4381 // candidate functions in the usual way.113) A given name can refer to one 4382 // or more function templates and also to a set of overloaded non-template 4383 // functions. In such a case, the candidate functions generated from each 4384 // function template are combined with the set of non-template candidate 4385 // functions. 4386 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4387 FunctionDecl *Specialization = 0; 4388 if (TemplateDeductionResult Result 4389 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 4390 Args, NumArgs, Specialization, Info)) { 4391 CandidateSet.push_back(OverloadCandidate()); 4392 OverloadCandidate &Candidate = CandidateSet.back(); 4393 Candidate.FoundDecl = FoundDecl; 4394 Candidate.Function = MethodTmpl->getTemplatedDecl(); 4395 Candidate.Viable = false; 4396 Candidate.FailureKind = ovl_fail_bad_deduction; 4397 Candidate.IsSurrogate = false; 4398 Candidate.IgnoreObjectArgument = false; 4399 Candidate.ExplicitCallArguments = NumArgs; 4400 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4401 Info); 4402 return; 4403 } 4404 4405 // Add the function template specialization produced by template argument 4406 // deduction as a candidate. 4407 assert(Specialization && "Missing member function template specialization?"); 4408 assert(isa<CXXMethodDecl>(Specialization) && 4409 "Specialization is not a member function?"); 4410 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 4411 ActingContext, ObjectType, ObjectClassification, 4412 Args, NumArgs, CandidateSet, SuppressUserConversions); 4413} 4414 4415/// \brief Add a C++ function template specialization as a candidate 4416/// in the candidate set, using template argument deduction to produce 4417/// an appropriate function template specialization. 4418void 4419Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 4420 DeclAccessPair FoundDecl, 4421 TemplateArgumentListInfo *ExplicitTemplateArgs, 4422 Expr **Args, unsigned NumArgs, 4423 OverloadCandidateSet& CandidateSet, 4424 bool SuppressUserConversions) { 4425 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 4426 return; 4427 4428 // C++ [over.match.funcs]p7: 4429 // In each case where a candidate is a function template, candidate 4430 // function template specializations are generated using template argument 4431 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 4432 // candidate functions in the usual way.113) A given name can refer to one 4433 // or more function templates and also to a set of overloaded non-template 4434 // functions. In such a case, the candidate functions generated from each 4435 // function template are combined with the set of non-template candidate 4436 // functions. 4437 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4438 FunctionDecl *Specialization = 0; 4439 if (TemplateDeductionResult Result 4440 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 4441 Args, NumArgs, Specialization, Info)) { 4442 CandidateSet.push_back(OverloadCandidate()); 4443 OverloadCandidate &Candidate = CandidateSet.back(); 4444 Candidate.FoundDecl = FoundDecl; 4445 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 4446 Candidate.Viable = false; 4447 Candidate.FailureKind = ovl_fail_bad_deduction; 4448 Candidate.IsSurrogate = false; 4449 Candidate.IgnoreObjectArgument = false; 4450 Candidate.ExplicitCallArguments = NumArgs; 4451 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4452 Info); 4453 return; 4454 } 4455 4456 // Add the function template specialization produced by template argument 4457 // deduction as a candidate. 4458 assert(Specialization && "Missing function template specialization?"); 4459 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet, 4460 SuppressUserConversions); 4461} 4462 4463/// AddConversionCandidate - Add a C++ conversion function as a 4464/// candidate in the candidate set (C++ [over.match.conv], 4465/// C++ [over.match.copy]). From is the expression we're converting from, 4466/// and ToType is the type that we're eventually trying to convert to 4467/// (which may or may not be the same type as the type that the 4468/// conversion function produces). 4469void 4470Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 4471 DeclAccessPair FoundDecl, 4472 CXXRecordDecl *ActingContext, 4473 Expr *From, QualType ToType, 4474 OverloadCandidateSet& CandidateSet) { 4475 assert(!Conversion->getDescribedFunctionTemplate() && 4476 "Conversion function templates use AddTemplateConversionCandidate"); 4477 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 4478 if (!CandidateSet.isNewCandidate(Conversion)) 4479 return; 4480 4481 // Overload resolution is always an unevaluated context. 4482 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4483 4484 // Add this candidate 4485 CandidateSet.push_back(OverloadCandidate()); 4486 OverloadCandidate& Candidate = CandidateSet.back(); 4487 Candidate.FoundDecl = FoundDecl; 4488 Candidate.Function = Conversion; 4489 Candidate.IsSurrogate = false; 4490 Candidate.IgnoreObjectArgument = false; 4491 Candidate.FinalConversion.setAsIdentityConversion(); 4492 Candidate.FinalConversion.setFromType(ConvType); 4493 Candidate.FinalConversion.setAllToTypes(ToType); 4494 Candidate.Viable = true; 4495 Candidate.Conversions.resize(1); 4496 Candidate.ExplicitCallArguments = 1; 4497 4498 // C++ [over.match.funcs]p4: 4499 // For conversion functions, the function is considered to be a member of 4500 // the class of the implicit implied object argument for the purpose of 4501 // defining the type of the implicit object parameter. 4502 // 4503 // Determine the implicit conversion sequence for the implicit 4504 // object parameter. 4505 QualType ImplicitParamType = From->getType(); 4506 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 4507 ImplicitParamType = FromPtrType->getPointeeType(); 4508 CXXRecordDecl *ConversionContext 4509 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 4510 4511 Candidate.Conversions[0] 4512 = TryObjectArgumentInitialization(*this, From->getType(), 4513 From->Classify(Context), 4514 Conversion, ConversionContext); 4515 4516 if (Candidate.Conversions[0].isBad()) { 4517 Candidate.Viable = false; 4518 Candidate.FailureKind = ovl_fail_bad_conversion; 4519 return; 4520 } 4521 4522 // We won't go through a user-define type conversion function to convert a 4523 // derived to base as such conversions are given Conversion Rank. They only 4524 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 4525 QualType FromCanon 4526 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 4527 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 4528 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 4529 Candidate.Viable = false; 4530 Candidate.FailureKind = ovl_fail_trivial_conversion; 4531 return; 4532 } 4533 4534 // To determine what the conversion from the result of calling the 4535 // conversion function to the type we're eventually trying to 4536 // convert to (ToType), we need to synthesize a call to the 4537 // conversion function and attempt copy initialization from it. This 4538 // makes sure that we get the right semantics with respect to 4539 // lvalues/rvalues and the type. Fortunately, we can allocate this 4540 // call on the stack and we don't need its arguments to be 4541 // well-formed. 4542 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 4543 VK_LValue, From->getLocStart()); 4544 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 4545 Context.getPointerType(Conversion->getType()), 4546 CK_FunctionToPointerDecay, 4547 &ConversionRef, VK_RValue); 4548 4549 QualType ConversionType = Conversion->getConversionType(); 4550 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 4551 Candidate.Viable = false; 4552 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4553 return; 4554 } 4555 4556 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 4557 4558 // Note that it is safe to allocate CallExpr on the stack here because 4559 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 4560 // allocator). 4561 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 4562 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK, 4563 From->getLocStart()); 4564 ImplicitConversionSequence ICS = 4565 TryCopyInitialization(*this, &Call, ToType, 4566 /*SuppressUserConversions=*/true, 4567 /*InOverloadResolution=*/false, 4568 /*AllowObjCWritebackConversion=*/false); 4569 4570 switch (ICS.getKind()) { 4571 case ImplicitConversionSequence::StandardConversion: 4572 Candidate.FinalConversion = ICS.Standard; 4573 4574 // C++ [over.ics.user]p3: 4575 // If the user-defined conversion is specified by a specialization of a 4576 // conversion function template, the second standard conversion sequence 4577 // shall have exact match rank. 4578 if (Conversion->getPrimaryTemplate() && 4579 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 4580 Candidate.Viable = false; 4581 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 4582 } 4583 4584 // C++0x [dcl.init.ref]p5: 4585 // In the second case, if the reference is an rvalue reference and 4586 // the second standard conversion sequence of the user-defined 4587 // conversion sequence includes an lvalue-to-rvalue conversion, the 4588 // program is ill-formed. 4589 if (ToType->isRValueReferenceType() && 4590 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 4591 Candidate.Viable = false; 4592 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4593 } 4594 break; 4595 4596 case ImplicitConversionSequence::BadConversion: 4597 Candidate.Viable = false; 4598 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4599 break; 4600 4601 default: 4602 assert(false && 4603 "Can only end up with a standard conversion sequence or failure"); 4604 } 4605} 4606 4607/// \brief Adds a conversion function template specialization 4608/// candidate to the overload set, using template argument deduction 4609/// to deduce the template arguments of the conversion function 4610/// template from the type that we are converting to (C++ 4611/// [temp.deduct.conv]). 4612void 4613Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 4614 DeclAccessPair FoundDecl, 4615 CXXRecordDecl *ActingDC, 4616 Expr *From, QualType ToType, 4617 OverloadCandidateSet &CandidateSet) { 4618 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 4619 "Only conversion function templates permitted here"); 4620 4621 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 4622 return; 4623 4624 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4625 CXXConversionDecl *Specialization = 0; 4626 if (TemplateDeductionResult Result 4627 = DeduceTemplateArguments(FunctionTemplate, ToType, 4628 Specialization, Info)) { 4629 CandidateSet.push_back(OverloadCandidate()); 4630 OverloadCandidate &Candidate = CandidateSet.back(); 4631 Candidate.FoundDecl = FoundDecl; 4632 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 4633 Candidate.Viable = false; 4634 Candidate.FailureKind = ovl_fail_bad_deduction; 4635 Candidate.IsSurrogate = false; 4636 Candidate.IgnoreObjectArgument = false; 4637 Candidate.ExplicitCallArguments = 1; 4638 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4639 Info); 4640 return; 4641 } 4642 4643 // Add the conversion function template specialization produced by 4644 // template argument deduction as a candidate. 4645 assert(Specialization && "Missing function template specialization?"); 4646 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 4647 CandidateSet); 4648} 4649 4650/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 4651/// converts the given @c Object to a function pointer via the 4652/// conversion function @c Conversion, and then attempts to call it 4653/// with the given arguments (C++ [over.call.object]p2-4). Proto is 4654/// the type of function that we'll eventually be calling. 4655void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 4656 DeclAccessPair FoundDecl, 4657 CXXRecordDecl *ActingContext, 4658 const FunctionProtoType *Proto, 4659 Expr *Object, 4660 Expr **Args, unsigned NumArgs, 4661 OverloadCandidateSet& CandidateSet) { 4662 if (!CandidateSet.isNewCandidate(Conversion)) 4663 return; 4664 4665 // Overload resolution is always an unevaluated context. 4666 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4667 4668 CandidateSet.push_back(OverloadCandidate()); 4669 OverloadCandidate& Candidate = CandidateSet.back(); 4670 Candidate.FoundDecl = FoundDecl; 4671 Candidate.Function = 0; 4672 Candidate.Surrogate = Conversion; 4673 Candidate.Viable = true; 4674 Candidate.IsSurrogate = true; 4675 Candidate.IgnoreObjectArgument = false; 4676 Candidate.Conversions.resize(NumArgs + 1); 4677 Candidate.ExplicitCallArguments = NumArgs; 4678 4679 // Determine the implicit conversion sequence for the implicit 4680 // object parameter. 4681 ImplicitConversionSequence ObjectInit 4682 = TryObjectArgumentInitialization(*this, Object->getType(), 4683 Object->Classify(Context), 4684 Conversion, ActingContext); 4685 if (ObjectInit.isBad()) { 4686 Candidate.Viable = false; 4687 Candidate.FailureKind = ovl_fail_bad_conversion; 4688 Candidate.Conversions[0] = ObjectInit; 4689 return; 4690 } 4691 4692 // The first conversion is actually a user-defined conversion whose 4693 // first conversion is ObjectInit's standard conversion (which is 4694 // effectively a reference binding). Record it as such. 4695 Candidate.Conversions[0].setUserDefined(); 4696 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 4697 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 4698 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 4699 Candidate.Conversions[0].UserDefined.FoundConversionFunction 4700 = FoundDecl.getDecl(); 4701 Candidate.Conversions[0].UserDefined.After 4702 = Candidate.Conversions[0].UserDefined.Before; 4703 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 4704 4705 // Find the 4706 unsigned NumArgsInProto = Proto->getNumArgs(); 4707 4708 // (C++ 13.3.2p2): A candidate function having fewer than m 4709 // parameters is viable only if it has an ellipsis in its parameter 4710 // list (8.3.5). 4711 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 4712 Candidate.Viable = false; 4713 Candidate.FailureKind = ovl_fail_too_many_arguments; 4714 return; 4715 } 4716 4717 // Function types don't have any default arguments, so just check if 4718 // we have enough arguments. 4719 if (NumArgs < NumArgsInProto) { 4720 // Not enough arguments. 4721 Candidate.Viable = false; 4722 Candidate.FailureKind = ovl_fail_too_few_arguments; 4723 return; 4724 } 4725 4726 // Determine the implicit conversion sequences for each of the 4727 // arguments. 4728 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4729 if (ArgIdx < NumArgsInProto) { 4730 // (C++ 13.3.2p3): for F to be a viable function, there shall 4731 // exist for each argument an implicit conversion sequence 4732 // (13.3.3.1) that converts that argument to the corresponding 4733 // parameter of F. 4734 QualType ParamType = Proto->getArgType(ArgIdx); 4735 Candidate.Conversions[ArgIdx + 1] 4736 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4737 /*SuppressUserConversions=*/false, 4738 /*InOverloadResolution=*/false, 4739 /*AllowObjCWritebackConversion=*/ 4740 getLangOptions().ObjCAutoRefCount); 4741 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 4742 Candidate.Viable = false; 4743 Candidate.FailureKind = ovl_fail_bad_conversion; 4744 break; 4745 } 4746 } else { 4747 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4748 // argument for which there is no corresponding parameter is 4749 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4750 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 4751 } 4752 } 4753} 4754 4755/// \brief Add overload candidates for overloaded operators that are 4756/// member functions. 4757/// 4758/// Add the overloaded operator candidates that are member functions 4759/// for the operator Op that was used in an operator expression such 4760/// as "x Op y". , Args/NumArgs provides the operator arguments, and 4761/// CandidateSet will store the added overload candidates. (C++ 4762/// [over.match.oper]). 4763void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 4764 SourceLocation OpLoc, 4765 Expr **Args, unsigned NumArgs, 4766 OverloadCandidateSet& CandidateSet, 4767 SourceRange OpRange) { 4768 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 4769 4770 // C++ [over.match.oper]p3: 4771 // For a unary operator @ with an operand of a type whose 4772 // cv-unqualified version is T1, and for a binary operator @ with 4773 // a left operand of a type whose cv-unqualified version is T1 and 4774 // a right operand of a type whose cv-unqualified version is T2, 4775 // three sets of candidate functions, designated member 4776 // candidates, non-member candidates and built-in candidates, are 4777 // constructed as follows: 4778 QualType T1 = Args[0]->getType(); 4779 4780 // -- If T1 is a class type, the set of member candidates is the 4781 // result of the qualified lookup of T1::operator@ 4782 // (13.3.1.1.1); otherwise, the set of member candidates is 4783 // empty. 4784 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 4785 // Complete the type if it can be completed. Otherwise, we're done. 4786 if (RequireCompleteType(OpLoc, T1, PDiag())) 4787 return; 4788 4789 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 4790 LookupQualifiedName(Operators, T1Rec->getDecl()); 4791 Operators.suppressDiagnostics(); 4792 4793 for (LookupResult::iterator Oper = Operators.begin(), 4794 OperEnd = Operators.end(); 4795 Oper != OperEnd; 4796 ++Oper) 4797 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 4798 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 4799 CandidateSet, 4800 /* SuppressUserConversions = */ false); 4801 } 4802} 4803 4804/// AddBuiltinCandidate - Add a candidate for a built-in 4805/// operator. ResultTy and ParamTys are the result and parameter types 4806/// of the built-in candidate, respectively. Args and NumArgs are the 4807/// arguments being passed to the candidate. IsAssignmentOperator 4808/// should be true when this built-in candidate is an assignment 4809/// operator. NumContextualBoolArguments is the number of arguments 4810/// (at the beginning of the argument list) that will be contextually 4811/// converted to bool. 4812void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 4813 Expr **Args, unsigned NumArgs, 4814 OverloadCandidateSet& CandidateSet, 4815 bool IsAssignmentOperator, 4816 unsigned NumContextualBoolArguments) { 4817 // Overload resolution is always an unevaluated context. 4818 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4819 4820 // Add this candidate 4821 CandidateSet.push_back(OverloadCandidate()); 4822 OverloadCandidate& Candidate = CandidateSet.back(); 4823 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 4824 Candidate.Function = 0; 4825 Candidate.IsSurrogate = false; 4826 Candidate.IgnoreObjectArgument = false; 4827 Candidate.BuiltinTypes.ResultTy = ResultTy; 4828 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4829 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 4830 4831 // Determine the implicit conversion sequences for each of the 4832 // arguments. 4833 Candidate.Viable = true; 4834 Candidate.Conversions.resize(NumArgs); 4835 Candidate.ExplicitCallArguments = NumArgs; 4836 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4837 // C++ [over.match.oper]p4: 4838 // For the built-in assignment operators, conversions of the 4839 // left operand are restricted as follows: 4840 // -- no temporaries are introduced to hold the left operand, and 4841 // -- no user-defined conversions are applied to the left 4842 // operand to achieve a type match with the left-most 4843 // parameter of a built-in candidate. 4844 // 4845 // We block these conversions by turning off user-defined 4846 // conversions, since that is the only way that initialization of 4847 // a reference to a non-class type can occur from something that 4848 // is not of the same type. 4849 if (ArgIdx < NumContextualBoolArguments) { 4850 assert(ParamTys[ArgIdx] == Context.BoolTy && 4851 "Contextual conversion to bool requires bool type"); 4852 Candidate.Conversions[ArgIdx] 4853 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 4854 } else { 4855 Candidate.Conversions[ArgIdx] 4856 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 4857 ArgIdx == 0 && IsAssignmentOperator, 4858 /*InOverloadResolution=*/false, 4859 /*AllowObjCWritebackConversion=*/ 4860 getLangOptions().ObjCAutoRefCount); 4861 } 4862 if (Candidate.Conversions[ArgIdx].isBad()) { 4863 Candidate.Viable = false; 4864 Candidate.FailureKind = ovl_fail_bad_conversion; 4865 break; 4866 } 4867 } 4868} 4869 4870/// BuiltinCandidateTypeSet - A set of types that will be used for the 4871/// candidate operator functions for built-in operators (C++ 4872/// [over.built]). The types are separated into pointer types and 4873/// enumeration types. 4874class BuiltinCandidateTypeSet { 4875 /// TypeSet - A set of types. 4876 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 4877 4878 /// PointerTypes - The set of pointer types that will be used in the 4879 /// built-in candidates. 4880 TypeSet PointerTypes; 4881 4882 /// MemberPointerTypes - The set of member pointer types that will be 4883 /// used in the built-in candidates. 4884 TypeSet MemberPointerTypes; 4885 4886 /// EnumerationTypes - The set of enumeration types that will be 4887 /// used in the built-in candidates. 4888 TypeSet EnumerationTypes; 4889 4890 /// \brief The set of vector types that will be used in the built-in 4891 /// candidates. 4892 TypeSet VectorTypes; 4893 4894 /// \brief A flag indicating non-record types are viable candidates 4895 bool HasNonRecordTypes; 4896 4897 /// \brief A flag indicating whether either arithmetic or enumeration types 4898 /// were present in the candidate set. 4899 bool HasArithmeticOrEnumeralTypes; 4900 4901 /// \brief A flag indicating whether the nullptr type was present in the 4902 /// candidate set. 4903 bool HasNullPtrType; 4904 4905 /// Sema - The semantic analysis instance where we are building the 4906 /// candidate type set. 4907 Sema &SemaRef; 4908 4909 /// Context - The AST context in which we will build the type sets. 4910 ASTContext &Context; 4911 4912 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4913 const Qualifiers &VisibleQuals); 4914 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 4915 4916public: 4917 /// iterator - Iterates through the types that are part of the set. 4918 typedef TypeSet::iterator iterator; 4919 4920 BuiltinCandidateTypeSet(Sema &SemaRef) 4921 : HasNonRecordTypes(false), 4922 HasArithmeticOrEnumeralTypes(false), 4923 HasNullPtrType(false), 4924 SemaRef(SemaRef), 4925 Context(SemaRef.Context) { } 4926 4927 void AddTypesConvertedFrom(QualType Ty, 4928 SourceLocation Loc, 4929 bool AllowUserConversions, 4930 bool AllowExplicitConversions, 4931 const Qualifiers &VisibleTypeConversionsQuals); 4932 4933 /// pointer_begin - First pointer type found; 4934 iterator pointer_begin() { return PointerTypes.begin(); } 4935 4936 /// pointer_end - Past the last pointer type found; 4937 iterator pointer_end() { return PointerTypes.end(); } 4938 4939 /// member_pointer_begin - First member pointer type found; 4940 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 4941 4942 /// member_pointer_end - Past the last member pointer type found; 4943 iterator member_pointer_end() { return MemberPointerTypes.end(); } 4944 4945 /// enumeration_begin - First enumeration type found; 4946 iterator enumeration_begin() { return EnumerationTypes.begin(); } 4947 4948 /// enumeration_end - Past the last enumeration type found; 4949 iterator enumeration_end() { return EnumerationTypes.end(); } 4950 4951 iterator vector_begin() { return VectorTypes.begin(); } 4952 iterator vector_end() { return VectorTypes.end(); } 4953 4954 bool hasNonRecordTypes() { return HasNonRecordTypes; } 4955 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 4956 bool hasNullPtrType() const { return HasNullPtrType; } 4957}; 4958 4959/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 4960/// the set of pointer types along with any more-qualified variants of 4961/// that type. For example, if @p Ty is "int const *", this routine 4962/// will add "int const *", "int const volatile *", "int const 4963/// restrict *", and "int const volatile restrict *" to the set of 4964/// pointer types. Returns true if the add of @p Ty itself succeeded, 4965/// false otherwise. 4966/// 4967/// FIXME: what to do about extended qualifiers? 4968bool 4969BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4970 const Qualifiers &VisibleQuals) { 4971 4972 // Insert this type. 4973 if (!PointerTypes.insert(Ty)) 4974 return false; 4975 4976 QualType PointeeTy; 4977 const PointerType *PointerTy = Ty->getAs<PointerType>(); 4978 bool buildObjCPtr = false; 4979 if (!PointerTy) { 4980 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) { 4981 PointeeTy = PTy->getPointeeType(); 4982 buildObjCPtr = true; 4983 } 4984 else 4985 assert(false && "type was not a pointer type!"); 4986 } 4987 else 4988 PointeeTy = PointerTy->getPointeeType(); 4989 4990 // Don't add qualified variants of arrays. For one, they're not allowed 4991 // (the qualifier would sink to the element type), and for another, the 4992 // only overload situation where it matters is subscript or pointer +- int, 4993 // and those shouldn't have qualifier variants anyway. 4994 if (PointeeTy->isArrayType()) 4995 return true; 4996 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4997 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 4998 BaseCVR = Array->getElementType().getCVRQualifiers(); 4999 bool hasVolatile = VisibleQuals.hasVolatile(); 5000 bool hasRestrict = VisibleQuals.hasRestrict(); 5001 5002 // Iterate through all strict supersets of BaseCVR. 5003 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 5004 if ((CVR | BaseCVR) != CVR) continue; 5005 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 5006 // in the types. 5007 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 5008 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 5009 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 5010 if (!buildObjCPtr) 5011 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 5012 else 5013 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy)); 5014 } 5015 5016 return true; 5017} 5018 5019/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 5020/// to the set of pointer types along with any more-qualified variants of 5021/// that type. For example, if @p Ty is "int const *", this routine 5022/// will add "int const *", "int const volatile *", "int const 5023/// restrict *", and "int const volatile restrict *" to the set of 5024/// pointer types. Returns true if the add of @p Ty itself succeeded, 5025/// false otherwise. 5026/// 5027/// FIXME: what to do about extended qualifiers? 5028bool 5029BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 5030 QualType Ty) { 5031 // Insert this type. 5032 if (!MemberPointerTypes.insert(Ty)) 5033 return false; 5034 5035 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 5036 assert(PointerTy && "type was not a member pointer type!"); 5037 5038 QualType PointeeTy = PointerTy->getPointeeType(); 5039 // Don't add qualified variants of arrays. For one, they're not allowed 5040 // (the qualifier would sink to the element type), and for another, the 5041 // only overload situation where it matters is subscript or pointer +- int, 5042 // and those shouldn't have qualifier variants anyway. 5043 if (PointeeTy->isArrayType()) 5044 return true; 5045 const Type *ClassTy = PointerTy->getClass(); 5046 5047 // Iterate through all strict supersets of the pointee type's CVR 5048 // qualifiers. 5049 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 5050 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 5051 if ((CVR | BaseCVR) != CVR) continue; 5052 5053 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 5054 MemberPointerTypes.insert( 5055 Context.getMemberPointerType(QPointeeTy, ClassTy)); 5056 } 5057 5058 return true; 5059} 5060 5061/// AddTypesConvertedFrom - Add each of the types to which the type @p 5062/// Ty can be implicit converted to the given set of @p Types. We're 5063/// primarily interested in pointer types and enumeration types. We also 5064/// take member pointer types, for the conditional operator. 5065/// AllowUserConversions is true if we should look at the conversion 5066/// functions of a class type, and AllowExplicitConversions if we 5067/// should also include the explicit conversion functions of a class 5068/// type. 5069void 5070BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 5071 SourceLocation Loc, 5072 bool AllowUserConversions, 5073 bool AllowExplicitConversions, 5074 const Qualifiers &VisibleQuals) { 5075 // Only deal with canonical types. 5076 Ty = Context.getCanonicalType(Ty); 5077 5078 // Look through reference types; they aren't part of the type of an 5079 // expression for the purposes of conversions. 5080 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 5081 Ty = RefTy->getPointeeType(); 5082 5083 // If we're dealing with an array type, decay to the pointer. 5084 if (Ty->isArrayType()) 5085 Ty = SemaRef.Context.getArrayDecayedType(Ty); 5086 5087 // Otherwise, we don't care about qualifiers on the type. 5088 Ty = Ty.getLocalUnqualifiedType(); 5089 5090 // Flag if we ever add a non-record type. 5091 const RecordType *TyRec = Ty->getAs<RecordType>(); 5092 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 5093 5094 // Flag if we encounter an arithmetic type. 5095 HasArithmeticOrEnumeralTypes = 5096 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 5097 5098 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 5099 PointerTypes.insert(Ty); 5100 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 5101 // Insert our type, and its more-qualified variants, into the set 5102 // of types. 5103 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 5104 return; 5105 } else if (Ty->isMemberPointerType()) { 5106 // Member pointers are far easier, since the pointee can't be converted. 5107 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 5108 return; 5109 } else if (Ty->isEnumeralType()) { 5110 HasArithmeticOrEnumeralTypes = true; 5111 EnumerationTypes.insert(Ty); 5112 } else if (Ty->isVectorType()) { 5113 // We treat vector types as arithmetic types in many contexts as an 5114 // extension. 5115 HasArithmeticOrEnumeralTypes = true; 5116 VectorTypes.insert(Ty); 5117 } else if (Ty->isNullPtrType()) { 5118 HasNullPtrType = true; 5119 } else if (AllowUserConversions && TyRec) { 5120 // No conversion functions in incomplete types. 5121 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 5122 return; 5123 5124 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 5125 const UnresolvedSetImpl *Conversions 5126 = ClassDecl->getVisibleConversionFunctions(); 5127 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5128 E = Conversions->end(); I != E; ++I) { 5129 NamedDecl *D = I.getDecl(); 5130 if (isa<UsingShadowDecl>(D)) 5131 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5132 5133 // Skip conversion function templates; they don't tell us anything 5134 // about which builtin types we can convert to. 5135 if (isa<FunctionTemplateDecl>(D)) 5136 continue; 5137 5138 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 5139 if (AllowExplicitConversions || !Conv->isExplicit()) { 5140 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 5141 VisibleQuals); 5142 } 5143 } 5144 } 5145} 5146 5147/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 5148/// the volatile- and non-volatile-qualified assignment operators for the 5149/// given type to the candidate set. 5150static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 5151 QualType T, 5152 Expr **Args, 5153 unsigned NumArgs, 5154 OverloadCandidateSet &CandidateSet) { 5155 QualType ParamTypes[2]; 5156 5157 // T& operator=(T&, T) 5158 ParamTypes[0] = S.Context.getLValueReferenceType(T); 5159 ParamTypes[1] = T; 5160 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5161 /*IsAssignmentOperator=*/true); 5162 5163 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 5164 // volatile T& operator=(volatile T&, T) 5165 ParamTypes[0] 5166 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 5167 ParamTypes[1] = T; 5168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5169 /*IsAssignmentOperator=*/true); 5170 } 5171} 5172 5173/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 5174/// if any, found in visible type conversion functions found in ArgExpr's type. 5175static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 5176 Qualifiers VRQuals; 5177 const RecordType *TyRec; 5178 if (const MemberPointerType *RHSMPType = 5179 ArgExpr->getType()->getAs<MemberPointerType>()) 5180 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 5181 else 5182 TyRec = ArgExpr->getType()->getAs<RecordType>(); 5183 if (!TyRec) { 5184 // Just to be safe, assume the worst case. 5185 VRQuals.addVolatile(); 5186 VRQuals.addRestrict(); 5187 return VRQuals; 5188 } 5189 5190 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 5191 if (!ClassDecl->hasDefinition()) 5192 return VRQuals; 5193 5194 const UnresolvedSetImpl *Conversions = 5195 ClassDecl->getVisibleConversionFunctions(); 5196 5197 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5198 E = Conversions->end(); I != E; ++I) { 5199 NamedDecl *D = I.getDecl(); 5200 if (isa<UsingShadowDecl>(D)) 5201 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5202 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 5203 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 5204 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 5205 CanTy = ResTypeRef->getPointeeType(); 5206 // Need to go down the pointer/mempointer chain and add qualifiers 5207 // as see them. 5208 bool done = false; 5209 while (!done) { 5210 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 5211 CanTy = ResTypePtr->getPointeeType(); 5212 else if (const MemberPointerType *ResTypeMPtr = 5213 CanTy->getAs<MemberPointerType>()) 5214 CanTy = ResTypeMPtr->getPointeeType(); 5215 else 5216 done = true; 5217 if (CanTy.isVolatileQualified()) 5218 VRQuals.addVolatile(); 5219 if (CanTy.isRestrictQualified()) 5220 VRQuals.addRestrict(); 5221 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 5222 return VRQuals; 5223 } 5224 } 5225 } 5226 return VRQuals; 5227} 5228 5229namespace { 5230 5231/// \brief Helper class to manage the addition of builtin operator overload 5232/// candidates. It provides shared state and utility methods used throughout 5233/// the process, as well as a helper method to add each group of builtin 5234/// operator overloads from the standard to a candidate set. 5235class BuiltinOperatorOverloadBuilder { 5236 // Common instance state available to all overload candidate addition methods. 5237 Sema &S; 5238 Expr **Args; 5239 unsigned NumArgs; 5240 Qualifiers VisibleTypeConversionsQuals; 5241 bool HasArithmeticOrEnumeralCandidateType; 5242 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 5243 OverloadCandidateSet &CandidateSet; 5244 5245 // Define some constants used to index and iterate over the arithemetic types 5246 // provided via the getArithmeticType() method below. 5247 // The "promoted arithmetic types" are the arithmetic 5248 // types are that preserved by promotion (C++ [over.built]p2). 5249 static const unsigned FirstIntegralType = 3; 5250 static const unsigned LastIntegralType = 18; 5251 static const unsigned FirstPromotedIntegralType = 3, 5252 LastPromotedIntegralType = 9; 5253 static const unsigned FirstPromotedArithmeticType = 0, 5254 LastPromotedArithmeticType = 9; 5255 static const unsigned NumArithmeticTypes = 18; 5256 5257 /// \brief Get the canonical type for a given arithmetic type index. 5258 CanQualType getArithmeticType(unsigned index) { 5259 assert(index < NumArithmeticTypes); 5260 static CanQualType ASTContext::* const 5261 ArithmeticTypes[NumArithmeticTypes] = { 5262 // Start of promoted types. 5263 &ASTContext::FloatTy, 5264 &ASTContext::DoubleTy, 5265 &ASTContext::LongDoubleTy, 5266 5267 // Start of integral types. 5268 &ASTContext::IntTy, 5269 &ASTContext::LongTy, 5270 &ASTContext::LongLongTy, 5271 &ASTContext::UnsignedIntTy, 5272 &ASTContext::UnsignedLongTy, 5273 &ASTContext::UnsignedLongLongTy, 5274 // End of promoted types. 5275 5276 &ASTContext::BoolTy, 5277 &ASTContext::CharTy, 5278 &ASTContext::WCharTy, 5279 &ASTContext::Char16Ty, 5280 &ASTContext::Char32Ty, 5281 &ASTContext::SignedCharTy, 5282 &ASTContext::ShortTy, 5283 &ASTContext::UnsignedCharTy, 5284 &ASTContext::UnsignedShortTy, 5285 // End of integral types. 5286 // FIXME: What about complex? 5287 }; 5288 return S.Context.*ArithmeticTypes[index]; 5289 } 5290 5291 /// \brief Gets the canonical type resulting from the usual arithemetic 5292 /// converions for the given arithmetic types. 5293 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 5294 // Accelerator table for performing the usual arithmetic conversions. 5295 // The rules are basically: 5296 // - if either is floating-point, use the wider floating-point 5297 // - if same signedness, use the higher rank 5298 // - if same size, use unsigned of the higher rank 5299 // - use the larger type 5300 // These rules, together with the axiom that higher ranks are 5301 // never smaller, are sufficient to precompute all of these results 5302 // *except* when dealing with signed types of higher rank. 5303 // (we could precompute SLL x UI for all known platforms, but it's 5304 // better not to make any assumptions). 5305 enum PromotedType { 5306 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 5307 }; 5308 static PromotedType ConversionsTable[LastPromotedArithmeticType] 5309 [LastPromotedArithmeticType] = { 5310 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt }, 5311 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 5312 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 5313 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL }, 5314 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL }, 5315 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL }, 5316 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL }, 5317 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL }, 5318 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }, 5319 }; 5320 5321 assert(L < LastPromotedArithmeticType); 5322 assert(R < LastPromotedArithmeticType); 5323 int Idx = ConversionsTable[L][R]; 5324 5325 // Fast path: the table gives us a concrete answer. 5326 if (Idx != Dep) return getArithmeticType(Idx); 5327 5328 // Slow path: we need to compare widths. 5329 // An invariant is that the signed type has higher rank. 5330 CanQualType LT = getArithmeticType(L), 5331 RT = getArithmeticType(R); 5332 unsigned LW = S.Context.getIntWidth(LT), 5333 RW = S.Context.getIntWidth(RT); 5334 5335 // If they're different widths, use the signed type. 5336 if (LW > RW) return LT; 5337 else if (LW < RW) return RT; 5338 5339 // Otherwise, use the unsigned type of the signed type's rank. 5340 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 5341 assert(L == SLL || R == SLL); 5342 return S.Context.UnsignedLongLongTy; 5343 } 5344 5345 /// \brief Helper method to factor out the common pattern of adding overloads 5346 /// for '++' and '--' builtin operators. 5347 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 5348 bool HasVolatile) { 5349 QualType ParamTypes[2] = { 5350 S.Context.getLValueReferenceType(CandidateTy), 5351 S.Context.IntTy 5352 }; 5353 5354 // Non-volatile version. 5355 if (NumArgs == 1) 5356 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 5357 else 5358 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 5359 5360 // Use a heuristic to reduce number of builtin candidates in the set: 5361 // add volatile version only if there are conversions to a volatile type. 5362 if (HasVolatile) { 5363 ParamTypes[0] = 5364 S.Context.getLValueReferenceType( 5365 S.Context.getVolatileType(CandidateTy)); 5366 if (NumArgs == 1) 5367 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 5368 else 5369 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 5370 } 5371 } 5372 5373public: 5374 BuiltinOperatorOverloadBuilder( 5375 Sema &S, Expr **Args, unsigned NumArgs, 5376 Qualifiers VisibleTypeConversionsQuals, 5377 bool HasArithmeticOrEnumeralCandidateType, 5378 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 5379 OverloadCandidateSet &CandidateSet) 5380 : S(S), Args(Args), NumArgs(NumArgs), 5381 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 5382 HasArithmeticOrEnumeralCandidateType( 5383 HasArithmeticOrEnumeralCandidateType), 5384 CandidateTypes(CandidateTypes), 5385 CandidateSet(CandidateSet) { 5386 // Validate some of our static helper constants in debug builds. 5387 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 5388 "Invalid first promoted integral type"); 5389 assert(getArithmeticType(LastPromotedIntegralType - 1) 5390 == S.Context.UnsignedLongLongTy && 5391 "Invalid last promoted integral type"); 5392 assert(getArithmeticType(FirstPromotedArithmeticType) 5393 == S.Context.FloatTy && 5394 "Invalid first promoted arithmetic type"); 5395 assert(getArithmeticType(LastPromotedArithmeticType - 1) 5396 == S.Context.UnsignedLongLongTy && 5397 "Invalid last promoted arithmetic type"); 5398 } 5399 5400 // C++ [over.built]p3: 5401 // 5402 // For every pair (T, VQ), where T is an arithmetic type, and VQ 5403 // is either volatile or empty, there exist candidate operator 5404 // functions of the form 5405 // 5406 // VQ T& operator++(VQ T&); 5407 // T operator++(VQ T&, int); 5408 // 5409 // C++ [over.built]p4: 5410 // 5411 // For every pair (T, VQ), where T is an arithmetic type other 5412 // than bool, and VQ is either volatile or empty, there exist 5413 // candidate operator functions of the form 5414 // 5415 // VQ T& operator--(VQ T&); 5416 // T operator--(VQ T&, int); 5417 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 5418 if (!HasArithmeticOrEnumeralCandidateType) 5419 return; 5420 5421 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 5422 Arith < NumArithmeticTypes; ++Arith) { 5423 addPlusPlusMinusMinusStyleOverloads( 5424 getArithmeticType(Arith), 5425 VisibleTypeConversionsQuals.hasVolatile()); 5426 } 5427 } 5428 5429 // C++ [over.built]p5: 5430 // 5431 // For every pair (T, VQ), where T is a cv-qualified or 5432 // cv-unqualified object type, and VQ is either volatile or 5433 // empty, there exist candidate operator functions of the form 5434 // 5435 // T*VQ& operator++(T*VQ&); 5436 // T*VQ& operator--(T*VQ&); 5437 // T* operator++(T*VQ&, int); 5438 // T* operator--(T*VQ&, int); 5439 void addPlusPlusMinusMinusPointerOverloads() { 5440 for (BuiltinCandidateTypeSet::iterator 5441 Ptr = CandidateTypes[0].pointer_begin(), 5442 PtrEnd = CandidateTypes[0].pointer_end(); 5443 Ptr != PtrEnd; ++Ptr) { 5444 // Skip pointer types that aren't pointers to object types. 5445 if (!(*Ptr)->getPointeeType()->isObjectType()) 5446 continue; 5447 5448 addPlusPlusMinusMinusStyleOverloads(*Ptr, 5449 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5450 VisibleTypeConversionsQuals.hasVolatile())); 5451 } 5452 } 5453 5454 // C++ [over.built]p6: 5455 // For every cv-qualified or cv-unqualified object type T, there 5456 // exist candidate operator functions of the form 5457 // 5458 // T& operator*(T*); 5459 // 5460 // C++ [over.built]p7: 5461 // For every function type T that does not have cv-qualifiers or a 5462 // ref-qualifier, there exist candidate operator functions of the form 5463 // T& operator*(T*); 5464 void addUnaryStarPointerOverloads() { 5465 for (BuiltinCandidateTypeSet::iterator 5466 Ptr = CandidateTypes[0].pointer_begin(), 5467 PtrEnd = CandidateTypes[0].pointer_end(); 5468 Ptr != PtrEnd; ++Ptr) { 5469 QualType ParamTy = *Ptr; 5470 QualType PointeeTy = ParamTy->getPointeeType(); 5471 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 5472 continue; 5473 5474 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 5475 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 5476 continue; 5477 5478 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 5479 &ParamTy, Args, 1, CandidateSet); 5480 } 5481 } 5482 5483 // C++ [over.built]p9: 5484 // For every promoted arithmetic type T, there exist candidate 5485 // operator functions of the form 5486 // 5487 // T operator+(T); 5488 // T operator-(T); 5489 void addUnaryPlusOrMinusArithmeticOverloads() { 5490 if (!HasArithmeticOrEnumeralCandidateType) 5491 return; 5492 5493 for (unsigned Arith = FirstPromotedArithmeticType; 5494 Arith < LastPromotedArithmeticType; ++Arith) { 5495 QualType ArithTy = getArithmeticType(Arith); 5496 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 5497 } 5498 5499 // Extension: We also add these operators for vector types. 5500 for (BuiltinCandidateTypeSet::iterator 5501 Vec = CandidateTypes[0].vector_begin(), 5502 VecEnd = CandidateTypes[0].vector_end(); 5503 Vec != VecEnd; ++Vec) { 5504 QualType VecTy = *Vec; 5505 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 5506 } 5507 } 5508 5509 // C++ [over.built]p8: 5510 // For every type T, there exist candidate operator functions of 5511 // the form 5512 // 5513 // T* operator+(T*); 5514 void addUnaryPlusPointerOverloads() { 5515 for (BuiltinCandidateTypeSet::iterator 5516 Ptr = CandidateTypes[0].pointer_begin(), 5517 PtrEnd = CandidateTypes[0].pointer_end(); 5518 Ptr != PtrEnd; ++Ptr) { 5519 QualType ParamTy = *Ptr; 5520 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 5521 } 5522 } 5523 5524 // C++ [over.built]p10: 5525 // For every promoted integral type T, there exist candidate 5526 // operator functions of the form 5527 // 5528 // T operator~(T); 5529 void addUnaryTildePromotedIntegralOverloads() { 5530 if (!HasArithmeticOrEnumeralCandidateType) 5531 return; 5532 5533 for (unsigned Int = FirstPromotedIntegralType; 5534 Int < LastPromotedIntegralType; ++Int) { 5535 QualType IntTy = getArithmeticType(Int); 5536 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 5537 } 5538 5539 // Extension: We also add this operator for vector types. 5540 for (BuiltinCandidateTypeSet::iterator 5541 Vec = CandidateTypes[0].vector_begin(), 5542 VecEnd = CandidateTypes[0].vector_end(); 5543 Vec != VecEnd; ++Vec) { 5544 QualType VecTy = *Vec; 5545 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 5546 } 5547 } 5548 5549 // C++ [over.match.oper]p16: 5550 // For every pointer to member type T, there exist candidate operator 5551 // functions of the form 5552 // 5553 // bool operator==(T,T); 5554 // bool operator!=(T,T); 5555 void addEqualEqualOrNotEqualMemberPointerOverloads() { 5556 /// Set of (canonical) types that we've already handled. 5557 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5558 5559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5560 for (BuiltinCandidateTypeSet::iterator 5561 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 5562 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 5563 MemPtr != MemPtrEnd; 5564 ++MemPtr) { 5565 // Don't add the same builtin candidate twice. 5566 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 5567 continue; 5568 5569 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 5570 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5571 CandidateSet); 5572 } 5573 } 5574 } 5575 5576 // C++ [over.built]p15: 5577 // 5578 // For every T, where T is an enumeration type, a pointer type, or 5579 // std::nullptr_t, there exist candidate operator functions of the form 5580 // 5581 // bool operator<(T, T); 5582 // bool operator>(T, T); 5583 // bool operator<=(T, T); 5584 // bool operator>=(T, T); 5585 // bool operator==(T, T); 5586 // bool operator!=(T, T); 5587 void addRelationalPointerOrEnumeralOverloads() { 5588 // C++ [over.built]p1: 5589 // If there is a user-written candidate with the same name and parameter 5590 // types as a built-in candidate operator function, the built-in operator 5591 // function is hidden and is not included in the set of candidate 5592 // functions. 5593 // 5594 // The text is actually in a note, but if we don't implement it then we end 5595 // up with ambiguities when the user provides an overloaded operator for 5596 // an enumeration type. Note that only enumeration types have this problem, 5597 // so we track which enumeration types we've seen operators for. Also, the 5598 // only other overloaded operator with enumeration argumenst, operator=, 5599 // cannot be overloaded for enumeration types, so this is the only place 5600 // where we must suppress candidates like this. 5601 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 5602 UserDefinedBinaryOperators; 5603 5604 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5605 if (CandidateTypes[ArgIdx].enumeration_begin() != 5606 CandidateTypes[ArgIdx].enumeration_end()) { 5607 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 5608 CEnd = CandidateSet.end(); 5609 C != CEnd; ++C) { 5610 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 5611 continue; 5612 5613 QualType FirstParamType = 5614 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 5615 QualType SecondParamType = 5616 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 5617 5618 // Skip if either parameter isn't of enumeral type. 5619 if (!FirstParamType->isEnumeralType() || 5620 !SecondParamType->isEnumeralType()) 5621 continue; 5622 5623 // Add this operator to the set of known user-defined operators. 5624 UserDefinedBinaryOperators.insert( 5625 std::make_pair(S.Context.getCanonicalType(FirstParamType), 5626 S.Context.getCanonicalType(SecondParamType))); 5627 } 5628 } 5629 } 5630 5631 /// Set of (canonical) types that we've already handled. 5632 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5633 5634 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5635 for (BuiltinCandidateTypeSet::iterator 5636 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 5637 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 5638 Ptr != PtrEnd; ++Ptr) { 5639 // Don't add the same builtin candidate twice. 5640 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5641 continue; 5642 5643 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5644 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5645 CandidateSet); 5646 } 5647 for (BuiltinCandidateTypeSet::iterator 5648 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5649 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5650 Enum != EnumEnd; ++Enum) { 5651 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 5652 5653 // Don't add the same builtin candidate twice, or if a user defined 5654 // candidate exists. 5655 if (!AddedTypes.insert(CanonType) || 5656 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 5657 CanonType))) 5658 continue; 5659 5660 QualType ParamTypes[2] = { *Enum, *Enum }; 5661 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5662 CandidateSet); 5663 } 5664 5665 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 5666 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 5667 if (AddedTypes.insert(NullPtrTy) && 5668 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 5669 NullPtrTy))) { 5670 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 5671 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5672 CandidateSet); 5673 } 5674 } 5675 } 5676 } 5677 5678 // C++ [over.built]p13: 5679 // 5680 // For every cv-qualified or cv-unqualified object type T 5681 // there exist candidate operator functions of the form 5682 // 5683 // T* operator+(T*, ptrdiff_t); 5684 // T& operator[](T*, ptrdiff_t); [BELOW] 5685 // T* operator-(T*, ptrdiff_t); 5686 // T* operator+(ptrdiff_t, T*); 5687 // T& operator[](ptrdiff_t, T*); [BELOW] 5688 // 5689 // C++ [over.built]p14: 5690 // 5691 // For every T, where T is a pointer to object type, there 5692 // exist candidate operator functions of the form 5693 // 5694 // ptrdiff_t operator-(T, T); 5695 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 5696 /// Set of (canonical) types that we've already handled. 5697 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5698 5699 for (int Arg = 0; Arg < 2; ++Arg) { 5700 QualType AsymetricParamTypes[2] = { 5701 S.Context.getPointerDiffType(), 5702 S.Context.getPointerDiffType(), 5703 }; 5704 for (BuiltinCandidateTypeSet::iterator 5705 Ptr = CandidateTypes[Arg].pointer_begin(), 5706 PtrEnd = CandidateTypes[Arg].pointer_end(); 5707 Ptr != PtrEnd; ++Ptr) { 5708 QualType PointeeTy = (*Ptr)->getPointeeType(); 5709 if (!PointeeTy->isObjectType()) 5710 continue; 5711 5712 AsymetricParamTypes[Arg] = *Ptr; 5713 if (Arg == 0 || Op == OO_Plus) { 5714 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 5715 // T* operator+(ptrdiff_t, T*); 5716 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 5717 CandidateSet); 5718 } 5719 if (Op == OO_Minus) { 5720 // ptrdiff_t operator-(T, T); 5721 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5722 continue; 5723 5724 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5725 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 5726 Args, 2, CandidateSet); 5727 } 5728 } 5729 } 5730 } 5731 5732 // C++ [over.built]p12: 5733 // 5734 // For every pair of promoted arithmetic types L and R, there 5735 // exist candidate operator functions of the form 5736 // 5737 // LR operator*(L, R); 5738 // LR operator/(L, R); 5739 // LR operator+(L, R); 5740 // LR operator-(L, R); 5741 // bool operator<(L, R); 5742 // bool operator>(L, R); 5743 // bool operator<=(L, R); 5744 // bool operator>=(L, R); 5745 // bool operator==(L, R); 5746 // bool operator!=(L, R); 5747 // 5748 // where LR is the result of the usual arithmetic conversions 5749 // between types L and R. 5750 // 5751 // C++ [over.built]p24: 5752 // 5753 // For every pair of promoted arithmetic types L and R, there exist 5754 // candidate operator functions of the form 5755 // 5756 // LR operator?(bool, L, R); 5757 // 5758 // where LR is the result of the usual arithmetic conversions 5759 // between types L and R. 5760 // Our candidates ignore the first parameter. 5761 void addGenericBinaryArithmeticOverloads(bool isComparison) { 5762 if (!HasArithmeticOrEnumeralCandidateType) 5763 return; 5764 5765 for (unsigned Left = FirstPromotedArithmeticType; 5766 Left < LastPromotedArithmeticType; ++Left) { 5767 for (unsigned Right = FirstPromotedArithmeticType; 5768 Right < LastPromotedArithmeticType; ++Right) { 5769 QualType LandR[2] = { getArithmeticType(Left), 5770 getArithmeticType(Right) }; 5771 QualType Result = 5772 isComparison ? S.Context.BoolTy 5773 : getUsualArithmeticConversions(Left, Right); 5774 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5775 } 5776 } 5777 5778 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 5779 // conditional operator for vector types. 5780 for (BuiltinCandidateTypeSet::iterator 5781 Vec1 = CandidateTypes[0].vector_begin(), 5782 Vec1End = CandidateTypes[0].vector_end(); 5783 Vec1 != Vec1End; ++Vec1) { 5784 for (BuiltinCandidateTypeSet::iterator 5785 Vec2 = CandidateTypes[1].vector_begin(), 5786 Vec2End = CandidateTypes[1].vector_end(); 5787 Vec2 != Vec2End; ++Vec2) { 5788 QualType LandR[2] = { *Vec1, *Vec2 }; 5789 QualType Result = S.Context.BoolTy; 5790 if (!isComparison) { 5791 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 5792 Result = *Vec1; 5793 else 5794 Result = *Vec2; 5795 } 5796 5797 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5798 } 5799 } 5800 } 5801 5802 // C++ [over.built]p17: 5803 // 5804 // For every pair of promoted integral types L and R, there 5805 // exist candidate operator functions of the form 5806 // 5807 // LR operator%(L, R); 5808 // LR operator&(L, R); 5809 // LR operator^(L, R); 5810 // LR operator|(L, R); 5811 // L operator<<(L, R); 5812 // L operator>>(L, R); 5813 // 5814 // where LR is the result of the usual arithmetic conversions 5815 // between types L and R. 5816 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 5817 if (!HasArithmeticOrEnumeralCandidateType) 5818 return; 5819 5820 for (unsigned Left = FirstPromotedIntegralType; 5821 Left < LastPromotedIntegralType; ++Left) { 5822 for (unsigned Right = FirstPromotedIntegralType; 5823 Right < LastPromotedIntegralType; ++Right) { 5824 QualType LandR[2] = { getArithmeticType(Left), 5825 getArithmeticType(Right) }; 5826 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 5827 ? LandR[0] 5828 : getUsualArithmeticConversions(Left, Right); 5829 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5830 } 5831 } 5832 } 5833 5834 // C++ [over.built]p20: 5835 // 5836 // For every pair (T, VQ), where T is an enumeration or 5837 // pointer to member type and VQ is either volatile or 5838 // empty, there exist candidate operator functions of the form 5839 // 5840 // VQ T& operator=(VQ T&, T); 5841 void addAssignmentMemberPointerOrEnumeralOverloads() { 5842 /// Set of (canonical) types that we've already handled. 5843 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5844 5845 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 5846 for (BuiltinCandidateTypeSet::iterator 5847 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5848 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5849 Enum != EnumEnd; ++Enum) { 5850 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 5851 continue; 5852 5853 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 5854 CandidateSet); 5855 } 5856 5857 for (BuiltinCandidateTypeSet::iterator 5858 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 5859 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 5860 MemPtr != MemPtrEnd; ++MemPtr) { 5861 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 5862 continue; 5863 5864 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 5865 CandidateSet); 5866 } 5867 } 5868 } 5869 5870 // C++ [over.built]p19: 5871 // 5872 // For every pair (T, VQ), where T is any type and VQ is either 5873 // volatile or empty, there exist candidate operator functions 5874 // of the form 5875 // 5876 // T*VQ& operator=(T*VQ&, T*); 5877 // 5878 // C++ [over.built]p21: 5879 // 5880 // For every pair (T, VQ), where T is a cv-qualified or 5881 // cv-unqualified object type and VQ is either volatile or 5882 // empty, there exist candidate operator functions of the form 5883 // 5884 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 5885 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 5886 void addAssignmentPointerOverloads(bool isEqualOp) { 5887 /// Set of (canonical) types that we've already handled. 5888 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5889 5890 for (BuiltinCandidateTypeSet::iterator 5891 Ptr = CandidateTypes[0].pointer_begin(), 5892 PtrEnd = CandidateTypes[0].pointer_end(); 5893 Ptr != PtrEnd; ++Ptr) { 5894 // If this is operator=, keep track of the builtin candidates we added. 5895 if (isEqualOp) 5896 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 5897 else if (!(*Ptr)->getPointeeType()->isObjectType()) 5898 continue; 5899 5900 // non-volatile version 5901 QualType ParamTypes[2] = { 5902 S.Context.getLValueReferenceType(*Ptr), 5903 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 5904 }; 5905 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5906 /*IsAssigmentOperator=*/ isEqualOp); 5907 5908 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5909 VisibleTypeConversionsQuals.hasVolatile()) { 5910 // volatile version 5911 ParamTypes[0] = 5912 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 5913 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5914 /*IsAssigmentOperator=*/isEqualOp); 5915 } 5916 } 5917 5918 if (isEqualOp) { 5919 for (BuiltinCandidateTypeSet::iterator 5920 Ptr = CandidateTypes[1].pointer_begin(), 5921 PtrEnd = CandidateTypes[1].pointer_end(); 5922 Ptr != PtrEnd; ++Ptr) { 5923 // Make sure we don't add the same candidate twice. 5924 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5925 continue; 5926 5927 QualType ParamTypes[2] = { 5928 S.Context.getLValueReferenceType(*Ptr), 5929 *Ptr, 5930 }; 5931 5932 // non-volatile version 5933 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5934 /*IsAssigmentOperator=*/true); 5935 5936 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5937 VisibleTypeConversionsQuals.hasVolatile()) { 5938 // volatile version 5939 ParamTypes[0] = 5940 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 5941 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5942 CandidateSet, /*IsAssigmentOperator=*/true); 5943 } 5944 } 5945 } 5946 } 5947 5948 // C++ [over.built]p18: 5949 // 5950 // For every triple (L, VQ, R), where L is an arithmetic type, 5951 // VQ is either volatile or empty, and R is a promoted 5952 // arithmetic type, there exist candidate operator functions of 5953 // the form 5954 // 5955 // VQ L& operator=(VQ L&, R); 5956 // VQ L& operator*=(VQ L&, R); 5957 // VQ L& operator/=(VQ L&, R); 5958 // VQ L& operator+=(VQ L&, R); 5959 // VQ L& operator-=(VQ L&, R); 5960 void addAssignmentArithmeticOverloads(bool isEqualOp) { 5961 if (!HasArithmeticOrEnumeralCandidateType) 5962 return; 5963 5964 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 5965 for (unsigned Right = FirstPromotedArithmeticType; 5966 Right < LastPromotedArithmeticType; ++Right) { 5967 QualType ParamTypes[2]; 5968 ParamTypes[1] = getArithmeticType(Right); 5969 5970 // Add this built-in operator as a candidate (VQ is empty). 5971 ParamTypes[0] = 5972 S.Context.getLValueReferenceType(getArithmeticType(Left)); 5973 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5974 /*IsAssigmentOperator=*/isEqualOp); 5975 5976 // Add this built-in operator as a candidate (VQ is 'volatile'). 5977 if (VisibleTypeConversionsQuals.hasVolatile()) { 5978 ParamTypes[0] = 5979 S.Context.getVolatileType(getArithmeticType(Left)); 5980 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 5981 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5982 CandidateSet, 5983 /*IsAssigmentOperator=*/isEqualOp); 5984 } 5985 } 5986 } 5987 5988 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 5989 for (BuiltinCandidateTypeSet::iterator 5990 Vec1 = CandidateTypes[0].vector_begin(), 5991 Vec1End = CandidateTypes[0].vector_end(); 5992 Vec1 != Vec1End; ++Vec1) { 5993 for (BuiltinCandidateTypeSet::iterator 5994 Vec2 = CandidateTypes[1].vector_begin(), 5995 Vec2End = CandidateTypes[1].vector_end(); 5996 Vec2 != Vec2End; ++Vec2) { 5997 QualType ParamTypes[2]; 5998 ParamTypes[1] = *Vec2; 5999 // Add this built-in operator as a candidate (VQ is empty). 6000 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 6001 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6002 /*IsAssigmentOperator=*/isEqualOp); 6003 6004 // Add this built-in operator as a candidate (VQ is 'volatile'). 6005 if (VisibleTypeConversionsQuals.hasVolatile()) { 6006 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 6007 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 6008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 6009 CandidateSet, 6010 /*IsAssigmentOperator=*/isEqualOp); 6011 } 6012 } 6013 } 6014 } 6015 6016 // C++ [over.built]p22: 6017 // 6018 // For every triple (L, VQ, R), where L is an integral type, VQ 6019 // is either volatile or empty, and R is a promoted integral 6020 // type, there exist candidate operator functions of the form 6021 // 6022 // VQ L& operator%=(VQ L&, R); 6023 // VQ L& operator<<=(VQ L&, R); 6024 // VQ L& operator>>=(VQ L&, R); 6025 // VQ L& operator&=(VQ L&, R); 6026 // VQ L& operator^=(VQ L&, R); 6027 // VQ L& operator|=(VQ L&, R); 6028 void addAssignmentIntegralOverloads() { 6029 if (!HasArithmeticOrEnumeralCandidateType) 6030 return; 6031 6032 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 6033 for (unsigned Right = FirstPromotedIntegralType; 6034 Right < LastPromotedIntegralType; ++Right) { 6035 QualType ParamTypes[2]; 6036 ParamTypes[1] = getArithmeticType(Right); 6037 6038 // Add this built-in operator as a candidate (VQ is empty). 6039 ParamTypes[0] = 6040 S.Context.getLValueReferenceType(getArithmeticType(Left)); 6041 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 6042 if (VisibleTypeConversionsQuals.hasVolatile()) { 6043 // Add this built-in operator as a candidate (VQ is 'volatile'). 6044 ParamTypes[0] = getArithmeticType(Left); 6045 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 6046 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 6047 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 6048 CandidateSet); 6049 } 6050 } 6051 } 6052 } 6053 6054 // C++ [over.operator]p23: 6055 // 6056 // There also exist candidate operator functions of the form 6057 // 6058 // bool operator!(bool); 6059 // bool operator&&(bool, bool); 6060 // bool operator||(bool, bool); 6061 void addExclaimOverload() { 6062 QualType ParamTy = S.Context.BoolTy; 6063 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 6064 /*IsAssignmentOperator=*/false, 6065 /*NumContextualBoolArguments=*/1); 6066 } 6067 void addAmpAmpOrPipePipeOverload() { 6068 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 6069 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 6070 /*IsAssignmentOperator=*/false, 6071 /*NumContextualBoolArguments=*/2); 6072 } 6073 6074 // C++ [over.built]p13: 6075 // 6076 // For every cv-qualified or cv-unqualified object type T there 6077 // exist candidate operator functions of the form 6078 // 6079 // T* operator+(T*, ptrdiff_t); [ABOVE] 6080 // T& operator[](T*, ptrdiff_t); 6081 // T* operator-(T*, ptrdiff_t); [ABOVE] 6082 // T* operator+(ptrdiff_t, T*); [ABOVE] 6083 // T& operator[](ptrdiff_t, T*); 6084 void addSubscriptOverloads() { 6085 for (BuiltinCandidateTypeSet::iterator 6086 Ptr = CandidateTypes[0].pointer_begin(), 6087 PtrEnd = CandidateTypes[0].pointer_end(); 6088 Ptr != PtrEnd; ++Ptr) { 6089 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 6090 QualType PointeeType = (*Ptr)->getPointeeType(); 6091 if (!PointeeType->isObjectType()) 6092 continue; 6093 6094 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 6095 6096 // T& operator[](T*, ptrdiff_t) 6097 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 6098 } 6099 6100 for (BuiltinCandidateTypeSet::iterator 6101 Ptr = CandidateTypes[1].pointer_begin(), 6102 PtrEnd = CandidateTypes[1].pointer_end(); 6103 Ptr != PtrEnd; ++Ptr) { 6104 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 6105 QualType PointeeType = (*Ptr)->getPointeeType(); 6106 if (!PointeeType->isObjectType()) 6107 continue; 6108 6109 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 6110 6111 // T& operator[](ptrdiff_t, T*) 6112 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 6113 } 6114 } 6115 6116 // C++ [over.built]p11: 6117 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 6118 // C1 is the same type as C2 or is a derived class of C2, T is an object 6119 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 6120 // there exist candidate operator functions of the form 6121 // 6122 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 6123 // 6124 // where CV12 is the union of CV1 and CV2. 6125 void addArrowStarOverloads() { 6126 for (BuiltinCandidateTypeSet::iterator 6127 Ptr = CandidateTypes[0].pointer_begin(), 6128 PtrEnd = CandidateTypes[0].pointer_end(); 6129 Ptr != PtrEnd; ++Ptr) { 6130 QualType C1Ty = (*Ptr); 6131 QualType C1; 6132 QualifierCollector Q1; 6133 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 6134 if (!isa<RecordType>(C1)) 6135 continue; 6136 // heuristic to reduce number of builtin candidates in the set. 6137 // Add volatile/restrict version only if there are conversions to a 6138 // volatile/restrict type. 6139 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 6140 continue; 6141 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 6142 continue; 6143 for (BuiltinCandidateTypeSet::iterator 6144 MemPtr = CandidateTypes[1].member_pointer_begin(), 6145 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 6146 MemPtr != MemPtrEnd; ++MemPtr) { 6147 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 6148 QualType C2 = QualType(mptr->getClass(), 0); 6149 C2 = C2.getUnqualifiedType(); 6150 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 6151 break; 6152 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 6153 // build CV12 T& 6154 QualType T = mptr->getPointeeType(); 6155 if (!VisibleTypeConversionsQuals.hasVolatile() && 6156 T.isVolatileQualified()) 6157 continue; 6158 if (!VisibleTypeConversionsQuals.hasRestrict() && 6159 T.isRestrictQualified()) 6160 continue; 6161 T = Q1.apply(S.Context, T); 6162 QualType ResultTy = S.Context.getLValueReferenceType(T); 6163 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 6164 } 6165 } 6166 } 6167 6168 // Note that we don't consider the first argument, since it has been 6169 // contextually converted to bool long ago. The candidates below are 6170 // therefore added as binary. 6171 // 6172 // C++ [over.built]p25: 6173 // For every type T, where T is a pointer, pointer-to-member, or scoped 6174 // enumeration type, there exist candidate operator functions of the form 6175 // 6176 // T operator?(bool, T, T); 6177 // 6178 void addConditionalOperatorOverloads() { 6179 /// Set of (canonical) types that we've already handled. 6180 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6181 6182 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 6183 for (BuiltinCandidateTypeSet::iterator 6184 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6185 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6186 Ptr != PtrEnd; ++Ptr) { 6187 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6188 continue; 6189 6190 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6191 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 6192 } 6193 6194 for (BuiltinCandidateTypeSet::iterator 6195 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6196 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6197 MemPtr != MemPtrEnd; ++MemPtr) { 6198 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6199 continue; 6200 6201 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6202 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 6203 } 6204 6205 if (S.getLangOptions().CPlusPlus0x) { 6206 for (BuiltinCandidateTypeSet::iterator 6207 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6208 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6209 Enum != EnumEnd; ++Enum) { 6210 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 6211 continue; 6212 6213 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 6214 continue; 6215 6216 QualType ParamTypes[2] = { *Enum, *Enum }; 6217 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 6218 } 6219 } 6220 } 6221 } 6222}; 6223 6224} // end anonymous namespace 6225 6226/// AddBuiltinOperatorCandidates - Add the appropriate built-in 6227/// operator overloads to the candidate set (C++ [over.built]), based 6228/// on the operator @p Op and the arguments given. For example, if the 6229/// operator is a binary '+', this routine might add "int 6230/// operator+(int, int)" to cover integer addition. 6231void 6232Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 6233 SourceLocation OpLoc, 6234 Expr **Args, unsigned NumArgs, 6235 OverloadCandidateSet& CandidateSet) { 6236 // Find all of the types that the arguments can convert to, but only 6237 // if the operator we're looking at has built-in operator candidates 6238 // that make use of these types. Also record whether we encounter non-record 6239 // candidate types or either arithmetic or enumeral candidate types. 6240 Qualifiers VisibleTypeConversionsQuals; 6241 VisibleTypeConversionsQuals.addConst(); 6242 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6243 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 6244 6245 bool HasNonRecordCandidateType = false; 6246 bool HasArithmeticOrEnumeralCandidateType = false; 6247 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 6248 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6249 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 6250 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 6251 OpLoc, 6252 true, 6253 (Op == OO_Exclaim || 6254 Op == OO_AmpAmp || 6255 Op == OO_PipePipe), 6256 VisibleTypeConversionsQuals); 6257 HasNonRecordCandidateType = HasNonRecordCandidateType || 6258 CandidateTypes[ArgIdx].hasNonRecordTypes(); 6259 HasArithmeticOrEnumeralCandidateType = 6260 HasArithmeticOrEnumeralCandidateType || 6261 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 6262 } 6263 6264 // Exit early when no non-record types have been added to the candidate set 6265 // for any of the arguments to the operator. 6266 if (!HasNonRecordCandidateType) 6267 return; 6268 6269 // Setup an object to manage the common state for building overloads. 6270 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 6271 VisibleTypeConversionsQuals, 6272 HasArithmeticOrEnumeralCandidateType, 6273 CandidateTypes, CandidateSet); 6274 6275 // Dispatch over the operation to add in only those overloads which apply. 6276 switch (Op) { 6277 case OO_None: 6278 case NUM_OVERLOADED_OPERATORS: 6279 assert(false && "Expected an overloaded operator"); 6280 break; 6281 6282 case OO_New: 6283 case OO_Delete: 6284 case OO_Array_New: 6285 case OO_Array_Delete: 6286 case OO_Call: 6287 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 6288 break; 6289 6290 case OO_Comma: 6291 case OO_Arrow: 6292 // C++ [over.match.oper]p3: 6293 // -- For the operator ',', the unary operator '&', or the 6294 // operator '->', the built-in candidates set is empty. 6295 break; 6296 6297 case OO_Plus: // '+' is either unary or binary 6298 if (NumArgs == 1) 6299 OpBuilder.addUnaryPlusPointerOverloads(); 6300 // Fall through. 6301 6302 case OO_Minus: // '-' is either unary or binary 6303 if (NumArgs == 1) { 6304 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 6305 } else { 6306 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 6307 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6308 } 6309 break; 6310 6311 case OO_Star: // '*' is either unary or binary 6312 if (NumArgs == 1) 6313 OpBuilder.addUnaryStarPointerOverloads(); 6314 else 6315 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6316 break; 6317 6318 case OO_Slash: 6319 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6320 break; 6321 6322 case OO_PlusPlus: 6323 case OO_MinusMinus: 6324 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 6325 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 6326 break; 6327 6328 case OO_EqualEqual: 6329 case OO_ExclaimEqual: 6330 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 6331 // Fall through. 6332 6333 case OO_Less: 6334 case OO_Greater: 6335 case OO_LessEqual: 6336 case OO_GreaterEqual: 6337 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 6338 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 6339 break; 6340 6341 case OO_Percent: 6342 case OO_Caret: 6343 case OO_Pipe: 6344 case OO_LessLess: 6345 case OO_GreaterGreater: 6346 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 6347 break; 6348 6349 case OO_Amp: // '&' is either unary or binary 6350 if (NumArgs == 1) 6351 // C++ [over.match.oper]p3: 6352 // -- For the operator ',', the unary operator '&', or the 6353 // operator '->', the built-in candidates set is empty. 6354 break; 6355 6356 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 6357 break; 6358 6359 case OO_Tilde: 6360 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 6361 break; 6362 6363 case OO_Equal: 6364 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 6365 // Fall through. 6366 6367 case OO_PlusEqual: 6368 case OO_MinusEqual: 6369 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 6370 // Fall through. 6371 6372 case OO_StarEqual: 6373 case OO_SlashEqual: 6374 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 6375 break; 6376 6377 case OO_PercentEqual: 6378 case OO_LessLessEqual: 6379 case OO_GreaterGreaterEqual: 6380 case OO_AmpEqual: 6381 case OO_CaretEqual: 6382 case OO_PipeEqual: 6383 OpBuilder.addAssignmentIntegralOverloads(); 6384 break; 6385 6386 case OO_Exclaim: 6387 OpBuilder.addExclaimOverload(); 6388 break; 6389 6390 case OO_AmpAmp: 6391 case OO_PipePipe: 6392 OpBuilder.addAmpAmpOrPipePipeOverload(); 6393 break; 6394 6395 case OO_Subscript: 6396 OpBuilder.addSubscriptOverloads(); 6397 break; 6398 6399 case OO_ArrowStar: 6400 OpBuilder.addArrowStarOverloads(); 6401 break; 6402 6403 case OO_Conditional: 6404 OpBuilder.addConditionalOperatorOverloads(); 6405 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6406 break; 6407 } 6408} 6409 6410/// \brief Add function candidates found via argument-dependent lookup 6411/// to the set of overloading candidates. 6412/// 6413/// This routine performs argument-dependent name lookup based on the 6414/// given function name (which may also be an operator name) and adds 6415/// all of the overload candidates found by ADL to the overload 6416/// candidate set (C++ [basic.lookup.argdep]). 6417void 6418Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 6419 bool Operator, 6420 Expr **Args, unsigned NumArgs, 6421 TemplateArgumentListInfo *ExplicitTemplateArgs, 6422 OverloadCandidateSet& CandidateSet, 6423 bool PartialOverloading, 6424 bool StdNamespaceIsAssociated) { 6425 ADLResult Fns; 6426 6427 // FIXME: This approach for uniquing ADL results (and removing 6428 // redundant candidates from the set) relies on pointer-equality, 6429 // which means we need to key off the canonical decl. However, 6430 // always going back to the canonical decl might not get us the 6431 // right set of default arguments. What default arguments are 6432 // we supposed to consider on ADL candidates, anyway? 6433 6434 // FIXME: Pass in the explicit template arguments? 6435 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns, 6436 StdNamespaceIsAssociated); 6437 6438 // Erase all of the candidates we already knew about. 6439 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 6440 CandEnd = CandidateSet.end(); 6441 Cand != CandEnd; ++Cand) 6442 if (Cand->Function) { 6443 Fns.erase(Cand->Function); 6444 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 6445 Fns.erase(FunTmpl); 6446 } 6447 6448 // For each of the ADL candidates we found, add it to the overload 6449 // set. 6450 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 6451 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 6452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 6453 if (ExplicitTemplateArgs) 6454 continue; 6455 6456 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet, 6457 false, PartialOverloading); 6458 } else 6459 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 6460 FoundDecl, ExplicitTemplateArgs, 6461 Args, NumArgs, CandidateSet); 6462 } 6463} 6464 6465/// isBetterOverloadCandidate - Determines whether the first overload 6466/// candidate is a better candidate than the second (C++ 13.3.3p1). 6467bool 6468isBetterOverloadCandidate(Sema &S, 6469 const OverloadCandidate &Cand1, 6470 const OverloadCandidate &Cand2, 6471 SourceLocation Loc, 6472 bool UserDefinedConversion) { 6473 // Define viable functions to be better candidates than non-viable 6474 // functions. 6475 if (!Cand2.Viable) 6476 return Cand1.Viable; 6477 else if (!Cand1.Viable) 6478 return false; 6479 6480 // C++ [over.match.best]p1: 6481 // 6482 // -- if F is a static member function, ICS1(F) is defined such 6483 // that ICS1(F) is neither better nor worse than ICS1(G) for 6484 // any function G, and, symmetrically, ICS1(G) is neither 6485 // better nor worse than ICS1(F). 6486 unsigned StartArg = 0; 6487 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 6488 StartArg = 1; 6489 6490 // C++ [over.match.best]p1: 6491 // A viable function F1 is defined to be a better function than another 6492 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 6493 // conversion sequence than ICSi(F2), and then... 6494 unsigned NumArgs = Cand1.Conversions.size(); 6495 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 6496 bool HasBetterConversion = false; 6497 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 6498 switch (CompareImplicitConversionSequences(S, 6499 Cand1.Conversions[ArgIdx], 6500 Cand2.Conversions[ArgIdx])) { 6501 case ImplicitConversionSequence::Better: 6502 // Cand1 has a better conversion sequence. 6503 HasBetterConversion = true; 6504 break; 6505 6506 case ImplicitConversionSequence::Worse: 6507 // Cand1 can't be better than Cand2. 6508 return false; 6509 6510 case ImplicitConversionSequence::Indistinguishable: 6511 // Do nothing. 6512 break; 6513 } 6514 } 6515 6516 // -- for some argument j, ICSj(F1) is a better conversion sequence than 6517 // ICSj(F2), or, if not that, 6518 if (HasBetterConversion) 6519 return true; 6520 6521 // - F1 is a non-template function and F2 is a function template 6522 // specialization, or, if not that, 6523 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 6524 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 6525 return true; 6526 6527 // -- F1 and F2 are function template specializations, and the function 6528 // template for F1 is more specialized than the template for F2 6529 // according to the partial ordering rules described in 14.5.5.2, or, 6530 // if not that, 6531 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 6532 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 6533 if (FunctionTemplateDecl *BetterTemplate 6534 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 6535 Cand2.Function->getPrimaryTemplate(), 6536 Loc, 6537 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 6538 : TPOC_Call, 6539 Cand1.ExplicitCallArguments)) 6540 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 6541 } 6542 6543 // -- the context is an initialization by user-defined conversion 6544 // (see 8.5, 13.3.1.5) and the standard conversion sequence 6545 // from the return type of F1 to the destination type (i.e., 6546 // the type of the entity being initialized) is a better 6547 // conversion sequence than the standard conversion sequence 6548 // from the return type of F2 to the destination type. 6549 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 6550 isa<CXXConversionDecl>(Cand1.Function) && 6551 isa<CXXConversionDecl>(Cand2.Function)) { 6552 switch (CompareStandardConversionSequences(S, 6553 Cand1.FinalConversion, 6554 Cand2.FinalConversion)) { 6555 case ImplicitConversionSequence::Better: 6556 // Cand1 has a better conversion sequence. 6557 return true; 6558 6559 case ImplicitConversionSequence::Worse: 6560 // Cand1 can't be better than Cand2. 6561 return false; 6562 6563 case ImplicitConversionSequence::Indistinguishable: 6564 // Do nothing 6565 break; 6566 } 6567 } 6568 6569 return false; 6570} 6571 6572/// \brief Computes the best viable function (C++ 13.3.3) 6573/// within an overload candidate set. 6574/// 6575/// \param CandidateSet the set of candidate functions. 6576/// 6577/// \param Loc the location of the function name (or operator symbol) for 6578/// which overload resolution occurs. 6579/// 6580/// \param Best f overload resolution was successful or found a deleted 6581/// function, Best points to the candidate function found. 6582/// 6583/// \returns The result of overload resolution. 6584OverloadingResult 6585OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 6586 iterator &Best, 6587 bool UserDefinedConversion) { 6588 // Find the best viable function. 6589 Best = end(); 6590 for (iterator Cand = begin(); Cand != end(); ++Cand) { 6591 if (Cand->Viable) 6592 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 6593 UserDefinedConversion)) 6594 Best = Cand; 6595 } 6596 6597 // If we didn't find any viable functions, abort. 6598 if (Best == end()) 6599 return OR_No_Viable_Function; 6600 6601 // Make sure that this function is better than every other viable 6602 // function. If not, we have an ambiguity. 6603 for (iterator Cand = begin(); Cand != end(); ++Cand) { 6604 if (Cand->Viable && 6605 Cand != Best && 6606 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 6607 UserDefinedConversion)) { 6608 Best = end(); 6609 return OR_Ambiguous; 6610 } 6611 } 6612 6613 // Best is the best viable function. 6614 if (Best->Function && 6615 (Best->Function->isDeleted() || 6616 S.isFunctionConsideredUnavailable(Best->Function))) 6617 return OR_Deleted; 6618 6619 return OR_Success; 6620} 6621 6622namespace { 6623 6624enum OverloadCandidateKind { 6625 oc_function, 6626 oc_method, 6627 oc_constructor, 6628 oc_function_template, 6629 oc_method_template, 6630 oc_constructor_template, 6631 oc_implicit_default_constructor, 6632 oc_implicit_copy_constructor, 6633 oc_implicit_move_constructor, 6634 oc_implicit_copy_assignment, 6635 oc_implicit_move_assignment, 6636 oc_implicit_inherited_constructor 6637}; 6638 6639OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 6640 FunctionDecl *Fn, 6641 std::string &Description) { 6642 bool isTemplate = false; 6643 6644 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 6645 isTemplate = true; 6646 Description = S.getTemplateArgumentBindingsText( 6647 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 6648 } 6649 6650 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 6651 if (!Ctor->isImplicit()) 6652 return isTemplate ? oc_constructor_template : oc_constructor; 6653 6654 if (Ctor->getInheritedConstructor()) 6655 return oc_implicit_inherited_constructor; 6656 6657 if (Ctor->isDefaultConstructor()) 6658 return oc_implicit_default_constructor; 6659 6660 if (Ctor->isMoveConstructor()) 6661 return oc_implicit_move_constructor; 6662 6663 assert(Ctor->isCopyConstructor() && 6664 "unexpected sort of implicit constructor"); 6665 return oc_implicit_copy_constructor; 6666 } 6667 6668 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 6669 // This actually gets spelled 'candidate function' for now, but 6670 // it doesn't hurt to split it out. 6671 if (!Meth->isImplicit()) 6672 return isTemplate ? oc_method_template : oc_method; 6673 6674 if (Meth->isMoveAssignmentOperator()) 6675 return oc_implicit_move_assignment; 6676 6677 assert(Meth->isCopyAssignmentOperator() 6678 && "implicit method is not copy assignment operator?"); 6679 return oc_implicit_copy_assignment; 6680 } 6681 6682 return isTemplate ? oc_function_template : oc_function; 6683} 6684 6685void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 6686 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 6687 if (!Ctor) return; 6688 6689 Ctor = Ctor->getInheritedConstructor(); 6690 if (!Ctor) return; 6691 6692 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 6693} 6694 6695} // end anonymous namespace 6696 6697// Notes the location of an overload candidate. 6698void Sema::NoteOverloadCandidate(FunctionDecl *Fn) { 6699 std::string FnDesc; 6700 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 6701 Diag(Fn->getLocation(), diag::note_ovl_candidate) 6702 << (unsigned) K << FnDesc; 6703 MaybeEmitInheritedConstructorNote(*this, Fn); 6704} 6705 6706//Notes the location of all overload candidates designated through 6707// OverloadedExpr 6708void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) { 6709 assert(OverloadedExpr->getType() == Context.OverloadTy); 6710 6711 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 6712 OverloadExpr *OvlExpr = Ovl.Expression; 6713 6714 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6715 IEnd = OvlExpr->decls_end(); 6716 I != IEnd; ++I) { 6717 if (FunctionTemplateDecl *FunTmpl = 6718 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 6719 NoteOverloadCandidate(FunTmpl->getTemplatedDecl()); 6720 } else if (FunctionDecl *Fun 6721 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 6722 NoteOverloadCandidate(Fun); 6723 } 6724 } 6725} 6726 6727/// Diagnoses an ambiguous conversion. The partial diagnostic is the 6728/// "lead" diagnostic; it will be given two arguments, the source and 6729/// target types of the conversion. 6730void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 6731 Sema &S, 6732 SourceLocation CaretLoc, 6733 const PartialDiagnostic &PDiag) const { 6734 S.Diag(CaretLoc, PDiag) 6735 << Ambiguous.getFromType() << Ambiguous.getToType(); 6736 for (AmbiguousConversionSequence::const_iterator 6737 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 6738 S.NoteOverloadCandidate(*I); 6739 } 6740} 6741 6742namespace { 6743 6744void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 6745 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 6746 assert(Conv.isBad()); 6747 assert(Cand->Function && "for now, candidate must be a function"); 6748 FunctionDecl *Fn = Cand->Function; 6749 6750 // There's a conversion slot for the object argument if this is a 6751 // non-constructor method. Note that 'I' corresponds the 6752 // conversion-slot index. 6753 bool isObjectArgument = false; 6754 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 6755 if (I == 0) 6756 isObjectArgument = true; 6757 else 6758 I--; 6759 } 6760 6761 std::string FnDesc; 6762 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 6763 6764 Expr *FromExpr = Conv.Bad.FromExpr; 6765 QualType FromTy = Conv.Bad.getFromType(); 6766 QualType ToTy = Conv.Bad.getToType(); 6767 6768 if (FromTy == S.Context.OverloadTy) { 6769 assert(FromExpr && "overload set argument came from implicit argument?"); 6770 Expr *E = FromExpr->IgnoreParens(); 6771 if (isa<UnaryOperator>(E)) 6772 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 6773 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 6774 6775 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 6776 << (unsigned) FnKind << FnDesc 6777 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6778 << ToTy << Name << I+1; 6779 MaybeEmitInheritedConstructorNote(S, Fn); 6780 return; 6781 } 6782 6783 // Do some hand-waving analysis to see if the non-viability is due 6784 // to a qualifier mismatch. 6785 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 6786 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 6787 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 6788 CToTy = RT->getPointeeType(); 6789 else { 6790 // TODO: detect and diagnose the full richness of const mismatches. 6791 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 6792 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 6793 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 6794 } 6795 6796 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 6797 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 6798 // It is dumb that we have to do this here. 6799 while (isa<ArrayType>(CFromTy)) 6800 CFromTy = CFromTy->getAs<ArrayType>()->getElementType(); 6801 while (isa<ArrayType>(CToTy)) 6802 CToTy = CFromTy->getAs<ArrayType>()->getElementType(); 6803 6804 Qualifiers FromQs = CFromTy.getQualifiers(); 6805 Qualifiers ToQs = CToTy.getQualifiers(); 6806 6807 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 6808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 6809 << (unsigned) FnKind << FnDesc 6810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6811 << FromTy 6812 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 6813 << (unsigned) isObjectArgument << I+1; 6814 MaybeEmitInheritedConstructorNote(S, Fn); 6815 return; 6816 } 6817 6818 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 6819 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 6820 << (unsigned) FnKind << FnDesc 6821 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6822 << FromTy 6823 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 6824 << (unsigned) isObjectArgument << I+1; 6825 MaybeEmitInheritedConstructorNote(S, Fn); 6826 return; 6827 } 6828 6829 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 6830 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 6831 << (unsigned) FnKind << FnDesc 6832 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6833 << FromTy 6834 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 6835 << (unsigned) isObjectArgument << I+1; 6836 MaybeEmitInheritedConstructorNote(S, Fn); 6837 return; 6838 } 6839 6840 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 6841 assert(CVR && "unexpected qualifiers mismatch"); 6842 6843 if (isObjectArgument) { 6844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 6845 << (unsigned) FnKind << FnDesc 6846 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6847 << FromTy << (CVR - 1); 6848 } else { 6849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 6850 << (unsigned) FnKind << FnDesc 6851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6852 << FromTy << (CVR - 1) << I+1; 6853 } 6854 MaybeEmitInheritedConstructorNote(S, Fn); 6855 return; 6856 } 6857 6858 // Diagnose references or pointers to incomplete types differently, 6859 // since it's far from impossible that the incompleteness triggered 6860 // the failure. 6861 QualType TempFromTy = FromTy.getNonReferenceType(); 6862 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 6863 TempFromTy = PTy->getPointeeType(); 6864 if (TempFromTy->isIncompleteType()) { 6865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 6866 << (unsigned) FnKind << FnDesc 6867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6868 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 6869 MaybeEmitInheritedConstructorNote(S, Fn); 6870 return; 6871 } 6872 6873 // Diagnose base -> derived pointer conversions. 6874 unsigned BaseToDerivedConversion = 0; 6875 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 6876 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 6877 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 6878 FromPtrTy->getPointeeType()) && 6879 !FromPtrTy->getPointeeType()->isIncompleteType() && 6880 !ToPtrTy->getPointeeType()->isIncompleteType() && 6881 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 6882 FromPtrTy->getPointeeType())) 6883 BaseToDerivedConversion = 1; 6884 } 6885 } else if (const ObjCObjectPointerType *FromPtrTy 6886 = FromTy->getAs<ObjCObjectPointerType>()) { 6887 if (const ObjCObjectPointerType *ToPtrTy 6888 = ToTy->getAs<ObjCObjectPointerType>()) 6889 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 6890 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 6891 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 6892 FromPtrTy->getPointeeType()) && 6893 FromIface->isSuperClassOf(ToIface)) 6894 BaseToDerivedConversion = 2; 6895 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 6896 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 6897 !FromTy->isIncompleteType() && 6898 !ToRefTy->getPointeeType()->isIncompleteType() && 6899 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 6900 BaseToDerivedConversion = 3; 6901 } 6902 6903 if (BaseToDerivedConversion) { 6904 S.Diag(Fn->getLocation(), 6905 diag::note_ovl_candidate_bad_base_to_derived_conv) 6906 << (unsigned) FnKind << FnDesc 6907 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6908 << (BaseToDerivedConversion - 1) 6909 << FromTy << ToTy << I+1; 6910 MaybeEmitInheritedConstructorNote(S, Fn); 6911 return; 6912 } 6913 6914 if (isa<ObjCObjectPointerType>(CFromTy) && 6915 isa<PointerType>(CToTy)) { 6916 Qualifiers FromQs = CFromTy.getQualifiers(); 6917 Qualifiers ToQs = CToTy.getQualifiers(); 6918 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 6919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 6920 << (unsigned) FnKind << FnDesc 6921 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6922 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 6923 MaybeEmitInheritedConstructorNote(S, Fn); 6924 return; 6925 } 6926 } 6927 6928 // Emit the generic diagnostic and, optionally, add the hints to it. 6929 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 6930 FDiag << (unsigned) FnKind << FnDesc 6931 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6932 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 6933 << (unsigned) (Cand->Fix.Kind); 6934 6935 // If we can fix the conversion, suggest the FixIts. 6936 for (SmallVector<FixItHint, 1>::iterator 6937 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end(); 6938 HI != HE; ++HI) 6939 FDiag << *HI; 6940 S.Diag(Fn->getLocation(), FDiag); 6941 6942 MaybeEmitInheritedConstructorNote(S, Fn); 6943} 6944 6945void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 6946 unsigned NumFormalArgs) { 6947 // TODO: treat calls to a missing default constructor as a special case 6948 6949 FunctionDecl *Fn = Cand->Function; 6950 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 6951 6952 unsigned MinParams = Fn->getMinRequiredArguments(); 6953 6954 // With invalid overloaded operators, it's possible that we think we 6955 // have an arity mismatch when it fact it looks like we have the 6956 // right number of arguments, because only overloaded operators have 6957 // the weird behavior of overloading member and non-member functions. 6958 // Just don't report anything. 6959 if (Fn->isInvalidDecl() && 6960 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 6961 return; 6962 6963 // at least / at most / exactly 6964 unsigned mode, modeCount; 6965 if (NumFormalArgs < MinParams) { 6966 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 6967 (Cand->FailureKind == ovl_fail_bad_deduction && 6968 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 6969 if (MinParams != FnTy->getNumArgs() || 6970 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 6971 mode = 0; // "at least" 6972 else 6973 mode = 2; // "exactly" 6974 modeCount = MinParams; 6975 } else { 6976 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 6977 (Cand->FailureKind == ovl_fail_bad_deduction && 6978 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 6979 if (MinParams != FnTy->getNumArgs()) 6980 mode = 1; // "at most" 6981 else 6982 mode = 2; // "exactly" 6983 modeCount = FnTy->getNumArgs(); 6984 } 6985 6986 std::string Description; 6987 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 6988 6989 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 6990 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 6991 << modeCount << NumFormalArgs; 6992 MaybeEmitInheritedConstructorNote(S, Fn); 6993} 6994 6995/// Diagnose a failed template-argument deduction. 6996void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 6997 Expr **Args, unsigned NumArgs) { 6998 FunctionDecl *Fn = Cand->Function; // pattern 6999 7000 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 7001 NamedDecl *ParamD; 7002 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 7003 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 7004 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 7005 switch (Cand->DeductionFailure.Result) { 7006 case Sema::TDK_Success: 7007 llvm_unreachable("TDK_success while diagnosing bad deduction"); 7008 7009 case Sema::TDK_Incomplete: { 7010 assert(ParamD && "no parameter found for incomplete deduction result"); 7011 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 7012 << ParamD->getDeclName(); 7013 MaybeEmitInheritedConstructorNote(S, Fn); 7014 return; 7015 } 7016 7017 case Sema::TDK_Underqualified: { 7018 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 7019 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 7020 7021 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 7022 7023 // Param will have been canonicalized, but it should just be a 7024 // qualified version of ParamD, so move the qualifiers to that. 7025 QualifierCollector Qs; 7026 Qs.strip(Param); 7027 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 7028 assert(S.Context.hasSameType(Param, NonCanonParam)); 7029 7030 // Arg has also been canonicalized, but there's nothing we can do 7031 // about that. It also doesn't matter as much, because it won't 7032 // have any template parameters in it (because deduction isn't 7033 // done on dependent types). 7034 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 7035 7036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 7037 << ParamD->getDeclName() << Arg << NonCanonParam; 7038 MaybeEmitInheritedConstructorNote(S, Fn); 7039 return; 7040 } 7041 7042 case Sema::TDK_Inconsistent: { 7043 assert(ParamD && "no parameter found for inconsistent deduction result"); 7044 int which = 0; 7045 if (isa<TemplateTypeParmDecl>(ParamD)) 7046 which = 0; 7047 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 7048 which = 1; 7049 else { 7050 which = 2; 7051 } 7052 7053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 7054 << which << ParamD->getDeclName() 7055 << *Cand->DeductionFailure.getFirstArg() 7056 << *Cand->DeductionFailure.getSecondArg(); 7057 MaybeEmitInheritedConstructorNote(S, Fn); 7058 return; 7059 } 7060 7061 case Sema::TDK_InvalidExplicitArguments: 7062 assert(ParamD && "no parameter found for invalid explicit arguments"); 7063 if (ParamD->getDeclName()) 7064 S.Diag(Fn->getLocation(), 7065 diag::note_ovl_candidate_explicit_arg_mismatch_named) 7066 << ParamD->getDeclName(); 7067 else { 7068 int index = 0; 7069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 7070 index = TTP->getIndex(); 7071 else if (NonTypeTemplateParmDecl *NTTP 7072 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 7073 index = NTTP->getIndex(); 7074 else 7075 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 7076 S.Diag(Fn->getLocation(), 7077 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 7078 << (index + 1); 7079 } 7080 MaybeEmitInheritedConstructorNote(S, Fn); 7081 return; 7082 7083 case Sema::TDK_TooManyArguments: 7084 case Sema::TDK_TooFewArguments: 7085 DiagnoseArityMismatch(S, Cand, NumArgs); 7086 return; 7087 7088 case Sema::TDK_InstantiationDepth: 7089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 7090 MaybeEmitInheritedConstructorNote(S, Fn); 7091 return; 7092 7093 case Sema::TDK_SubstitutionFailure: { 7094 std::string ArgString; 7095 if (TemplateArgumentList *Args 7096 = Cand->DeductionFailure.getTemplateArgumentList()) 7097 ArgString = S.getTemplateArgumentBindingsText( 7098 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), 7099 *Args); 7100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 7101 << ArgString; 7102 MaybeEmitInheritedConstructorNote(S, Fn); 7103 return; 7104 } 7105 7106 // TODO: diagnose these individually, then kill off 7107 // note_ovl_candidate_bad_deduction, which is uselessly vague. 7108 case Sema::TDK_NonDeducedMismatch: 7109 case Sema::TDK_FailedOverloadResolution: 7110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 7111 MaybeEmitInheritedConstructorNote(S, Fn); 7112 return; 7113 } 7114} 7115 7116/// Generates a 'note' diagnostic for an overload candidate. We've 7117/// already generated a primary error at the call site. 7118/// 7119/// It really does need to be a single diagnostic with its caret 7120/// pointed at the candidate declaration. Yes, this creates some 7121/// major challenges of technical writing. Yes, this makes pointing 7122/// out problems with specific arguments quite awkward. It's still 7123/// better than generating twenty screens of text for every failed 7124/// overload. 7125/// 7126/// It would be great to be able to express per-candidate problems 7127/// more richly for those diagnostic clients that cared, but we'd 7128/// still have to be just as careful with the default diagnostics. 7129void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 7130 Expr **Args, unsigned NumArgs) { 7131 FunctionDecl *Fn = Cand->Function; 7132 7133 // Note deleted candidates, but only if they're viable. 7134 if (Cand->Viable && (Fn->isDeleted() || 7135 S.isFunctionConsideredUnavailable(Fn))) { 7136 std::string FnDesc; 7137 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 7138 7139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 7140 << FnKind << FnDesc << Fn->isDeleted(); 7141 MaybeEmitInheritedConstructorNote(S, Fn); 7142 return; 7143 } 7144 7145 // We don't really have anything else to say about viable candidates. 7146 if (Cand->Viable) { 7147 S.NoteOverloadCandidate(Fn); 7148 return; 7149 } 7150 7151 switch (Cand->FailureKind) { 7152 case ovl_fail_too_many_arguments: 7153 case ovl_fail_too_few_arguments: 7154 return DiagnoseArityMismatch(S, Cand, NumArgs); 7155 7156 case ovl_fail_bad_deduction: 7157 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 7158 7159 case ovl_fail_trivial_conversion: 7160 case ovl_fail_bad_final_conversion: 7161 case ovl_fail_final_conversion_not_exact: 7162 return S.NoteOverloadCandidate(Fn); 7163 7164 case ovl_fail_bad_conversion: { 7165 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 7166 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 7167 if (Cand->Conversions[I].isBad()) 7168 return DiagnoseBadConversion(S, Cand, I); 7169 7170 // FIXME: this currently happens when we're called from SemaInit 7171 // when user-conversion overload fails. Figure out how to handle 7172 // those conditions and diagnose them well. 7173 return S.NoteOverloadCandidate(Fn); 7174 } 7175 } 7176} 7177 7178void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 7179 // Desugar the type of the surrogate down to a function type, 7180 // retaining as many typedefs as possible while still showing 7181 // the function type (and, therefore, its parameter types). 7182 QualType FnType = Cand->Surrogate->getConversionType(); 7183 bool isLValueReference = false; 7184 bool isRValueReference = false; 7185 bool isPointer = false; 7186 if (const LValueReferenceType *FnTypeRef = 7187 FnType->getAs<LValueReferenceType>()) { 7188 FnType = FnTypeRef->getPointeeType(); 7189 isLValueReference = true; 7190 } else if (const RValueReferenceType *FnTypeRef = 7191 FnType->getAs<RValueReferenceType>()) { 7192 FnType = FnTypeRef->getPointeeType(); 7193 isRValueReference = true; 7194 } 7195 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 7196 FnType = FnTypePtr->getPointeeType(); 7197 isPointer = true; 7198 } 7199 // Desugar down to a function type. 7200 FnType = QualType(FnType->getAs<FunctionType>(), 0); 7201 // Reconstruct the pointer/reference as appropriate. 7202 if (isPointer) FnType = S.Context.getPointerType(FnType); 7203 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 7204 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 7205 7206 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 7207 << FnType; 7208 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 7209} 7210 7211void NoteBuiltinOperatorCandidate(Sema &S, 7212 const char *Opc, 7213 SourceLocation OpLoc, 7214 OverloadCandidate *Cand) { 7215 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 7216 std::string TypeStr("operator"); 7217 TypeStr += Opc; 7218 TypeStr += "("; 7219 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 7220 if (Cand->Conversions.size() == 1) { 7221 TypeStr += ")"; 7222 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 7223 } else { 7224 TypeStr += ", "; 7225 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 7226 TypeStr += ")"; 7227 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 7228 } 7229} 7230 7231void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 7232 OverloadCandidate *Cand) { 7233 unsigned NoOperands = Cand->Conversions.size(); 7234 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 7235 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 7236 if (ICS.isBad()) break; // all meaningless after first invalid 7237 if (!ICS.isAmbiguous()) continue; 7238 7239 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 7240 S.PDiag(diag::note_ambiguous_type_conversion)); 7241 } 7242} 7243 7244SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 7245 if (Cand->Function) 7246 return Cand->Function->getLocation(); 7247 if (Cand->IsSurrogate) 7248 return Cand->Surrogate->getLocation(); 7249 return SourceLocation(); 7250} 7251 7252struct CompareOverloadCandidatesForDisplay { 7253 Sema &S; 7254 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 7255 7256 bool operator()(const OverloadCandidate *L, 7257 const OverloadCandidate *R) { 7258 // Fast-path this check. 7259 if (L == R) return false; 7260 7261 // Order first by viability. 7262 if (L->Viable) { 7263 if (!R->Viable) return true; 7264 7265 // TODO: introduce a tri-valued comparison for overload 7266 // candidates. Would be more worthwhile if we had a sort 7267 // that could exploit it. 7268 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 7269 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 7270 } else if (R->Viable) 7271 return false; 7272 7273 assert(L->Viable == R->Viable); 7274 7275 // Criteria by which we can sort non-viable candidates: 7276 if (!L->Viable) { 7277 // 1. Arity mismatches come after other candidates. 7278 if (L->FailureKind == ovl_fail_too_many_arguments || 7279 L->FailureKind == ovl_fail_too_few_arguments) 7280 return false; 7281 if (R->FailureKind == ovl_fail_too_many_arguments || 7282 R->FailureKind == ovl_fail_too_few_arguments) 7283 return true; 7284 7285 // 2. Bad conversions come first and are ordered by the number 7286 // of bad conversions and quality of good conversions. 7287 if (L->FailureKind == ovl_fail_bad_conversion) { 7288 if (R->FailureKind != ovl_fail_bad_conversion) 7289 return true; 7290 7291 // The conversion that can be fixed with a smaller number of changes, 7292 // comes first. 7293 unsigned numLFixes = L->Fix.NumConversionsFixed; 7294 unsigned numRFixes = R->Fix.NumConversionsFixed; 7295 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 7296 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 7297 if (numLFixes != numRFixes) { 7298 if (numLFixes < numRFixes) 7299 return true; 7300 else 7301 return false; 7302 } 7303 7304 // If there's any ordering between the defined conversions... 7305 // FIXME: this might not be transitive. 7306 assert(L->Conversions.size() == R->Conversions.size()); 7307 7308 int leftBetter = 0; 7309 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 7310 for (unsigned E = L->Conversions.size(); I != E; ++I) { 7311 switch (CompareImplicitConversionSequences(S, 7312 L->Conversions[I], 7313 R->Conversions[I])) { 7314 case ImplicitConversionSequence::Better: 7315 leftBetter++; 7316 break; 7317 7318 case ImplicitConversionSequence::Worse: 7319 leftBetter--; 7320 break; 7321 7322 case ImplicitConversionSequence::Indistinguishable: 7323 break; 7324 } 7325 } 7326 if (leftBetter > 0) return true; 7327 if (leftBetter < 0) return false; 7328 7329 } else if (R->FailureKind == ovl_fail_bad_conversion) 7330 return false; 7331 7332 // TODO: others? 7333 } 7334 7335 // Sort everything else by location. 7336 SourceLocation LLoc = GetLocationForCandidate(L); 7337 SourceLocation RLoc = GetLocationForCandidate(R); 7338 7339 // Put candidates without locations (e.g. builtins) at the end. 7340 if (LLoc.isInvalid()) return false; 7341 if (RLoc.isInvalid()) return true; 7342 7343 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 7344 } 7345}; 7346 7347/// CompleteNonViableCandidate - Normally, overload resolution only 7348/// computes up to the first. Produces the FixIt set if possible. 7349void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 7350 Expr **Args, unsigned NumArgs) { 7351 assert(!Cand->Viable); 7352 7353 // Don't do anything on failures other than bad conversion. 7354 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 7355 7356 // We only want the FixIts if all the arguments can be corrected. 7357 bool Unfixable = false; 7358 // Use a implicit copy initialization to check conversion fixes. 7359 Cand->Fix.setConversionChecker(TryCopyInitialization); 7360 7361 // Skip forward to the first bad conversion. 7362 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 7363 unsigned ConvCount = Cand->Conversions.size(); 7364 while (true) { 7365 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 7366 ConvIdx++; 7367 if (Cand->Conversions[ConvIdx - 1].isBad()) { 7368 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 7369 break; 7370 } 7371 } 7372 7373 if (ConvIdx == ConvCount) 7374 return; 7375 7376 assert(!Cand->Conversions[ConvIdx].isInitialized() && 7377 "remaining conversion is initialized?"); 7378 7379 // FIXME: this should probably be preserved from the overload 7380 // operation somehow. 7381 bool SuppressUserConversions = false; 7382 7383 const FunctionProtoType* Proto; 7384 unsigned ArgIdx = ConvIdx; 7385 7386 if (Cand->IsSurrogate) { 7387 QualType ConvType 7388 = Cand->Surrogate->getConversionType().getNonReferenceType(); 7389 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 7390 ConvType = ConvPtrType->getPointeeType(); 7391 Proto = ConvType->getAs<FunctionProtoType>(); 7392 ArgIdx--; 7393 } else if (Cand->Function) { 7394 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 7395 if (isa<CXXMethodDecl>(Cand->Function) && 7396 !isa<CXXConstructorDecl>(Cand->Function)) 7397 ArgIdx--; 7398 } else { 7399 // Builtin binary operator with a bad first conversion. 7400 assert(ConvCount <= 3); 7401 for (; ConvIdx != ConvCount; ++ConvIdx) 7402 Cand->Conversions[ConvIdx] 7403 = TryCopyInitialization(S, Args[ConvIdx], 7404 Cand->BuiltinTypes.ParamTypes[ConvIdx], 7405 SuppressUserConversions, 7406 /*InOverloadResolution*/ true, 7407 /*AllowObjCWritebackConversion=*/ 7408 S.getLangOptions().ObjCAutoRefCount); 7409 return; 7410 } 7411 7412 // Fill in the rest of the conversions. 7413 unsigned NumArgsInProto = Proto->getNumArgs(); 7414 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 7415 if (ArgIdx < NumArgsInProto) { 7416 Cand->Conversions[ConvIdx] 7417 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 7418 SuppressUserConversions, 7419 /*InOverloadResolution=*/true, 7420 /*AllowObjCWritebackConversion=*/ 7421 S.getLangOptions().ObjCAutoRefCount); 7422 // Store the FixIt in the candidate if it exists. 7423 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 7424 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 7425 } 7426 else 7427 Cand->Conversions[ConvIdx].setEllipsis(); 7428 } 7429} 7430 7431} // end anonymous namespace 7432 7433/// PrintOverloadCandidates - When overload resolution fails, prints 7434/// diagnostic messages containing the candidates in the candidate 7435/// set. 7436void OverloadCandidateSet::NoteCandidates(Sema &S, 7437 OverloadCandidateDisplayKind OCD, 7438 Expr **Args, unsigned NumArgs, 7439 const char *Opc, 7440 SourceLocation OpLoc) { 7441 // Sort the candidates by viability and position. Sorting directly would 7442 // be prohibitive, so we make a set of pointers and sort those. 7443 SmallVector<OverloadCandidate*, 32> Cands; 7444 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 7445 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 7446 if (Cand->Viable) 7447 Cands.push_back(Cand); 7448 else if (OCD == OCD_AllCandidates) { 7449 CompleteNonViableCandidate(S, Cand, Args, NumArgs); 7450 if (Cand->Function || Cand->IsSurrogate) 7451 Cands.push_back(Cand); 7452 // Otherwise, this a non-viable builtin candidate. We do not, in general, 7453 // want to list every possible builtin candidate. 7454 } 7455 } 7456 7457 std::sort(Cands.begin(), Cands.end(), 7458 CompareOverloadCandidatesForDisplay(S)); 7459 7460 bool ReportedAmbiguousConversions = false; 7461 7462 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 7463 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 7464 unsigned CandsShown = 0; 7465 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 7466 OverloadCandidate *Cand = *I; 7467 7468 // Set an arbitrary limit on the number of candidate functions we'll spam 7469 // the user with. FIXME: This limit should depend on details of the 7470 // candidate list. 7471 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) { 7472 break; 7473 } 7474 ++CandsShown; 7475 7476 if (Cand->Function) 7477 NoteFunctionCandidate(S, Cand, Args, NumArgs); 7478 else if (Cand->IsSurrogate) 7479 NoteSurrogateCandidate(S, Cand); 7480 else { 7481 assert(Cand->Viable && 7482 "Non-viable built-in candidates are not added to Cands."); 7483 // Generally we only see ambiguities including viable builtin 7484 // operators if overload resolution got screwed up by an 7485 // ambiguous user-defined conversion. 7486 // 7487 // FIXME: It's quite possible for different conversions to see 7488 // different ambiguities, though. 7489 if (!ReportedAmbiguousConversions) { 7490 NoteAmbiguousUserConversions(S, OpLoc, Cand); 7491 ReportedAmbiguousConversions = true; 7492 } 7493 7494 // If this is a viable builtin, print it. 7495 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 7496 } 7497 } 7498 7499 if (I != E) 7500 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 7501} 7502 7503// [PossiblyAFunctionType] --> [Return] 7504// NonFunctionType --> NonFunctionType 7505// R (A) --> R(A) 7506// R (*)(A) --> R (A) 7507// R (&)(A) --> R (A) 7508// R (S::*)(A) --> R (A) 7509QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 7510 QualType Ret = PossiblyAFunctionType; 7511 if (const PointerType *ToTypePtr = 7512 PossiblyAFunctionType->getAs<PointerType>()) 7513 Ret = ToTypePtr->getPointeeType(); 7514 else if (const ReferenceType *ToTypeRef = 7515 PossiblyAFunctionType->getAs<ReferenceType>()) 7516 Ret = ToTypeRef->getPointeeType(); 7517 else if (const MemberPointerType *MemTypePtr = 7518 PossiblyAFunctionType->getAs<MemberPointerType>()) 7519 Ret = MemTypePtr->getPointeeType(); 7520 Ret = 7521 Context.getCanonicalType(Ret).getUnqualifiedType(); 7522 return Ret; 7523} 7524 7525// A helper class to help with address of function resolution 7526// - allows us to avoid passing around all those ugly parameters 7527class AddressOfFunctionResolver 7528{ 7529 Sema& S; 7530 Expr* SourceExpr; 7531 const QualType& TargetType; 7532 QualType TargetFunctionType; // Extracted function type from target type 7533 7534 bool Complain; 7535 //DeclAccessPair& ResultFunctionAccessPair; 7536 ASTContext& Context; 7537 7538 bool TargetTypeIsNonStaticMemberFunction; 7539 bool FoundNonTemplateFunction; 7540 7541 OverloadExpr::FindResult OvlExprInfo; 7542 OverloadExpr *OvlExpr; 7543 TemplateArgumentListInfo OvlExplicitTemplateArgs; 7544 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 7545 7546public: 7547 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 7548 const QualType& TargetType, bool Complain) 7549 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 7550 Complain(Complain), Context(S.getASTContext()), 7551 TargetTypeIsNonStaticMemberFunction( 7552 !!TargetType->getAs<MemberPointerType>()), 7553 FoundNonTemplateFunction(false), 7554 OvlExprInfo(OverloadExpr::find(SourceExpr)), 7555 OvlExpr(OvlExprInfo.Expression) 7556 { 7557 ExtractUnqualifiedFunctionTypeFromTargetType(); 7558 7559 if (!TargetFunctionType->isFunctionType()) { 7560 if (OvlExpr->hasExplicitTemplateArgs()) { 7561 DeclAccessPair dap; 7562 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 7563 OvlExpr, false, &dap) ) { 7564 7565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7566 if (!Method->isStatic()) { 7567 // If the target type is a non-function type and the function 7568 // found is a non-static member function, pretend as if that was 7569 // the target, it's the only possible type to end up with. 7570 TargetTypeIsNonStaticMemberFunction = true; 7571 7572 // And skip adding the function if its not in the proper form. 7573 // We'll diagnose this due to an empty set of functions. 7574 if (!OvlExprInfo.HasFormOfMemberPointer) 7575 return; 7576 } 7577 } 7578 7579 Matches.push_back(std::make_pair(dap,Fn)); 7580 } 7581 } 7582 return; 7583 } 7584 7585 if (OvlExpr->hasExplicitTemplateArgs()) 7586 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 7587 7588 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 7589 // C++ [over.over]p4: 7590 // If more than one function is selected, [...] 7591 if (Matches.size() > 1) { 7592 if (FoundNonTemplateFunction) 7593 EliminateAllTemplateMatches(); 7594 else 7595 EliminateAllExceptMostSpecializedTemplate(); 7596 } 7597 } 7598 } 7599 7600private: 7601 bool isTargetTypeAFunction() const { 7602 return TargetFunctionType->isFunctionType(); 7603 } 7604 7605 // [ToType] [Return] 7606 7607 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 7608 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 7609 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 7610 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 7611 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 7612 } 7613 7614 // return true if any matching specializations were found 7615 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 7616 const DeclAccessPair& CurAccessFunPair) { 7617 if (CXXMethodDecl *Method 7618 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 7619 // Skip non-static function templates when converting to pointer, and 7620 // static when converting to member pointer. 7621 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 7622 return false; 7623 } 7624 else if (TargetTypeIsNonStaticMemberFunction) 7625 return false; 7626 7627 // C++ [over.over]p2: 7628 // If the name is a function template, template argument deduction is 7629 // done (14.8.2.2), and if the argument deduction succeeds, the 7630 // resulting template argument list is used to generate a single 7631 // function template specialization, which is added to the set of 7632 // overloaded functions considered. 7633 FunctionDecl *Specialization = 0; 7634 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 7635 if (Sema::TemplateDeductionResult Result 7636 = S.DeduceTemplateArguments(FunctionTemplate, 7637 &OvlExplicitTemplateArgs, 7638 TargetFunctionType, Specialization, 7639 Info)) { 7640 // FIXME: make a note of the failed deduction for diagnostics. 7641 (void)Result; 7642 return false; 7643 } 7644 7645 // Template argument deduction ensures that we have an exact match. 7646 // This function template specicalization works. 7647 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 7648 assert(TargetFunctionType 7649 == Context.getCanonicalType(Specialization->getType())); 7650 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 7651 return true; 7652 } 7653 7654 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 7655 const DeclAccessPair& CurAccessFunPair) { 7656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7657 // Skip non-static functions when converting to pointer, and static 7658 // when converting to member pointer. 7659 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 7660 return false; 7661 } 7662 else if (TargetTypeIsNonStaticMemberFunction) 7663 return false; 7664 7665 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 7666 QualType ResultTy; 7667 if (Context.hasSameUnqualifiedType(TargetFunctionType, 7668 FunDecl->getType()) || 7669 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 7670 ResultTy)) { 7671 Matches.push_back(std::make_pair(CurAccessFunPair, 7672 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 7673 FoundNonTemplateFunction = true; 7674 return true; 7675 } 7676 } 7677 7678 return false; 7679 } 7680 7681 bool FindAllFunctionsThatMatchTargetTypeExactly() { 7682 bool Ret = false; 7683 7684 // If the overload expression doesn't have the form of a pointer to 7685 // member, don't try to convert it to a pointer-to-member type. 7686 if (IsInvalidFormOfPointerToMemberFunction()) 7687 return false; 7688 7689 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7690 E = OvlExpr->decls_end(); 7691 I != E; ++I) { 7692 // Look through any using declarations to find the underlying function. 7693 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 7694 7695 // C++ [over.over]p3: 7696 // Non-member functions and static member functions match 7697 // targets of type "pointer-to-function" or "reference-to-function." 7698 // Nonstatic member functions match targets of 7699 // type "pointer-to-member-function." 7700 // Note that according to DR 247, the containing class does not matter. 7701 if (FunctionTemplateDecl *FunctionTemplate 7702 = dyn_cast<FunctionTemplateDecl>(Fn)) { 7703 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 7704 Ret = true; 7705 } 7706 // If we have explicit template arguments supplied, skip non-templates. 7707 else if (!OvlExpr->hasExplicitTemplateArgs() && 7708 AddMatchingNonTemplateFunction(Fn, I.getPair())) 7709 Ret = true; 7710 } 7711 assert(Ret || Matches.empty()); 7712 return Ret; 7713 } 7714 7715 void EliminateAllExceptMostSpecializedTemplate() { 7716 // [...] and any given function template specialization F1 is 7717 // eliminated if the set contains a second function template 7718 // specialization whose function template is more specialized 7719 // than the function template of F1 according to the partial 7720 // ordering rules of 14.5.5.2. 7721 7722 // The algorithm specified above is quadratic. We instead use a 7723 // two-pass algorithm (similar to the one used to identify the 7724 // best viable function in an overload set) that identifies the 7725 // best function template (if it exists). 7726 7727 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 7728 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 7729 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 7730 7731 UnresolvedSetIterator Result = 7732 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 7733 TPOC_Other, 0, SourceExpr->getLocStart(), 7734 S.PDiag(), 7735 S.PDiag(diag::err_addr_ovl_ambiguous) 7736 << Matches[0].second->getDeclName(), 7737 S.PDiag(diag::note_ovl_candidate) 7738 << (unsigned) oc_function_template, 7739 Complain); 7740 7741 if (Result != MatchesCopy.end()) { 7742 // Make it the first and only element 7743 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 7744 Matches[0].second = cast<FunctionDecl>(*Result); 7745 Matches.resize(1); 7746 } 7747 } 7748 7749 void EliminateAllTemplateMatches() { 7750 // [...] any function template specializations in the set are 7751 // eliminated if the set also contains a non-template function, [...] 7752 for (unsigned I = 0, N = Matches.size(); I != N; ) { 7753 if (Matches[I].second->getPrimaryTemplate() == 0) 7754 ++I; 7755 else { 7756 Matches[I] = Matches[--N]; 7757 Matches.set_size(N); 7758 } 7759 } 7760 } 7761 7762public: 7763 void ComplainNoMatchesFound() const { 7764 assert(Matches.empty()); 7765 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 7766 << OvlExpr->getName() << TargetFunctionType 7767 << OvlExpr->getSourceRange(); 7768 S.NoteAllOverloadCandidates(OvlExpr); 7769 } 7770 7771 bool IsInvalidFormOfPointerToMemberFunction() const { 7772 return TargetTypeIsNonStaticMemberFunction && 7773 !OvlExprInfo.HasFormOfMemberPointer; 7774 } 7775 7776 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 7777 // TODO: Should we condition this on whether any functions might 7778 // have matched, or is it more appropriate to do that in callers? 7779 // TODO: a fixit wouldn't hurt. 7780 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 7781 << TargetType << OvlExpr->getSourceRange(); 7782 } 7783 7784 void ComplainOfInvalidConversion() const { 7785 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 7786 << OvlExpr->getName() << TargetType; 7787 } 7788 7789 void ComplainMultipleMatchesFound() const { 7790 assert(Matches.size() > 1); 7791 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 7792 << OvlExpr->getName() 7793 << OvlExpr->getSourceRange(); 7794 S.NoteAllOverloadCandidates(OvlExpr); 7795 } 7796 7797 int getNumMatches() const { return Matches.size(); } 7798 7799 FunctionDecl* getMatchingFunctionDecl() const { 7800 if (Matches.size() != 1) return 0; 7801 return Matches[0].second; 7802 } 7803 7804 const DeclAccessPair* getMatchingFunctionAccessPair() const { 7805 if (Matches.size() != 1) return 0; 7806 return &Matches[0].first; 7807 } 7808}; 7809 7810/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 7811/// an overloaded function (C++ [over.over]), where @p From is an 7812/// expression with overloaded function type and @p ToType is the type 7813/// we're trying to resolve to. For example: 7814/// 7815/// @code 7816/// int f(double); 7817/// int f(int); 7818/// 7819/// int (*pfd)(double) = f; // selects f(double) 7820/// @endcode 7821/// 7822/// This routine returns the resulting FunctionDecl if it could be 7823/// resolved, and NULL otherwise. When @p Complain is true, this 7824/// routine will emit diagnostics if there is an error. 7825FunctionDecl * 7826Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, 7827 bool Complain, 7828 DeclAccessPair &FoundResult) { 7829 7830 assert(AddressOfExpr->getType() == Context.OverloadTy); 7831 7832 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain); 7833 int NumMatches = Resolver.getNumMatches(); 7834 FunctionDecl* Fn = 0; 7835 if ( NumMatches == 0 && Complain) { 7836 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 7837 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 7838 else 7839 Resolver.ComplainNoMatchesFound(); 7840 } 7841 else if (NumMatches > 1 && Complain) 7842 Resolver.ComplainMultipleMatchesFound(); 7843 else if (NumMatches == 1) { 7844 Fn = Resolver.getMatchingFunctionDecl(); 7845 assert(Fn); 7846 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 7847 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn); 7848 if (Complain) 7849 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 7850 } 7851 7852 return Fn; 7853} 7854 7855/// \brief Given an expression that refers to an overloaded function, try to 7856/// resolve that overloaded function expression down to a single function. 7857/// 7858/// This routine can only resolve template-ids that refer to a single function 7859/// template, where that template-id refers to a single template whose template 7860/// arguments are either provided by the template-id or have defaults, 7861/// as described in C++0x [temp.arg.explicit]p3. 7862FunctionDecl * 7863Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 7864 bool Complain, 7865 DeclAccessPair *FoundResult) { 7866 // C++ [over.over]p1: 7867 // [...] [Note: any redundant set of parentheses surrounding the 7868 // overloaded function name is ignored (5.1). ] 7869 // C++ [over.over]p1: 7870 // [...] The overloaded function name can be preceded by the & 7871 // operator. 7872 7873 // If we didn't actually find any template-ids, we're done. 7874 if (!ovl->hasExplicitTemplateArgs()) 7875 return 0; 7876 7877 TemplateArgumentListInfo ExplicitTemplateArgs; 7878 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 7879 7880 // Look through all of the overloaded functions, searching for one 7881 // whose type matches exactly. 7882 FunctionDecl *Matched = 0; 7883 for (UnresolvedSetIterator I = ovl->decls_begin(), 7884 E = ovl->decls_end(); I != E; ++I) { 7885 // C++0x [temp.arg.explicit]p3: 7886 // [...] In contexts where deduction is done and fails, or in contexts 7887 // where deduction is not done, if a template argument list is 7888 // specified and it, along with any default template arguments, 7889 // identifies a single function template specialization, then the 7890 // template-id is an lvalue for the function template specialization. 7891 FunctionTemplateDecl *FunctionTemplate 7892 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 7893 7894 // C++ [over.over]p2: 7895 // If the name is a function template, template argument deduction is 7896 // done (14.8.2.2), and if the argument deduction succeeds, the 7897 // resulting template argument list is used to generate a single 7898 // function template specialization, which is added to the set of 7899 // overloaded functions considered. 7900 FunctionDecl *Specialization = 0; 7901 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 7902 if (TemplateDeductionResult Result 7903 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 7904 Specialization, Info)) { 7905 // FIXME: make a note of the failed deduction for diagnostics. 7906 (void)Result; 7907 continue; 7908 } 7909 7910 assert(Specialization && "no specialization and no error?"); 7911 7912 // Multiple matches; we can't resolve to a single declaration. 7913 if (Matched) { 7914 if (Complain) { 7915 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 7916 << ovl->getName(); 7917 NoteAllOverloadCandidates(ovl); 7918 } 7919 return 0; 7920 } 7921 7922 Matched = Specialization; 7923 if (FoundResult) *FoundResult = I.getPair(); 7924 } 7925 7926 return Matched; 7927} 7928 7929 7930 7931 7932// Resolve and fix an overloaded expression that 7933// can be resolved because it identifies a single function 7934// template specialization 7935// Last three arguments should only be supplied if Complain = true 7936ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 7937 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain, 7938 const SourceRange& OpRangeForComplaining, 7939 QualType DestTypeForComplaining, 7940 unsigned DiagIDForComplaining) { 7941 assert(SrcExpr->getType() == Context.OverloadTy); 7942 7943 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr); 7944 7945 DeclAccessPair found; 7946 ExprResult SingleFunctionExpression; 7947 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 7948 ovl.Expression, /*complain*/ false, &found)) { 7949 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin())) 7950 return ExprError(); 7951 7952 // It is only correct to resolve to an instance method if we're 7953 // resolving a form that's permitted to be a pointer to member. 7954 // Otherwise we'll end up making a bound member expression, which 7955 // is illegal in all the contexts we resolve like this. 7956 if (!ovl.HasFormOfMemberPointer && 7957 isa<CXXMethodDecl>(fn) && 7958 cast<CXXMethodDecl>(fn)->isInstance()) { 7959 if (complain) { 7960 Diag(ovl.Expression->getExprLoc(), 7961 diag::err_invalid_use_of_bound_member_func) 7962 << ovl.Expression->getSourceRange(); 7963 // TODO: I believe we only end up here if there's a mix of 7964 // static and non-static candidates (otherwise the expression 7965 // would have 'bound member' type, not 'overload' type). 7966 // Ideally we would note which candidate was chosen and why 7967 // the static candidates were rejected. 7968 } 7969 7970 return ExprError(); 7971 } 7972 7973 // Fix the expresion to refer to 'fn'. 7974 SingleFunctionExpression = 7975 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn)); 7976 7977 // If desired, do function-to-pointer decay. 7978 if (doFunctionPointerConverion) 7979 SingleFunctionExpression = 7980 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 7981 } 7982 7983 if (!SingleFunctionExpression.isUsable()) { 7984 if (complain) { 7985 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 7986 << ovl.Expression->getName() 7987 << DestTypeForComplaining 7988 << OpRangeForComplaining 7989 << ovl.Expression->getQualifierLoc().getSourceRange(); 7990 NoteAllOverloadCandidates(SrcExpr); 7991 } 7992 return ExprError(); 7993 } 7994 7995 return SingleFunctionExpression; 7996} 7997 7998/// \brief Add a single candidate to the overload set. 7999static void AddOverloadedCallCandidate(Sema &S, 8000 DeclAccessPair FoundDecl, 8001 TemplateArgumentListInfo *ExplicitTemplateArgs, 8002 Expr **Args, unsigned NumArgs, 8003 OverloadCandidateSet &CandidateSet, 8004 bool PartialOverloading, 8005 bool KnownValid) { 8006 NamedDecl *Callee = FoundDecl.getDecl(); 8007 if (isa<UsingShadowDecl>(Callee)) 8008 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 8009 8010 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 8011 if (ExplicitTemplateArgs) { 8012 assert(!KnownValid && "Explicit template arguments?"); 8013 return; 8014 } 8015 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 8016 false, PartialOverloading); 8017 return; 8018 } 8019 8020 if (FunctionTemplateDecl *FuncTemplate 8021 = dyn_cast<FunctionTemplateDecl>(Callee)) { 8022 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 8023 ExplicitTemplateArgs, 8024 Args, NumArgs, CandidateSet); 8025 return; 8026 } 8027 8028 assert(!KnownValid && "unhandled case in overloaded call candidate"); 8029} 8030 8031/// \brief Add the overload candidates named by callee and/or found by argument 8032/// dependent lookup to the given overload set. 8033void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 8034 Expr **Args, unsigned NumArgs, 8035 OverloadCandidateSet &CandidateSet, 8036 bool PartialOverloading) { 8037 8038#ifndef NDEBUG 8039 // Verify that ArgumentDependentLookup is consistent with the rules 8040 // in C++0x [basic.lookup.argdep]p3: 8041 // 8042 // Let X be the lookup set produced by unqualified lookup (3.4.1) 8043 // and let Y be the lookup set produced by argument dependent 8044 // lookup (defined as follows). If X contains 8045 // 8046 // -- a declaration of a class member, or 8047 // 8048 // -- a block-scope function declaration that is not a 8049 // using-declaration, or 8050 // 8051 // -- a declaration that is neither a function or a function 8052 // template 8053 // 8054 // then Y is empty. 8055 8056 if (ULE->requiresADL()) { 8057 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 8058 E = ULE->decls_end(); I != E; ++I) { 8059 assert(!(*I)->getDeclContext()->isRecord()); 8060 assert(isa<UsingShadowDecl>(*I) || 8061 !(*I)->getDeclContext()->isFunctionOrMethod()); 8062 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 8063 } 8064 } 8065#endif 8066 8067 // It would be nice to avoid this copy. 8068 TemplateArgumentListInfo TABuffer; 8069 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 8070 if (ULE->hasExplicitTemplateArgs()) { 8071 ULE->copyTemplateArgumentsInto(TABuffer); 8072 ExplicitTemplateArgs = &TABuffer; 8073 } 8074 8075 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 8076 E = ULE->decls_end(); I != E; ++I) 8077 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 8078 Args, NumArgs, CandidateSet, 8079 PartialOverloading, /*KnownValid*/ true); 8080 8081 if (ULE->requiresADL()) 8082 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 8083 Args, NumArgs, 8084 ExplicitTemplateArgs, 8085 CandidateSet, 8086 PartialOverloading, 8087 ULE->isStdAssociatedNamespace()); 8088} 8089 8090/// Attempt to recover from an ill-formed use of a non-dependent name in a 8091/// template, where the non-dependent name was declared after the template 8092/// was defined. This is common in code written for a compilers which do not 8093/// correctly implement two-stage name lookup. 8094/// 8095/// Returns true if a viable candidate was found and a diagnostic was issued. 8096static bool 8097DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 8098 const CXXScopeSpec &SS, LookupResult &R, 8099 TemplateArgumentListInfo *ExplicitTemplateArgs, 8100 Expr **Args, unsigned NumArgs) { 8101 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 8102 return false; 8103 8104 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 8105 SemaRef.LookupQualifiedName(R, DC); 8106 8107 if (!R.empty()) { 8108 R.suppressDiagnostics(); 8109 8110 if (isa<CXXRecordDecl>(DC)) { 8111 // Don't diagnose names we find in classes; we get much better 8112 // diagnostics for these from DiagnoseEmptyLookup. 8113 R.clear(); 8114 return false; 8115 } 8116 8117 OverloadCandidateSet Candidates(FnLoc); 8118 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8119 AddOverloadedCallCandidate(SemaRef, I.getPair(), 8120 ExplicitTemplateArgs, Args, NumArgs, 8121 Candidates, false, /*KnownValid*/ false); 8122 8123 OverloadCandidateSet::iterator Best; 8124 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 8125 // No viable functions. Don't bother the user with notes for functions 8126 // which don't work and shouldn't be found anyway. 8127 R.clear(); 8128 return false; 8129 } 8130 8131 // Find the namespaces where ADL would have looked, and suggest 8132 // declaring the function there instead. 8133 Sema::AssociatedNamespaceSet AssociatedNamespaces; 8134 Sema::AssociatedClassSet AssociatedClasses; 8135 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs, 8136 AssociatedNamespaces, 8137 AssociatedClasses); 8138 // Never suggest declaring a function within namespace 'std'. 8139 Sema::AssociatedNamespaceSet SuggestedNamespaces; 8140 if (DeclContext *Std = SemaRef.getStdNamespace()) { 8141 for (Sema::AssociatedNamespaceSet::iterator 8142 it = AssociatedNamespaces.begin(), 8143 end = AssociatedNamespaces.end(); it != end; ++it) { 8144 if (!Std->Encloses(*it)) 8145 SuggestedNamespaces.insert(*it); 8146 } 8147 } else { 8148 // Lacking the 'std::' namespace, use all of the associated namespaces. 8149 SuggestedNamespaces = AssociatedNamespaces; 8150 } 8151 8152 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 8153 << R.getLookupName(); 8154 if (SuggestedNamespaces.empty()) { 8155 SemaRef.Diag(Best->Function->getLocation(), 8156 diag::note_not_found_by_two_phase_lookup) 8157 << R.getLookupName() << 0; 8158 } else if (SuggestedNamespaces.size() == 1) { 8159 SemaRef.Diag(Best->Function->getLocation(), 8160 diag::note_not_found_by_two_phase_lookup) 8161 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 8162 } else { 8163 // FIXME: It would be useful to list the associated namespaces here, 8164 // but the diagnostics infrastructure doesn't provide a way to produce 8165 // a localized representation of a list of items. 8166 SemaRef.Diag(Best->Function->getLocation(), 8167 diag::note_not_found_by_two_phase_lookup) 8168 << R.getLookupName() << 2; 8169 } 8170 8171 // Try to recover by calling this function. 8172 return true; 8173 } 8174 8175 R.clear(); 8176 } 8177 8178 return false; 8179} 8180 8181/// Attempt to recover from ill-formed use of a non-dependent operator in a 8182/// template, where the non-dependent operator was declared after the template 8183/// was defined. 8184/// 8185/// Returns true if a viable candidate was found and a diagnostic was issued. 8186static bool 8187DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 8188 SourceLocation OpLoc, 8189 Expr **Args, unsigned NumArgs) { 8190 DeclarationName OpName = 8191 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 8192 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 8193 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 8194 /*ExplicitTemplateArgs=*/0, Args, NumArgs); 8195} 8196 8197/// Attempts to recover from a call where no functions were found. 8198/// 8199/// Returns true if new candidates were found. 8200static ExprResult 8201BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 8202 UnresolvedLookupExpr *ULE, 8203 SourceLocation LParenLoc, 8204 Expr **Args, unsigned NumArgs, 8205 SourceLocation RParenLoc, 8206 bool EmptyLookup) { 8207 8208 CXXScopeSpec SS; 8209 SS.Adopt(ULE->getQualifierLoc()); 8210 8211 TemplateArgumentListInfo TABuffer; 8212 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 8213 if (ULE->hasExplicitTemplateArgs()) { 8214 ULE->copyTemplateArgumentsInto(TABuffer); 8215 ExplicitTemplateArgs = &TABuffer; 8216 } 8217 8218 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 8219 Sema::LookupOrdinaryName); 8220 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 8221 ExplicitTemplateArgs, Args, NumArgs) && 8222 (!EmptyLookup || 8223 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression, 8224 ExplicitTemplateArgs, Args, NumArgs))) 8225 return ExprError(); 8226 8227 assert(!R.empty() && "lookup results empty despite recovery"); 8228 8229 // Build an implicit member call if appropriate. Just drop the 8230 // casts and such from the call, we don't really care. 8231 ExprResult NewFn = ExprError(); 8232 if ((*R.begin())->isCXXClassMember()) 8233 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, 8234 ExplicitTemplateArgs); 8235 else if (ExplicitTemplateArgs) 8236 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 8237 else 8238 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 8239 8240 if (NewFn.isInvalid()) 8241 return ExprError(); 8242 8243 // This shouldn't cause an infinite loop because we're giving it 8244 // an expression with viable lookup results, which should never 8245 // end up here. 8246 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 8247 MultiExprArg(Args, NumArgs), RParenLoc); 8248} 8249 8250/// ResolveOverloadedCallFn - Given the call expression that calls Fn 8251/// (which eventually refers to the declaration Func) and the call 8252/// arguments Args/NumArgs, attempt to resolve the function call down 8253/// to a specific function. If overload resolution succeeds, returns 8254/// the function declaration produced by overload 8255/// resolution. Otherwise, emits diagnostics, deletes all of the 8256/// arguments and Fn, and returns NULL. 8257ExprResult 8258Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 8259 SourceLocation LParenLoc, 8260 Expr **Args, unsigned NumArgs, 8261 SourceLocation RParenLoc, 8262 Expr *ExecConfig) { 8263#ifndef NDEBUG 8264 if (ULE->requiresADL()) { 8265 // To do ADL, we must have found an unqualified name. 8266 assert(!ULE->getQualifier() && "qualified name with ADL"); 8267 8268 // We don't perform ADL for implicit declarations of builtins. 8269 // Verify that this was correctly set up. 8270 FunctionDecl *F; 8271 if (ULE->decls_begin() + 1 == ULE->decls_end() && 8272 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 8273 F->getBuiltinID() && F->isImplicit()) 8274 assert(0 && "performing ADL for builtin"); 8275 8276 // We don't perform ADL in C. 8277 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 8278 } else 8279 assert(!ULE->isStdAssociatedNamespace() && 8280 "std is associated namespace but not doing ADL"); 8281#endif 8282 8283 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 8284 8285 // Add the functions denoted by the callee to the set of candidate 8286 // functions, including those from argument-dependent lookup. 8287 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 8288 8289 // If we found nothing, try to recover. 8290 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 8291 // out if it fails. 8292 if (CandidateSet.empty()) 8293 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 8294 RParenLoc, /*EmptyLookup=*/true); 8295 8296 OverloadCandidateSet::iterator Best; 8297 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) { 8298 case OR_Success: { 8299 FunctionDecl *FDecl = Best->Function; 8300 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl); 8301 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 8302 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), 8303 ULE->getNameLoc()); 8304 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 8305 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc, 8306 ExecConfig); 8307 } 8308 8309 case OR_No_Viable_Function: { 8310 // Try to recover by looking for viable functions which the user might 8311 // have meant to call. 8312 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, 8313 Args, NumArgs, RParenLoc, 8314 /*EmptyLookup=*/false); 8315 if (!Recovery.isInvalid()) 8316 return Recovery; 8317 8318 Diag(Fn->getSourceRange().getBegin(), 8319 diag::err_ovl_no_viable_function_in_call) 8320 << ULE->getName() << Fn->getSourceRange(); 8321 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8322 break; 8323 } 8324 8325 case OR_Ambiguous: 8326 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 8327 << ULE->getName() << Fn->getSourceRange(); 8328 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 8329 break; 8330 8331 case OR_Deleted: 8332 { 8333 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 8334 << Best->Function->isDeleted() 8335 << ULE->getName() 8336 << getDeletedOrUnavailableSuffix(Best->Function) 8337 << Fn->getSourceRange(); 8338 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8339 } 8340 break; 8341 } 8342 8343 // Overload resolution failed. 8344 return ExprError(); 8345} 8346 8347static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 8348 return Functions.size() > 1 || 8349 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 8350} 8351 8352/// \brief Create a unary operation that may resolve to an overloaded 8353/// operator. 8354/// 8355/// \param OpLoc The location of the operator itself (e.g., '*'). 8356/// 8357/// \param OpcIn The UnaryOperator::Opcode that describes this 8358/// operator. 8359/// 8360/// \param Functions The set of non-member functions that will be 8361/// considered by overload resolution. The caller needs to build this 8362/// set based on the context using, e.g., 8363/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 8364/// set should not contain any member functions; those will be added 8365/// by CreateOverloadedUnaryOp(). 8366/// 8367/// \param input The input argument. 8368ExprResult 8369Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 8370 const UnresolvedSetImpl &Fns, 8371 Expr *Input) { 8372 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 8373 8374 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 8375 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 8376 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8377 // TODO: provide better source location info. 8378 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 8379 8380 if (Input->getObjectKind() == OK_ObjCProperty) { 8381 ExprResult Result = ConvertPropertyForRValue(Input); 8382 if (Result.isInvalid()) 8383 return ExprError(); 8384 Input = Result.take(); 8385 } 8386 8387 Expr *Args[2] = { Input, 0 }; 8388 unsigned NumArgs = 1; 8389 8390 // For post-increment and post-decrement, add the implicit '0' as 8391 // the second argument, so that we know this is a post-increment or 8392 // post-decrement. 8393 if (Opc == UO_PostInc || Opc == UO_PostDec) { 8394 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 8395 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 8396 SourceLocation()); 8397 NumArgs = 2; 8398 } 8399 8400 if (Input->isTypeDependent()) { 8401 if (Fns.empty()) 8402 return Owned(new (Context) UnaryOperator(Input, 8403 Opc, 8404 Context.DependentTy, 8405 VK_RValue, OK_Ordinary, 8406 OpLoc)); 8407 8408 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 8409 UnresolvedLookupExpr *Fn 8410 = UnresolvedLookupExpr::Create(Context, NamingClass, 8411 NestedNameSpecifierLoc(), OpNameInfo, 8412 /*ADL*/ true, IsOverloaded(Fns), 8413 Fns.begin(), Fns.end()); 8414 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 8415 &Args[0], NumArgs, 8416 Context.DependentTy, 8417 VK_RValue, 8418 OpLoc)); 8419 } 8420 8421 // Build an empty overload set. 8422 OverloadCandidateSet CandidateSet(OpLoc); 8423 8424 // Add the candidates from the given function set. 8425 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 8426 8427 // Add operator candidates that are member functions. 8428 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 8429 8430 // Add candidates from ADL. 8431 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 8432 Args, NumArgs, 8433 /*ExplicitTemplateArgs*/ 0, 8434 CandidateSet); 8435 8436 // Add builtin operator candidates. 8437 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 8438 8439 // Perform overload resolution. 8440 OverloadCandidateSet::iterator Best; 8441 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 8442 case OR_Success: { 8443 // We found a built-in operator or an overloaded operator. 8444 FunctionDecl *FnDecl = Best->Function; 8445 8446 if (FnDecl) { 8447 // We matched an overloaded operator. Build a call to that 8448 // operator. 8449 8450 MarkDeclarationReferenced(OpLoc, FnDecl); 8451 8452 // Convert the arguments. 8453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 8454 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 8455 8456 ExprResult InputRes = 8457 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 8458 Best->FoundDecl, Method); 8459 if (InputRes.isInvalid()) 8460 return ExprError(); 8461 Input = InputRes.take(); 8462 } else { 8463 // Convert the arguments. 8464 ExprResult InputInit 8465 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 8466 Context, 8467 FnDecl->getParamDecl(0)), 8468 SourceLocation(), 8469 Input); 8470 if (InputInit.isInvalid()) 8471 return ExprError(); 8472 Input = InputInit.take(); 8473 } 8474 8475 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 8476 8477 // Determine the result type. 8478 QualType ResultTy = FnDecl->getResultType(); 8479 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8480 ResultTy = ResultTy.getNonLValueExprType(Context); 8481 8482 // Build the actual expression node. 8483 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl); 8484 if (FnExpr.isInvalid()) 8485 return ExprError(); 8486 8487 Args[0] = Input; 8488 CallExpr *TheCall = 8489 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 8490 Args, NumArgs, ResultTy, VK, OpLoc); 8491 8492 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 8493 FnDecl)) 8494 return ExprError(); 8495 8496 return MaybeBindToTemporary(TheCall); 8497 } else { 8498 // We matched a built-in operator. Convert the arguments, then 8499 // break out so that we will build the appropriate built-in 8500 // operator node. 8501 ExprResult InputRes = 8502 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 8503 Best->Conversions[0], AA_Passing); 8504 if (InputRes.isInvalid()) 8505 return ExprError(); 8506 Input = InputRes.take(); 8507 break; 8508 } 8509 } 8510 8511 case OR_No_Viable_Function: 8512 // This is an erroneous use of an operator which can be overloaded by 8513 // a non-member function. Check for non-member operators which were 8514 // defined too late to be candidates. 8515 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs)) 8516 // FIXME: Recover by calling the found function. 8517 return ExprError(); 8518 8519 // No viable function; fall through to handling this as a 8520 // built-in operator, which will produce an error message for us. 8521 break; 8522 8523 case OR_Ambiguous: 8524 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 8525 << UnaryOperator::getOpcodeStr(Opc) 8526 << Input->getType() 8527 << Input->getSourceRange(); 8528 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 8529 Args, NumArgs, 8530 UnaryOperator::getOpcodeStr(Opc), OpLoc); 8531 return ExprError(); 8532 8533 case OR_Deleted: 8534 Diag(OpLoc, diag::err_ovl_deleted_oper) 8535 << Best->Function->isDeleted() 8536 << UnaryOperator::getOpcodeStr(Opc) 8537 << getDeletedOrUnavailableSuffix(Best->Function) 8538 << Input->getSourceRange(); 8539 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8540 return ExprError(); 8541 } 8542 8543 // Either we found no viable overloaded operator or we matched a 8544 // built-in operator. In either case, fall through to trying to 8545 // build a built-in operation. 8546 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8547} 8548 8549/// \brief Create a binary operation that may resolve to an overloaded 8550/// operator. 8551/// 8552/// \param OpLoc The location of the operator itself (e.g., '+'). 8553/// 8554/// \param OpcIn The BinaryOperator::Opcode that describes this 8555/// operator. 8556/// 8557/// \param Functions The set of non-member functions that will be 8558/// considered by overload resolution. The caller needs to build this 8559/// set based on the context using, e.g., 8560/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 8561/// set should not contain any member functions; those will be added 8562/// by CreateOverloadedBinOp(). 8563/// 8564/// \param LHS Left-hand argument. 8565/// \param RHS Right-hand argument. 8566ExprResult 8567Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 8568 unsigned OpcIn, 8569 const UnresolvedSetImpl &Fns, 8570 Expr *LHS, Expr *RHS) { 8571 Expr *Args[2] = { LHS, RHS }; 8572 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 8573 8574 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 8575 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 8576 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8577 8578 // If either side is type-dependent, create an appropriate dependent 8579 // expression. 8580 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 8581 if (Fns.empty()) { 8582 // If there are no functions to store, just build a dependent 8583 // BinaryOperator or CompoundAssignment. 8584 if (Opc <= BO_Assign || Opc > BO_OrAssign) 8585 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 8586 Context.DependentTy, 8587 VK_RValue, OK_Ordinary, 8588 OpLoc)); 8589 8590 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 8591 Context.DependentTy, 8592 VK_LValue, 8593 OK_Ordinary, 8594 Context.DependentTy, 8595 Context.DependentTy, 8596 OpLoc)); 8597 } 8598 8599 // FIXME: save results of ADL from here? 8600 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 8601 // TODO: provide better source location info in DNLoc component. 8602 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 8603 UnresolvedLookupExpr *Fn 8604 = UnresolvedLookupExpr::Create(Context, NamingClass, 8605 NestedNameSpecifierLoc(), OpNameInfo, 8606 /*ADL*/ true, IsOverloaded(Fns), 8607 Fns.begin(), Fns.end()); 8608 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 8609 Args, 2, 8610 Context.DependentTy, 8611 VK_RValue, 8612 OpLoc)); 8613 } 8614 8615 // Always do property rvalue conversions on the RHS. 8616 if (Args[1]->getObjectKind() == OK_ObjCProperty) { 8617 ExprResult Result = ConvertPropertyForRValue(Args[1]); 8618 if (Result.isInvalid()) 8619 return ExprError(); 8620 Args[1] = Result.take(); 8621 } 8622 8623 // The LHS is more complicated. 8624 if (Args[0]->getObjectKind() == OK_ObjCProperty) { 8625 8626 // There's a tension for assignment operators between primitive 8627 // property assignment and the overloaded operators. 8628 if (BinaryOperator::isAssignmentOp(Opc)) { 8629 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty(); 8630 8631 // Is the property "logically" settable? 8632 bool Settable = (PRE->isExplicitProperty() || 8633 PRE->getImplicitPropertySetter()); 8634 8635 // To avoid gratuitously inventing semantics, use the primitive 8636 // unless it isn't. Thoughts in case we ever really care: 8637 // - If the property isn't logically settable, we have to 8638 // load and hope. 8639 // - If the property is settable and this is simple assignment, 8640 // we really should use the primitive. 8641 // - If the property is settable, then we could try overloading 8642 // on a generic lvalue of the appropriate type; if it works 8643 // out to a builtin candidate, we would do that same operation 8644 // on the property, and otherwise just error. 8645 if (Settable) 8646 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8647 } 8648 8649 ExprResult Result = ConvertPropertyForRValue(Args[0]); 8650 if (Result.isInvalid()) 8651 return ExprError(); 8652 Args[0] = Result.take(); 8653 } 8654 8655 // If this is the assignment operator, we only perform overload resolution 8656 // if the left-hand side is a class or enumeration type. This is actually 8657 // a hack. The standard requires that we do overload resolution between the 8658 // various built-in candidates, but as DR507 points out, this can lead to 8659 // problems. So we do it this way, which pretty much follows what GCC does. 8660 // Note that we go the traditional code path for compound assignment forms. 8661 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 8662 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8663 8664 // If this is the .* operator, which is not overloadable, just 8665 // create a built-in binary operator. 8666 if (Opc == BO_PtrMemD) 8667 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8668 8669 // Build an empty overload set. 8670 OverloadCandidateSet CandidateSet(OpLoc); 8671 8672 // Add the candidates from the given function set. 8673 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 8674 8675 // Add operator candidates that are member functions. 8676 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 8677 8678 // Add candidates from ADL. 8679 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 8680 Args, 2, 8681 /*ExplicitTemplateArgs*/ 0, 8682 CandidateSet); 8683 8684 // Add builtin operator candidates. 8685 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 8686 8687 // Perform overload resolution. 8688 OverloadCandidateSet::iterator Best; 8689 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 8690 case OR_Success: { 8691 // We found a built-in operator or an overloaded operator. 8692 FunctionDecl *FnDecl = Best->Function; 8693 8694 if (FnDecl) { 8695 // We matched an overloaded operator. Build a call to that 8696 // operator. 8697 8698 MarkDeclarationReferenced(OpLoc, FnDecl); 8699 8700 // Convert the arguments. 8701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 8702 // Best->Access is only meaningful for class members. 8703 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 8704 8705 ExprResult Arg1 = 8706 PerformCopyInitialization( 8707 InitializedEntity::InitializeParameter(Context, 8708 FnDecl->getParamDecl(0)), 8709 SourceLocation(), Owned(Args[1])); 8710 if (Arg1.isInvalid()) 8711 return ExprError(); 8712 8713 ExprResult Arg0 = 8714 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 8715 Best->FoundDecl, Method); 8716 if (Arg0.isInvalid()) 8717 return ExprError(); 8718 Args[0] = Arg0.takeAs<Expr>(); 8719 Args[1] = RHS = Arg1.takeAs<Expr>(); 8720 } else { 8721 // Convert the arguments. 8722 ExprResult Arg0 = PerformCopyInitialization( 8723 InitializedEntity::InitializeParameter(Context, 8724 FnDecl->getParamDecl(0)), 8725 SourceLocation(), Owned(Args[0])); 8726 if (Arg0.isInvalid()) 8727 return ExprError(); 8728 8729 ExprResult Arg1 = 8730 PerformCopyInitialization( 8731 InitializedEntity::InitializeParameter(Context, 8732 FnDecl->getParamDecl(1)), 8733 SourceLocation(), Owned(Args[1])); 8734 if (Arg1.isInvalid()) 8735 return ExprError(); 8736 Args[0] = LHS = Arg0.takeAs<Expr>(); 8737 Args[1] = RHS = Arg1.takeAs<Expr>(); 8738 } 8739 8740 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 8741 8742 // Determine the result type. 8743 QualType ResultTy = FnDecl->getResultType(); 8744 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8745 ResultTy = ResultTy.getNonLValueExprType(Context); 8746 8747 // Build the actual expression node. 8748 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc); 8749 if (FnExpr.isInvalid()) 8750 return ExprError(); 8751 8752 CXXOperatorCallExpr *TheCall = 8753 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 8754 Args, 2, ResultTy, VK, OpLoc); 8755 8756 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 8757 FnDecl)) 8758 return ExprError(); 8759 8760 return MaybeBindToTemporary(TheCall); 8761 } else { 8762 // We matched a built-in operator. Convert the arguments, then 8763 // break out so that we will build the appropriate built-in 8764 // operator node. 8765 ExprResult ArgsRes0 = 8766 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 8767 Best->Conversions[0], AA_Passing); 8768 if (ArgsRes0.isInvalid()) 8769 return ExprError(); 8770 Args[0] = ArgsRes0.take(); 8771 8772 ExprResult ArgsRes1 = 8773 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 8774 Best->Conversions[1], AA_Passing); 8775 if (ArgsRes1.isInvalid()) 8776 return ExprError(); 8777 Args[1] = ArgsRes1.take(); 8778 break; 8779 } 8780 } 8781 8782 case OR_No_Viable_Function: { 8783 // C++ [over.match.oper]p9: 8784 // If the operator is the operator , [...] and there are no 8785 // viable functions, then the operator is assumed to be the 8786 // built-in operator and interpreted according to clause 5. 8787 if (Opc == BO_Comma) 8788 break; 8789 8790 // For class as left operand for assignment or compound assigment 8791 // operator do not fall through to handling in built-in, but report that 8792 // no overloaded assignment operator found 8793 ExprResult Result = ExprError(); 8794 if (Args[0]->getType()->isRecordType() && 8795 Opc >= BO_Assign && Opc <= BO_OrAssign) { 8796 Diag(OpLoc, diag::err_ovl_no_viable_oper) 8797 << BinaryOperator::getOpcodeStr(Opc) 8798 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8799 } else { 8800 // This is an erroneous use of an operator which can be overloaded by 8801 // a non-member function. Check for non-member operators which were 8802 // defined too late to be candidates. 8803 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2)) 8804 // FIXME: Recover by calling the found function. 8805 return ExprError(); 8806 8807 // No viable function; try to create a built-in operation, which will 8808 // produce an error. Then, show the non-viable candidates. 8809 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8810 } 8811 assert(Result.isInvalid() && 8812 "C++ binary operator overloading is missing candidates!"); 8813 if (Result.isInvalid()) 8814 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 8815 BinaryOperator::getOpcodeStr(Opc), OpLoc); 8816 return move(Result); 8817 } 8818 8819 case OR_Ambiguous: 8820 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 8821 << BinaryOperator::getOpcodeStr(Opc) 8822 << Args[0]->getType() << Args[1]->getType() 8823 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8824 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 8825 BinaryOperator::getOpcodeStr(Opc), OpLoc); 8826 return ExprError(); 8827 8828 case OR_Deleted: 8829 Diag(OpLoc, diag::err_ovl_deleted_oper) 8830 << Best->Function->isDeleted() 8831 << BinaryOperator::getOpcodeStr(Opc) 8832 << getDeletedOrUnavailableSuffix(Best->Function) 8833 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8834 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2); 8835 return ExprError(); 8836 } 8837 8838 // We matched a built-in operator; build it. 8839 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8840} 8841 8842ExprResult 8843Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 8844 SourceLocation RLoc, 8845 Expr *Base, Expr *Idx) { 8846 Expr *Args[2] = { Base, Idx }; 8847 DeclarationName OpName = 8848 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 8849 8850 // If either side is type-dependent, create an appropriate dependent 8851 // expression. 8852 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 8853 8854 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 8855 // CHECKME: no 'operator' keyword? 8856 DeclarationNameInfo OpNameInfo(OpName, LLoc); 8857 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 8858 UnresolvedLookupExpr *Fn 8859 = UnresolvedLookupExpr::Create(Context, NamingClass, 8860 NestedNameSpecifierLoc(), OpNameInfo, 8861 /*ADL*/ true, /*Overloaded*/ false, 8862 UnresolvedSetIterator(), 8863 UnresolvedSetIterator()); 8864 // Can't add any actual overloads yet 8865 8866 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 8867 Args, 2, 8868 Context.DependentTy, 8869 VK_RValue, 8870 RLoc)); 8871 } 8872 8873 if (Args[0]->getObjectKind() == OK_ObjCProperty) { 8874 ExprResult Result = ConvertPropertyForRValue(Args[0]); 8875 if (Result.isInvalid()) 8876 return ExprError(); 8877 Args[0] = Result.take(); 8878 } 8879 if (Args[1]->getObjectKind() == OK_ObjCProperty) { 8880 ExprResult Result = ConvertPropertyForRValue(Args[1]); 8881 if (Result.isInvalid()) 8882 return ExprError(); 8883 Args[1] = Result.take(); 8884 } 8885 8886 // Build an empty overload set. 8887 OverloadCandidateSet CandidateSet(LLoc); 8888 8889 // Subscript can only be overloaded as a member function. 8890 8891 // Add operator candidates that are member functions. 8892 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 8893 8894 // Add builtin operator candidates. 8895 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 8896 8897 // Perform overload resolution. 8898 OverloadCandidateSet::iterator Best; 8899 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 8900 case OR_Success: { 8901 // We found a built-in operator or an overloaded operator. 8902 FunctionDecl *FnDecl = Best->Function; 8903 8904 if (FnDecl) { 8905 // We matched an overloaded operator. Build a call to that 8906 // operator. 8907 8908 MarkDeclarationReferenced(LLoc, FnDecl); 8909 8910 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 8911 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 8912 8913 // Convert the arguments. 8914 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 8915 ExprResult Arg0 = 8916 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 8917 Best->FoundDecl, Method); 8918 if (Arg0.isInvalid()) 8919 return ExprError(); 8920 Args[0] = Arg0.take(); 8921 8922 // Convert the arguments. 8923 ExprResult InputInit 8924 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 8925 Context, 8926 FnDecl->getParamDecl(0)), 8927 SourceLocation(), 8928 Owned(Args[1])); 8929 if (InputInit.isInvalid()) 8930 return ExprError(); 8931 8932 Args[1] = InputInit.takeAs<Expr>(); 8933 8934 // Determine the result type 8935 QualType ResultTy = FnDecl->getResultType(); 8936 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8937 ResultTy = ResultTy.getNonLValueExprType(Context); 8938 8939 // Build the actual expression node. 8940 DeclarationNameLoc LocInfo; 8941 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding(); 8942 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding(); 8943 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo); 8944 if (FnExpr.isInvalid()) 8945 return ExprError(); 8946 8947 CXXOperatorCallExpr *TheCall = 8948 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 8949 FnExpr.take(), Args, 2, 8950 ResultTy, VK, RLoc); 8951 8952 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 8953 FnDecl)) 8954 return ExprError(); 8955 8956 return MaybeBindToTemporary(TheCall); 8957 } else { 8958 // We matched a built-in operator. Convert the arguments, then 8959 // break out so that we will build the appropriate built-in 8960 // operator node. 8961 ExprResult ArgsRes0 = 8962 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 8963 Best->Conversions[0], AA_Passing); 8964 if (ArgsRes0.isInvalid()) 8965 return ExprError(); 8966 Args[0] = ArgsRes0.take(); 8967 8968 ExprResult ArgsRes1 = 8969 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 8970 Best->Conversions[1], AA_Passing); 8971 if (ArgsRes1.isInvalid()) 8972 return ExprError(); 8973 Args[1] = ArgsRes1.take(); 8974 8975 break; 8976 } 8977 } 8978 8979 case OR_No_Viable_Function: { 8980 if (CandidateSet.empty()) 8981 Diag(LLoc, diag::err_ovl_no_oper) 8982 << Args[0]->getType() << /*subscript*/ 0 8983 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8984 else 8985 Diag(LLoc, diag::err_ovl_no_viable_subscript) 8986 << Args[0]->getType() 8987 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8988 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 8989 "[]", LLoc); 8990 return ExprError(); 8991 } 8992 8993 case OR_Ambiguous: 8994 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 8995 << "[]" 8996 << Args[0]->getType() << Args[1]->getType() 8997 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8998 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 8999 "[]", LLoc); 9000 return ExprError(); 9001 9002 case OR_Deleted: 9003 Diag(LLoc, diag::err_ovl_deleted_oper) 9004 << Best->Function->isDeleted() << "[]" 9005 << getDeletedOrUnavailableSuffix(Best->Function) 9006 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 9007 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 9008 "[]", LLoc); 9009 return ExprError(); 9010 } 9011 9012 // We matched a built-in operator; build it. 9013 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 9014} 9015 9016/// BuildCallToMemberFunction - Build a call to a member 9017/// function. MemExpr is the expression that refers to the member 9018/// function (and includes the object parameter), Args/NumArgs are the 9019/// arguments to the function call (not including the object 9020/// parameter). The caller needs to validate that the member 9021/// expression refers to a non-static member function or an overloaded 9022/// member function. 9023ExprResult 9024Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 9025 SourceLocation LParenLoc, Expr **Args, 9026 unsigned NumArgs, SourceLocation RParenLoc) { 9027 assert(MemExprE->getType() == Context.BoundMemberTy || 9028 MemExprE->getType() == Context.OverloadTy); 9029 9030 // Dig out the member expression. This holds both the object 9031 // argument and the member function we're referring to. 9032 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 9033 9034 // Determine whether this is a call to a pointer-to-member function. 9035 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 9036 assert(op->getType() == Context.BoundMemberTy); 9037 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 9038 9039 QualType fnType = 9040 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 9041 9042 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 9043 QualType resultType = proto->getCallResultType(Context); 9044 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 9045 9046 // Check that the object type isn't more qualified than the 9047 // member function we're calling. 9048 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 9049 9050 QualType objectType = op->getLHS()->getType(); 9051 if (op->getOpcode() == BO_PtrMemI) 9052 objectType = objectType->castAs<PointerType>()->getPointeeType(); 9053 Qualifiers objectQuals = objectType.getQualifiers(); 9054 9055 Qualifiers difference = objectQuals - funcQuals; 9056 difference.removeObjCGCAttr(); 9057 difference.removeAddressSpace(); 9058 if (difference) { 9059 std::string qualsString = difference.getAsString(); 9060 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 9061 << fnType.getUnqualifiedType() 9062 << qualsString 9063 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 9064 } 9065 9066 CXXMemberCallExpr *call 9067 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 9068 resultType, valueKind, RParenLoc); 9069 9070 if (CheckCallReturnType(proto->getResultType(), 9071 op->getRHS()->getSourceRange().getBegin(), 9072 call, 0)) 9073 return ExprError(); 9074 9075 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 9076 return ExprError(); 9077 9078 return MaybeBindToTemporary(call); 9079 } 9080 9081 MemberExpr *MemExpr; 9082 CXXMethodDecl *Method = 0; 9083 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 9084 NestedNameSpecifier *Qualifier = 0; 9085 if (isa<MemberExpr>(NakedMemExpr)) { 9086 MemExpr = cast<MemberExpr>(NakedMemExpr); 9087 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 9088 FoundDecl = MemExpr->getFoundDecl(); 9089 Qualifier = MemExpr->getQualifier(); 9090 } else { 9091 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 9092 Qualifier = UnresExpr->getQualifier(); 9093 9094 QualType ObjectType = UnresExpr->getBaseType(); 9095 Expr::Classification ObjectClassification 9096 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 9097 : UnresExpr->getBase()->Classify(Context); 9098 9099 // Add overload candidates 9100 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 9101 9102 // FIXME: avoid copy. 9103 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 9104 if (UnresExpr->hasExplicitTemplateArgs()) { 9105 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 9106 TemplateArgs = &TemplateArgsBuffer; 9107 } 9108 9109 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 9110 E = UnresExpr->decls_end(); I != E; ++I) { 9111 9112 NamedDecl *Func = *I; 9113 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 9114 if (isa<UsingShadowDecl>(Func)) 9115 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 9116 9117 9118 // Microsoft supports direct constructor calls. 9119 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) { 9120 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs, 9121 CandidateSet); 9122 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 9123 // If explicit template arguments were provided, we can't call a 9124 // non-template member function. 9125 if (TemplateArgs) 9126 continue; 9127 9128 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 9129 ObjectClassification, 9130 Args, NumArgs, CandidateSet, 9131 /*SuppressUserConversions=*/false); 9132 } else { 9133 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 9134 I.getPair(), ActingDC, TemplateArgs, 9135 ObjectType, ObjectClassification, 9136 Args, NumArgs, CandidateSet, 9137 /*SuppressUsedConversions=*/false); 9138 } 9139 } 9140 9141 DeclarationName DeclName = UnresExpr->getMemberName(); 9142 9143 OverloadCandidateSet::iterator Best; 9144 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 9145 Best)) { 9146 case OR_Success: 9147 Method = cast<CXXMethodDecl>(Best->Function); 9148 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method); 9149 FoundDecl = Best->FoundDecl; 9150 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 9151 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 9152 break; 9153 9154 case OR_No_Viable_Function: 9155 Diag(UnresExpr->getMemberLoc(), 9156 diag::err_ovl_no_viable_member_function_in_call) 9157 << DeclName << MemExprE->getSourceRange(); 9158 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9159 // FIXME: Leaking incoming expressions! 9160 return ExprError(); 9161 9162 case OR_Ambiguous: 9163 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 9164 << DeclName << MemExprE->getSourceRange(); 9165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9166 // FIXME: Leaking incoming expressions! 9167 return ExprError(); 9168 9169 case OR_Deleted: 9170 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 9171 << Best->Function->isDeleted() 9172 << DeclName 9173 << getDeletedOrUnavailableSuffix(Best->Function) 9174 << MemExprE->getSourceRange(); 9175 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9176 // FIXME: Leaking incoming expressions! 9177 return ExprError(); 9178 } 9179 9180 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 9181 9182 // If overload resolution picked a static member, build a 9183 // non-member call based on that function. 9184 if (Method->isStatic()) { 9185 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 9186 Args, NumArgs, RParenLoc); 9187 } 9188 9189 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 9190 } 9191 9192 QualType ResultType = Method->getResultType(); 9193 ExprValueKind VK = Expr::getValueKindForType(ResultType); 9194 ResultType = ResultType.getNonLValueExprType(Context); 9195 9196 assert(Method && "Member call to something that isn't a method?"); 9197 CXXMemberCallExpr *TheCall = 9198 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 9199 ResultType, VK, RParenLoc); 9200 9201 // Check for a valid return type. 9202 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 9203 TheCall, Method)) 9204 return ExprError(); 9205 9206 // Convert the object argument (for a non-static member function call). 9207 // We only need to do this if there was actually an overload; otherwise 9208 // it was done at lookup. 9209 if (!Method->isStatic()) { 9210 ExprResult ObjectArg = 9211 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 9212 FoundDecl, Method); 9213 if (ObjectArg.isInvalid()) 9214 return ExprError(); 9215 MemExpr->setBase(ObjectArg.take()); 9216 } 9217 9218 // Convert the rest of the arguments 9219 const FunctionProtoType *Proto = 9220 Method->getType()->getAs<FunctionProtoType>(); 9221 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 9222 RParenLoc)) 9223 return ExprError(); 9224 9225 if (CheckFunctionCall(Method, TheCall)) 9226 return ExprError(); 9227 9228 if ((isa<CXXConstructorDecl>(CurContext) || 9229 isa<CXXDestructorDecl>(CurContext)) && 9230 TheCall->getMethodDecl()->isPure()) { 9231 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 9232 9233 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 9234 Diag(MemExpr->getLocStart(), 9235 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 9236 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 9237 << MD->getParent()->getDeclName(); 9238 9239 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 9240 } 9241 } 9242 return MaybeBindToTemporary(TheCall); 9243} 9244 9245/// BuildCallToObjectOfClassType - Build a call to an object of class 9246/// type (C++ [over.call.object]), which can end up invoking an 9247/// overloaded function call operator (@c operator()) or performing a 9248/// user-defined conversion on the object argument. 9249ExprResult 9250Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 9251 SourceLocation LParenLoc, 9252 Expr **Args, unsigned NumArgs, 9253 SourceLocation RParenLoc) { 9254 ExprResult Object = Owned(Obj); 9255 if (Object.get()->getObjectKind() == OK_ObjCProperty) { 9256 Object = ConvertPropertyForRValue(Object.take()); 9257 if (Object.isInvalid()) 9258 return ExprError(); 9259 } 9260 9261 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 9262 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 9263 9264 // C++ [over.call.object]p1: 9265 // If the primary-expression E in the function call syntax 9266 // evaluates to a class object of type "cv T", then the set of 9267 // candidate functions includes at least the function call 9268 // operators of T. The function call operators of T are obtained by 9269 // ordinary lookup of the name operator() in the context of 9270 // (E).operator(). 9271 OverloadCandidateSet CandidateSet(LParenLoc); 9272 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 9273 9274 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 9275 PDiag(diag::err_incomplete_object_call) 9276 << Object.get()->getSourceRange())) 9277 return true; 9278 9279 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 9280 LookupQualifiedName(R, Record->getDecl()); 9281 R.suppressDiagnostics(); 9282 9283 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 9284 Oper != OperEnd; ++Oper) { 9285 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 9286 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 9287 /*SuppressUserConversions=*/ false); 9288 } 9289 9290 // C++ [over.call.object]p2: 9291 // In addition, for each (non-explicit in C++0x) conversion function 9292 // declared in T of the form 9293 // 9294 // operator conversion-type-id () cv-qualifier; 9295 // 9296 // where cv-qualifier is the same cv-qualification as, or a 9297 // greater cv-qualification than, cv, and where conversion-type-id 9298 // denotes the type "pointer to function of (P1,...,Pn) returning 9299 // R", or the type "reference to pointer to function of 9300 // (P1,...,Pn) returning R", or the type "reference to function 9301 // of (P1,...,Pn) returning R", a surrogate call function [...] 9302 // is also considered as a candidate function. Similarly, 9303 // surrogate call functions are added to the set of candidate 9304 // functions for each conversion function declared in an 9305 // accessible base class provided the function is not hidden 9306 // within T by another intervening declaration. 9307 const UnresolvedSetImpl *Conversions 9308 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 9309 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 9310 E = Conversions->end(); I != E; ++I) { 9311 NamedDecl *D = *I; 9312 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 9313 if (isa<UsingShadowDecl>(D)) 9314 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 9315 9316 // Skip over templated conversion functions; they aren't 9317 // surrogates. 9318 if (isa<FunctionTemplateDecl>(D)) 9319 continue; 9320 9321 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 9322 if (!Conv->isExplicit()) { 9323 // Strip the reference type (if any) and then the pointer type (if 9324 // any) to get down to what might be a function type. 9325 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 9326 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9327 ConvType = ConvPtrType->getPointeeType(); 9328 9329 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 9330 { 9331 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 9332 Object.get(), Args, NumArgs, CandidateSet); 9333 } 9334 } 9335 } 9336 9337 // Perform overload resolution. 9338 OverloadCandidateSet::iterator Best; 9339 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 9340 Best)) { 9341 case OR_Success: 9342 // Overload resolution succeeded; we'll build the appropriate call 9343 // below. 9344 break; 9345 9346 case OR_No_Viable_Function: 9347 if (CandidateSet.empty()) 9348 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper) 9349 << Object.get()->getType() << /*call*/ 1 9350 << Object.get()->getSourceRange(); 9351 else 9352 Diag(Object.get()->getSourceRange().getBegin(), 9353 diag::err_ovl_no_viable_object_call) 9354 << Object.get()->getType() << Object.get()->getSourceRange(); 9355 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9356 break; 9357 9358 case OR_Ambiguous: 9359 Diag(Object.get()->getSourceRange().getBegin(), 9360 diag::err_ovl_ambiguous_object_call) 9361 << Object.get()->getType() << Object.get()->getSourceRange(); 9362 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 9363 break; 9364 9365 case OR_Deleted: 9366 Diag(Object.get()->getSourceRange().getBegin(), 9367 diag::err_ovl_deleted_object_call) 9368 << Best->Function->isDeleted() 9369 << Object.get()->getType() 9370 << getDeletedOrUnavailableSuffix(Best->Function) 9371 << Object.get()->getSourceRange(); 9372 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9373 break; 9374 } 9375 9376 if (Best == CandidateSet.end()) 9377 return true; 9378 9379 if (Best->Function == 0) { 9380 // Since there is no function declaration, this is one of the 9381 // surrogate candidates. Dig out the conversion function. 9382 CXXConversionDecl *Conv 9383 = cast<CXXConversionDecl>( 9384 Best->Conversions[0].UserDefined.ConversionFunction); 9385 9386 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 9387 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 9388 9389 // We selected one of the surrogate functions that converts the 9390 // object parameter to a function pointer. Perform the conversion 9391 // on the object argument, then let ActOnCallExpr finish the job. 9392 9393 // Create an implicit member expr to refer to the conversion operator. 9394 // and then call it. 9395 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv); 9396 if (Call.isInvalid()) 9397 return ExprError(); 9398 9399 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 9400 RParenLoc); 9401 } 9402 9403 MarkDeclarationReferenced(LParenLoc, Best->Function); 9404 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 9405 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 9406 9407 // We found an overloaded operator(). Build a CXXOperatorCallExpr 9408 // that calls this method, using Object for the implicit object 9409 // parameter and passing along the remaining arguments. 9410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 9411 const FunctionProtoType *Proto = 9412 Method->getType()->getAs<FunctionProtoType>(); 9413 9414 unsigned NumArgsInProto = Proto->getNumArgs(); 9415 unsigned NumArgsToCheck = NumArgs; 9416 9417 // Build the full argument list for the method call (the 9418 // implicit object parameter is placed at the beginning of the 9419 // list). 9420 Expr **MethodArgs; 9421 if (NumArgs < NumArgsInProto) { 9422 NumArgsToCheck = NumArgsInProto; 9423 MethodArgs = new Expr*[NumArgsInProto + 1]; 9424 } else { 9425 MethodArgs = new Expr*[NumArgs + 1]; 9426 } 9427 MethodArgs[0] = Object.get(); 9428 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 9429 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 9430 9431 ExprResult NewFn = CreateFunctionRefExpr(*this, Method); 9432 if (NewFn.isInvalid()) 9433 return true; 9434 9435 // Once we've built TheCall, all of the expressions are properly 9436 // owned. 9437 QualType ResultTy = Method->getResultType(); 9438 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9439 ResultTy = ResultTy.getNonLValueExprType(Context); 9440 9441 CXXOperatorCallExpr *TheCall = 9442 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 9443 MethodArgs, NumArgs + 1, 9444 ResultTy, VK, RParenLoc); 9445 delete [] MethodArgs; 9446 9447 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 9448 Method)) 9449 return true; 9450 9451 // We may have default arguments. If so, we need to allocate more 9452 // slots in the call for them. 9453 if (NumArgs < NumArgsInProto) 9454 TheCall->setNumArgs(Context, NumArgsInProto + 1); 9455 else if (NumArgs > NumArgsInProto) 9456 NumArgsToCheck = NumArgsInProto; 9457 9458 bool IsError = false; 9459 9460 // Initialize the implicit object parameter. 9461 ExprResult ObjRes = 9462 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 9463 Best->FoundDecl, Method); 9464 if (ObjRes.isInvalid()) 9465 IsError = true; 9466 else 9467 Object = move(ObjRes); 9468 TheCall->setArg(0, Object.take()); 9469 9470 // Check the argument types. 9471 for (unsigned i = 0; i != NumArgsToCheck; i++) { 9472 Expr *Arg; 9473 if (i < NumArgs) { 9474 Arg = Args[i]; 9475 9476 // Pass the argument. 9477 9478 ExprResult InputInit 9479 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9480 Context, 9481 Method->getParamDecl(i)), 9482 SourceLocation(), Arg); 9483 9484 IsError |= InputInit.isInvalid(); 9485 Arg = InputInit.takeAs<Expr>(); 9486 } else { 9487 ExprResult DefArg 9488 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 9489 if (DefArg.isInvalid()) { 9490 IsError = true; 9491 break; 9492 } 9493 9494 Arg = DefArg.takeAs<Expr>(); 9495 } 9496 9497 TheCall->setArg(i + 1, Arg); 9498 } 9499 9500 // If this is a variadic call, handle args passed through "...". 9501 if (Proto->isVariadic()) { 9502 // Promote the arguments (C99 6.5.2.2p7). 9503 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 9504 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 9505 IsError |= Arg.isInvalid(); 9506 TheCall->setArg(i + 1, Arg.take()); 9507 } 9508 } 9509 9510 if (IsError) return true; 9511 9512 if (CheckFunctionCall(Method, TheCall)) 9513 return true; 9514 9515 return MaybeBindToTemporary(TheCall); 9516} 9517 9518/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 9519/// (if one exists), where @c Base is an expression of class type and 9520/// @c Member is the name of the member we're trying to find. 9521ExprResult 9522Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 9523 assert(Base->getType()->isRecordType() && 9524 "left-hand side must have class type"); 9525 9526 if (Base->getObjectKind() == OK_ObjCProperty) { 9527 ExprResult Result = ConvertPropertyForRValue(Base); 9528 if (Result.isInvalid()) 9529 return ExprError(); 9530 Base = Result.take(); 9531 } 9532 9533 SourceLocation Loc = Base->getExprLoc(); 9534 9535 // C++ [over.ref]p1: 9536 // 9537 // [...] An expression x->m is interpreted as (x.operator->())->m 9538 // for a class object x of type T if T::operator->() exists and if 9539 // the operator is selected as the best match function by the 9540 // overload resolution mechanism (13.3). 9541 DeclarationName OpName = 9542 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 9543 OverloadCandidateSet CandidateSet(Loc); 9544 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 9545 9546 if (RequireCompleteType(Loc, Base->getType(), 9547 PDiag(diag::err_typecheck_incomplete_tag) 9548 << Base->getSourceRange())) 9549 return ExprError(); 9550 9551 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 9552 LookupQualifiedName(R, BaseRecord->getDecl()); 9553 R.suppressDiagnostics(); 9554 9555 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 9556 Oper != OperEnd; ++Oper) { 9557 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 9558 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 9559 } 9560 9561 // Perform overload resolution. 9562 OverloadCandidateSet::iterator Best; 9563 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9564 case OR_Success: 9565 // Overload resolution succeeded; we'll build the call below. 9566 break; 9567 9568 case OR_No_Viable_Function: 9569 if (CandidateSet.empty()) 9570 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 9571 << Base->getType() << Base->getSourceRange(); 9572 else 9573 Diag(OpLoc, diag::err_ovl_no_viable_oper) 9574 << "operator->" << Base->getSourceRange(); 9575 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 9576 return ExprError(); 9577 9578 case OR_Ambiguous: 9579 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 9580 << "->" << Base->getType() << Base->getSourceRange(); 9581 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1); 9582 return ExprError(); 9583 9584 case OR_Deleted: 9585 Diag(OpLoc, diag::err_ovl_deleted_oper) 9586 << Best->Function->isDeleted() 9587 << "->" 9588 << getDeletedOrUnavailableSuffix(Best->Function) 9589 << Base->getSourceRange(); 9590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 9591 return ExprError(); 9592 } 9593 9594 MarkDeclarationReferenced(OpLoc, Best->Function); 9595 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 9596 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 9597 9598 // Convert the object parameter. 9599 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 9600 ExprResult BaseResult = 9601 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 9602 Best->FoundDecl, Method); 9603 if (BaseResult.isInvalid()) 9604 return ExprError(); 9605 Base = BaseResult.take(); 9606 9607 // Build the operator call. 9608 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method); 9609 if (FnExpr.isInvalid()) 9610 return ExprError(); 9611 9612 QualType ResultTy = Method->getResultType(); 9613 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9614 ResultTy = ResultTy.getNonLValueExprType(Context); 9615 CXXOperatorCallExpr *TheCall = 9616 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 9617 &Base, 1, ResultTy, VK, OpLoc); 9618 9619 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 9620 Method)) 9621 return ExprError(); 9622 9623 return MaybeBindToTemporary(TheCall); 9624} 9625 9626/// FixOverloadedFunctionReference - E is an expression that refers to 9627/// a C++ overloaded function (possibly with some parentheses and 9628/// perhaps a '&' around it). We have resolved the overloaded function 9629/// to the function declaration Fn, so patch up the expression E to 9630/// refer (possibly indirectly) to Fn. Returns the new expr. 9631Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 9632 FunctionDecl *Fn) { 9633 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 9634 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 9635 Found, Fn); 9636 if (SubExpr == PE->getSubExpr()) 9637 return PE; 9638 9639 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 9640 } 9641 9642 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9643 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 9644 Found, Fn); 9645 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 9646 SubExpr->getType()) && 9647 "Implicit cast type cannot be determined from overload"); 9648 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 9649 if (SubExpr == ICE->getSubExpr()) 9650 return ICE; 9651 9652 return ImplicitCastExpr::Create(Context, ICE->getType(), 9653 ICE->getCastKind(), 9654 SubExpr, 0, 9655 ICE->getValueKind()); 9656 } 9657 9658 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 9659 assert(UnOp->getOpcode() == UO_AddrOf && 9660 "Can only take the address of an overloaded function"); 9661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9662 if (Method->isStatic()) { 9663 // Do nothing: static member functions aren't any different 9664 // from non-member functions. 9665 } else { 9666 // Fix the sub expression, which really has to be an 9667 // UnresolvedLookupExpr holding an overloaded member function 9668 // or template. 9669 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 9670 Found, Fn); 9671 if (SubExpr == UnOp->getSubExpr()) 9672 return UnOp; 9673 9674 assert(isa<DeclRefExpr>(SubExpr) 9675 && "fixed to something other than a decl ref"); 9676 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 9677 && "fixed to a member ref with no nested name qualifier"); 9678 9679 // We have taken the address of a pointer to member 9680 // function. Perform the computation here so that we get the 9681 // appropriate pointer to member type. 9682 QualType ClassType 9683 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 9684 QualType MemPtrType 9685 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 9686 9687 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 9688 VK_RValue, OK_Ordinary, 9689 UnOp->getOperatorLoc()); 9690 } 9691 } 9692 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 9693 Found, Fn); 9694 if (SubExpr == UnOp->getSubExpr()) 9695 return UnOp; 9696 9697 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 9698 Context.getPointerType(SubExpr->getType()), 9699 VK_RValue, OK_Ordinary, 9700 UnOp->getOperatorLoc()); 9701 } 9702 9703 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9704 // FIXME: avoid copy. 9705 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 9706 if (ULE->hasExplicitTemplateArgs()) { 9707 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 9708 TemplateArgs = &TemplateArgsBuffer; 9709 } 9710 9711 return DeclRefExpr::Create(Context, 9712 ULE->getQualifierLoc(), 9713 Fn, 9714 ULE->getNameLoc(), 9715 Fn->getType(), 9716 VK_LValue, 9717 Found.getDecl(), 9718 TemplateArgs); 9719 } 9720 9721 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 9722 // FIXME: avoid copy. 9723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 9724 if (MemExpr->hasExplicitTemplateArgs()) { 9725 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 9726 TemplateArgs = &TemplateArgsBuffer; 9727 } 9728 9729 Expr *Base; 9730 9731 // If we're filling in a static method where we used to have an 9732 // implicit member access, rewrite to a simple decl ref. 9733 if (MemExpr->isImplicitAccess()) { 9734 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 9735 return DeclRefExpr::Create(Context, 9736 MemExpr->getQualifierLoc(), 9737 Fn, 9738 MemExpr->getMemberLoc(), 9739 Fn->getType(), 9740 VK_LValue, 9741 Found.getDecl(), 9742 TemplateArgs); 9743 } else { 9744 SourceLocation Loc = MemExpr->getMemberLoc(); 9745 if (MemExpr->getQualifier()) 9746 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 9747 Base = new (Context) CXXThisExpr(Loc, 9748 MemExpr->getBaseType(), 9749 /*isImplicit=*/true); 9750 } 9751 } else 9752 Base = MemExpr->getBase(); 9753 9754 ExprValueKind valueKind; 9755 QualType type; 9756 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 9757 valueKind = VK_LValue; 9758 type = Fn->getType(); 9759 } else { 9760 valueKind = VK_RValue; 9761 type = Context.BoundMemberTy; 9762 } 9763 9764 return MemberExpr::Create(Context, Base, 9765 MemExpr->isArrow(), 9766 MemExpr->getQualifierLoc(), 9767 Fn, 9768 Found, 9769 MemExpr->getMemberNameInfo(), 9770 TemplateArgs, 9771 type, valueKind, OK_Ordinary); 9772 } 9773 9774 llvm_unreachable("Invalid reference to overloaded function"); 9775 return E; 9776} 9777 9778ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 9779 DeclAccessPair Found, 9780 FunctionDecl *Fn) { 9781 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 9782} 9783 9784} // end namespace clang 9785