SemaOverload.cpp revision 4a030228d1bfa0cab89114a18d6b50b44eb3a1a8
13a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 23a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// 33a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// The LLVM Compiler Infrastructure 43a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// 53a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// This file is distributed under the University of Illinois Open Source 63a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// License. See LICENSE.TXT for details. 73a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// 83a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis//===----------------------------------------------------------------------===// 93a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// 10fc8f0e14ad142ed811e90fbd9a30e419e301c717Chris Lattner// This file provides Sema routines for C++ overloading. 113a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis// 123a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis//===----------------------------------------------------------------------===// 133a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis 143a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "clang/Sema/SemaInternal.h" 15ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall#include "clang/Sema/Lookup.h" 16ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall#include "clang/Sema/Initialization.h" 17ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall#include "clang/Sema/Template.h" 18ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall#include "clang/Sema/TemplateDeduction.h" 193a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "clang/Basic/Diagnostic.h" 203a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "clang/Lex/Preprocessor.h" 213a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "clang/AST/ASTContext.h" 220bab0cdab751248ca389a5592bcb70eac5d39260John McCall#include "clang/AST/CXXInheritance.h" 239ee494f98610dcd79441dce469d7bf609fcd7b92Charles Davis#include "clang/AST/DeclObjC.h" 2493d557bc1867b7d7b102f87290194b4be7932c92John McCall#include "clang/AST/Expr.h" 253a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "clang/AST/ExprCXX.h" 26ba77cb9c82cc9d498e4d6474d128007249f07871Craig Topper#include "clang/AST/ExprObjC.h" 27ba77cb9c82cc9d498e4d6474d128007249f07871Craig Topper#include "clang/AST/TypeOrdering.h" 283b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "clang/Basic/PartialDiagnostic.h" 293b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/ADT/DenseSet.h" 303b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/ADT/SmallPtrSet.h" 313a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "llvm/ADT/SmallString.h" 323a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis#include "llvm/ADT/STLExtras.h" 3393d557bc1867b7d7b102f87290194b4be7932c92John McCall#include <algorithm> 343a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis 353a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davisnamespace clang { 36071cc7deffad608165b1ddd5263e8bf181861520Charles Davisusing namespace sema; 3793d557bc1867b7d7b102f87290194b4be7932c92John McCall 38babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// A convenience routine for creating a decayed reference to a 390bab0cdab751248ca389a5592bcb70eac5d39260John McCall/// function. 403a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davisstatic ExprResult 41babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCallCreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 4292e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner SourceLocation Loc = SourceLocation(), 4393d557bc1867b7d7b102f87290194b4be7932c92John McCall const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 44ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 45ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov VK_LValue, Loc, LocInfo); 46ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov if (HadMultipleCandidates) 47ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov DRE->setHadMultipleCandidates(true); 48ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov ExprResult E = S.Owned(DRE); 49ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov E = S.DefaultFunctionArrayConversion(E.take()); 50ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov if (E.isInvalid()) 51ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov return ExprError(); 52ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov return E; 53ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov} 54ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov 55ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanovstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 56ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov bool InOverloadResolution, 57ed23bdf69dd63e4fd01c02b12a13d1e6cbff9c2fTimur Iskhodzhanov StandardConversionSequence &SCS, 58f16aa103d3afd42fbca2ab346f191bf745cec092John McCall bool CStyle, 59cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCall bool AllowObjCWritebackConversion); 609cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner 610bab0cdab751248ca389a5592bcb70eac5d39260John McCallstatic bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 6293d557bc1867b7d7b102f87290194b4be7932c92John McCall QualType &ToType, 6393d557bc1867b7d7b102f87290194b4be7932c92John McCall bool InOverloadResolution, 6493d557bc1867b7d7b102f87290194b4be7932c92John McCall StandardConversionSequence &SCS, 6593d557bc1867b7d7b102f87290194b4be7932c92John McCall bool CStyle); 663023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCallstatic OverloadingResult 676c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCallIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 686c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall UserDefinedConversionSequence& User, 696c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall OverloadCandidateSet& Conversions, 706c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall bool AllowExplicit); 716c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall 720bab0cdab751248ca389a5592bcb70eac5d39260John McCall 730bab0cdab751248ca389a5592bcb70eac5d39260John McCallstatic ImplicitConversionSequence::CompareKind 740bab0cdab751248ca389a5592bcb70eac5d39260John McCallCompareStandardConversionSequences(Sema &S, 754d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall const StandardConversionSequence& SCS1, 764d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall const StandardConversionSequence& SCS2); 77cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCall 780bab0cdab751248ca389a5592bcb70eac5d39260John McCallstatic ImplicitConversionSequence::CompareKind 79cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCallCompareQualificationConversions(Sema &S, 80755d8497e39071aa24acc173ff07083e3256b8f8John McCall const StandardConversionSequence& SCS1, 815808ce43f8d7e71f5acacc9ca320268c4f37565aJohn McCall const StandardConversionSequence& SCS2); 825808ce43f8d7e71f5acacc9ca320268c4f37565aJohn McCall 832d6a5670465cb3f1d811695a9f23e372508240d2Richard Smithstatic ImplicitConversionSequence::CompareKind 842d6a5670465cb3f1d811695a9f23e372508240d2Richard SmithCompareDerivedToBaseConversions(Sema &S, 852d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith const StandardConversionSequence& SCS1, 86875ab10245d3bf37252dd822aa1616bb0a391095John McCall const StandardConversionSequence& SCS2); 870bab0cdab751248ca389a5592bcb70eac5d39260John McCall 880bab0cdab751248ca389a5592bcb70eac5d39260John McCall 890bab0cdab751248ca389a5592bcb70eac5d39260John McCall 900bab0cdab751248ca389a5592bcb70eac5d39260John McCall/// GetConversionCategory - Retrieve the implicit conversion 910bab0cdab751248ca389a5592bcb70eac5d39260John McCall/// category corresponding to the given implicit conversion kind. 92e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCallImplicitConversionCategory 930bab0cdab751248ca389a5592bcb70eac5d39260John McCallGetConversionCategory(ImplicitConversionKind Kind) { 940bab0cdab751248ca389a5592bcb70eac5d39260John McCall static const ImplicitConversionCategory 950bab0cdab751248ca389a5592bcb70eac5d39260John McCall Category[(int)ICK_Num_Conversion_Kinds] = { 964c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Identity, 97ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall ICC_Lvalue_Transformation, 98ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall ICC_Lvalue_Transformation, 99ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall ICC_Lvalue_Transformation, 100ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall ICC_Identity, 1014c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Qualification_Adjustment, 1024c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Promotion, 1034c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Promotion, 1045f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner ICC_Promotion, 1054c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1064c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1074c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1084c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1095f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner ICC_Conversion, 1104c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1114c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1124c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1134c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1144c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1154c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ICC_Conversion, 1161e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall ICC_Conversion, 11763fd408a61ae9b94e8d8a986832f526f7cdbfa84Manman Ren ICC_Conversion 1181d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov }; 1191d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov return Category[(int)Kind]; 1201d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov} 1211d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov 1221d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov/// GetConversionRank - Retrieve the implicit conversion rank 1231d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov/// corresponding to the given implicit conversion kind. 1241d4fff5551c2347010b955b4337a2aa7d65a050eTimur IskhodzhanovImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 1250f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov static const ImplicitConversionRank 1260f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov Rank[(int)ICK_Num_Conversion_Kinds] = { 1270f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov ICR_Exact_Match, 1280f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov ICR_Exact_Match, 1290f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov ICR_Exact_Match, 1300f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov ICR_Exact_Match, 1310f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov ICR_Exact_Match, 132285baac67d722beb6854f5faa45ee1aa62a7ce92Joao Matos ICR_Exact_Match, 1332eb9a959d24ad757a82ecab61f343635ad67749aDavid Blaikie ICR_Promotion, 134285baac67d722beb6854f5faa45ee1aa62a7ce92Joao Matos ICR_Promotion, 135e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall ICR_Promotion, 1361e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall ICR_Conversion, 1371e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall ICR_Conversion, 1381e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall ICR_Conversion, 1396ec278d1a354517e20f13a877481453ee7940c78John McCall ICR_Conversion, 1401e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall ICR_Conversion, 141e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall ICR_Conversion, 142e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall ICR_Conversion, 143e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall ICR_Conversion, 1445cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICR_Conversion, 1453030eb82593097502469a8b3fc26112c79c75605John McCall ICR_Conversion, 1460f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth ICR_Conversion, 14704e517650569598e847c2ab609672e6df93effe5Richard Smith ICR_Complex_Real_Conversion, 14804e517650569598e847c2ab609672e6df93effe5Richard Smith ICR_Conversion, 149b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith ICR_Conversion, 150b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith ICR_Writeback_Conversion 151b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith }; 152b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return Rank[(int)Kind]; 153b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith} 154b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 155b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// GetImplicitConversionName - Return the name of this kind of 156b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// implicit conversion. 1573a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davisconst char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall "No conversion", 160ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall "Lvalue-to-rvalue", 161babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall "Array-to-pointer", 1624c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Function-to-pointer", 1634c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Noreturn adjustment", 1644c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Qualification", 1654c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Integral promotion", 1665f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner "Floating point promotion", 1674c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Complex promotion", 1684c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Integral conversion", 1694c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Floating conversion", 1704c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Complex conversion", 1715f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner "Floating-integral conversion", 1724c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Pointer conversion", 1734c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Pointer-to-member conversion", 1744c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Boolean conversion", 1754c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Compatible-types conversion", 1764c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Derived-to-base conversion", 1774c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Vector conversion", 1784c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Vector splat", 1794c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Complex-real conversion", 1804c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall "Block Pointer conversion", 181e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall "Transparent Union Conversion" 1821e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall "Writeback conversion" 1831e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall }; 1841e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall return Name[Kind]; 1856ec278d1a354517e20f13a877481453ee7940c78John McCall} 1861e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall 187e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall/// StandardConversionSequence - Set the standard conversion 188e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall/// sequence to the identity conversion. 1894c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCallvoid StandardConversionSequence::setAsIdentityConversion() { 1904c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall First = ICK_Identity; 1914c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Second = ICK_Identity; 19263fd408a61ae9b94e8d8a986832f526f7cdbfa84Manman Ren Third = ICK_Identity; 19363fd408a61ae9b94e8d8a986832f526f7cdbfa84Manman Ren DeprecatedStringLiteralToCharPtr = false; 19463fd408a61ae9b94e8d8a986832f526f7cdbfa84Manman Ren QualificationIncludesObjCLifetime = false; 1954c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ReferenceBinding = false; 1964c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall DirectBinding = false; 1974c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall IsLvalueReference = true; 198ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall BindsToFunctionLvalue = false; 1993a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis BindsToRvalue = false; 2003a811f1f4286ee3fd0c563c1cfe623956f3caa24Charles Davis BindsImplicitObjectArgumentWithoutRefQualifier = false; 201071cc7deffad608165b1ddd5263e8bf181861520Charles Davis ObjCLifetimeConversionBinding = false; 20264aa4b3ec7e62288e2e66c1935487ece995ca94bJohn McCall CopyConstructor = 0; 20396fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall} 20496fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall 20596fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall/// getRank - Retrieve the rank of this standard conversion sequence 20696fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 20796fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall/// implicit conversions. 20896fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCallImplicitConversionRank StandardConversionSequence::getRank() const { 209c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover ImplicitConversionRank Rank = ICR_Exact_Match; 210c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover if (GetConversionRank(First) > Rank) 211c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover Rank = GetConversionRank(First); 212c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover if (GetConversionRank(Second) > Rank) 213c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover Rank = GetConversionRank(Second); 214c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover if (GetConversionRank(Third) > Rank) 21596fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall Rank = GetConversionRank(Third); 21696fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall return Rank; 21796fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall} 21896fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall 21996fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall/// isPointerConversionToBool - Determines whether this conversion is 22096fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall/// a conversion of a pointer or pointer-to-member to bool. This is 22196fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall/// used as part of the ranking of standard conversion sequences 222ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCall/// (C++ 13.3.3.2p4). 223ee79a4c30e5d1c5285551c9a25b8ec6d45d46aa7John McCallbool StandardConversionSequence::isPointerConversionToBool() const { 2249cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner // Note that FromType has not necessarily been transformed by the 2250bab0cdab751248ca389a5592bcb70eac5d39260John McCall // array-to-pointer or function-to-pointer implicit conversions, so 2260bab0cdab751248ca389a5592bcb70eac5d39260John McCall // check for their presence as well as checking whether FromType is 22792e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner // a pointer. 22892e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner if (getToType(1)->isBooleanType() && 229875ab10245d3bf37252dd822aa1616bb0a391095John McCall (getFromType()->isPointerType() || 230875ab10245d3bf37252dd822aa1616bb0a391095John McCall getFromType()->isObjCObjectPointerType() || 231babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall getFromType()->isBlockPointerType() || 232babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall getFromType()->isNullPtrType() || 233babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall return true; 235babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall 236babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall return false; 237babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall} 238babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall 239babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// isPointerConversionToVoidPointer - Determines whether this 240babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// conversion is a conversion of a pointer to a void pointer. This is 241babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// used as part of the ranking of standard conversion sequences (C++ 242babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// 13.3.3.2p4). 243babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCallbool 244babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCallStandardConversionSequence:: 245babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCallisPointerConversionToVoidPointer(ASTContext& Context) const { 246babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall QualType FromType = getFromType(); 247babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall QualType ToType = getToType(1); 248babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall 249babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall // Note that FromType has not necessarily been transformed by the 250babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall // array-to-pointer implicit conversion, so check for its presence 25193d557bc1867b7d7b102f87290194b4be7932c92John McCall // and redo the conversion to get a pointer. 25293d557bc1867b7d7b102f87290194b4be7932c92John McCall if (First == ICK_Array_To_Pointer) 25393d557bc1867b7d7b102f87290194b4be7932c92John McCall FromType = Context.getArrayDecayedType(FromType); 25493d557bc1867b7d7b102f87290194b4be7932c92John McCall 25593d557bc1867b7d7b102f87290194b4be7932c92John McCall if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 25693d557bc1867b7d7b102f87290194b4be7932c92John McCall if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 25793d557bc1867b7d7b102f87290194b4be7932c92John McCall return ToPtrType->getPointeeType()->isVoidType(); 25893d557bc1867b7d7b102f87290194b4be7932c92John McCall 25993d557bc1867b7d7b102f87290194b4be7932c92John McCall return false; 26093d557bc1867b7d7b102f87290194b4be7932c92John McCall} 26193d557bc1867b7d7b102f87290194b4be7932c92John McCall 26293d557bc1867b7d7b102f87290194b4be7932c92John McCall/// Skip any implicit casts which could be either part of a narrowing conversion 2632acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner/// or after one in an implicit conversion. 264de5d3c717684f3821b8db58037bc7140acf134aaJohn McCallstatic const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 265de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 26693d557bc1867b7d7b102f87290194b4be7932c92John McCall switch (ICE->getCastKind()) { 26792e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner case CK_NoOp: 26893d557bc1867b7d7b102f87290194b4be7932c92John McCall case CK_IntegralCast: 269babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall case CK_IntegralToBoolean: 270babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall case CK_IntegralToFloating: 271babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall case CK_FloatingToIntegral: 272babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall case CK_FloatingToBoolean: 273d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case CK_FloatingCast: 274d608cdb7c044365cf4e8764ade1e11e99c176078John McCall Converted = ICE->getSubExpr(); 275babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall continue; 276babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall 277babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall default: 278babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall return Converted; 279babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall } 28093d557bc1867b7d7b102f87290194b4be7932c92John McCall } 28193d557bc1867b7d7b102f87290194b4be7932c92John McCall 28293d557bc1867b7d7b102f87290194b4be7932c92John McCall return Converted; 283babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall} 284babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall 285babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// Check if this standard conversion sequence represents a narrowing 28693d557bc1867b7d7b102f87290194b4be7932c92John McCall/// conversion, according to C++11 [dcl.init.list]p7. 28793d557bc1867b7d7b102f87290194b4be7932c92John McCall/// 288d608cdb7c044365cf4e8764ade1e11e99c176078John McCall/// \param Ctx The AST context. 28993d557bc1867b7d7b102f87290194b4be7932c92John McCall/// \param Converted The result of applying this standard conversion sequence. 29093d557bc1867b7d7b102f87290194b4be7932c92John McCall/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 29193d557bc1867b7d7b102f87290194b4be7932c92John McCall/// value of the expression prior to the narrowing conversion. 292babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 293babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall/// type of the expression prior to the narrowing conversion. 294babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCallNarrowingKind 295babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCallStandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 296babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall const Expr *Converted, 297babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall APValue &ConstantValue, 29893d557bc1867b7d7b102f87290194b4be7932c92John McCall QualType &ConstantType) const { 29993d557bc1867b7d7b102f87290194b4be7932c92John McCall assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 30093d557bc1867b7d7b102f87290194b4be7932c92John McCall 30193d557bc1867b7d7b102f87290194b4be7932c92John McCall // C++11 [dcl.init.list]p7: 302babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall // A narrowing conversion is an implicit conversion ... 30393d557bc1867b7d7b102f87290194b4be7932c92John McCall QualType FromType = getToType(0); 30493d557bc1867b7d7b102f87290194b4be7932c92John McCall QualType ToType = getToType(1); 30593d557bc1867b7d7b102f87290194b4be7932c92John McCall switch (Second) { 3062acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner // -- from a floating-point type to an integer type, or 30793d557bc1867b7d7b102f87290194b4be7932c92John McCall // 308babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall // -- from an integer type or unscoped enumeration type to a floating-point 30993d557bc1867b7d7b102f87290194b4be7932c92John McCall // type, except where the source is a constant expression and the actual 31093d557bc1867b7d7b102f87290194b4be7932c92John McCall // value after conversion will fit into the target type and will produce 311babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall // the original value when converted back to the original type, or 312babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall case ICK_Floating_Integral: 313babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 31493d557bc1867b7d7b102f87290194b4be7932c92John McCall return NK_Type_Narrowing; 31593d557bc1867b7d7b102f87290194b4be7932c92John McCall } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 31693d557bc1867b7d7b102f87290194b4be7932c92John McCall llvm::APSInt IntConstantValue; 317babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall const Expr *Initializer = IgnoreNarrowingConversion(Converted); 31893d557bc1867b7d7b102f87290194b4be7932c92John McCall if (Initializer && 31993d557bc1867b7d7b102f87290194b4be7932c92John McCall Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 32093d557bc1867b7d7b102f87290194b4be7932c92John McCall // Convert the integer to the floating type. 32193d557bc1867b7d7b102f87290194b4be7932c92John McCall llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 32293d557bc1867b7d7b102f87290194b4be7932c92John McCall Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 32393d557bc1867b7d7b102f87290194b4be7932c92John McCall llvm::APFloat::rmNearestTiesToEven); 324babc9a9ecc3fbc04edaac5a1f4fb3e869815b25cJohn McCall // And back. 32593d557bc1867b7d7b102f87290194b4be7932c92John McCall llvm::APSInt ConvertedValue = IntConstantValue; 32693d557bc1867b7d7b102f87290194b4be7932c92John McCall bool ignored; 32793d557bc1867b7d7b102f87290194b4be7932c92John McCall Result.convertToInteger(ConvertedValue, 328bbf3bacb3e0c1ebb3e8a4a8b1330404a7e379315Jay Foad llvm::APFloat::rmTowardZero, &ignored); 32993d557bc1867b7d7b102f87290194b4be7932c92John McCall // If the resulting value is different, this was a narrowing conversion. 33093d557bc1867b7d7b102f87290194b4be7932c92John McCall if (IntConstantValue != ConvertedValue) { 33193d557bc1867b7d7b102f87290194b4be7932c92John McCall ConstantValue = APValue(IntConstantValue); 33293d557bc1867b7d7b102f87290194b4be7932c92John McCall ConstantType = Initializer->getType(); 3333023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall return NK_Constant_Narrowing; 3346c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall } 3356c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall } else { 3366c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall // Variables are always narrowings. 3376c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall return NK_Variable_Narrowing; 3386c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall } 3396c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall } 34092e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner return NK_Not_Narrowing; 3416c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall 3426c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall // -- from long double to double or float, or from double to float, except 3436c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall // where the source is a constant expression and the actual value after 344956a5a17713deb1b5b27893303c4f308a1bd2a62Micah Villmow // conversion is within the range of values that can be represented (even 3456c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall // if it cannot be represented exactly), or 3466c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall case ICK_Floating_Conversion: 3476c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 3486c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 3496c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall // FromType is larger than ToType. 3506c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall const Expr *Initializer = IgnoreNarrowingConversion(Converted); 3516c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 3526c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall // Constant! 3536c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall assert(ConstantValue.isFloat()); 3542acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner llvm::APFloat FloatVal = ConstantValue.getFloat(); 355eede61a83e90f3cb03ef8665b67d648dccd6ce42Douglas Gregor // Convert the source value into the target type. 3566c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall bool ignored; 3576c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 3586c2ab1d578c6cc1f3ddcc948532cd625f1092ef2John McCall Ctx.getFloatTypeSemantics(ToType), 3594d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall llvm::APFloat::rmNearestTiesToEven, &ignored); 3604d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // If there was no overflow, the source value is within the range of 3614d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // values that can be represented. 3624d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (ConvertStatus & llvm::APFloat::opOverflow) { 3630bab0cdab751248ca389a5592bcb70eac5d39260John McCall ConstantType = Initializer->getType(); 3640bab0cdab751248ca389a5592bcb70eac5d39260John McCall return NK_Constant_Narrowing; 3650bab0cdab751248ca389a5592bcb70eac5d39260John McCall } 3660bab0cdab751248ca389a5592bcb70eac5d39260John McCall } else { 3670bab0cdab751248ca389a5592bcb70eac5d39260John McCall return NK_Variable_Narrowing; 3680bab0cdab751248ca389a5592bcb70eac5d39260John McCall } 3690bab0cdab751248ca389a5592bcb70eac5d39260John McCall } 3700bab0cdab751248ca389a5592bcb70eac5d39260John McCall return NK_Not_Narrowing; 3710bab0cdab751248ca389a5592bcb70eac5d39260John McCall 3720bab0cdab751248ca389a5592bcb70eac5d39260John McCall // -- from an integer type or unscoped enumeration type to an integer type 3730bab0cdab751248ca389a5592bcb70eac5d39260John McCall // that cannot represent all the values of the original type, except where 3740bab0cdab751248ca389a5592bcb70eac5d39260John McCall // the source is a constant expression and the actual value after 3750bab0cdab751248ca389a5592bcb70eac5d39260John McCall // conversion will fit into the target type and will produce the original 3760bab0cdab751248ca389a5592bcb70eac5d39260John McCall // value when converted back to the original type. 3770bab0cdab751248ca389a5592bcb70eac5d39260John McCall case ICK_Boolean_Conversion: // Bools are integers too. 3780bab0cdab751248ca389a5592bcb70eac5d39260John McCall if (!FromType->isIntegralOrUnscopedEnumerationType()) { 3790bab0cdab751248ca389a5592bcb70eac5d39260John McCall // Boolean conversions can be from pointers and pointers to members 3800bab0cdab751248ca389a5592bcb70eac5d39260John McCall // [conv.bool], and those aren't considered narrowing conversions. 3810bab0cdab751248ca389a5592bcb70eac5d39260John McCall return NK_Not_Narrowing; 382d608cdb7c044365cf4e8764ade1e11e99c176078John McCall } // Otherwise, fall through to the integral case. 3830bab0cdab751248ca389a5592bcb70eac5d39260John McCall case ICK_Integral_Conversion: { 3840bab0cdab751248ca389a5592bcb70eac5d39260John McCall assert(FromType->isIntegralOrUnscopedEnumerationType()); 3854d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall assert(ToType->isIntegralOrUnscopedEnumerationType()); 3862de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 3874d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall const unsigned FromWidth = Ctx.getIntWidth(FromType); 3884d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 3894d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall const unsigned ToWidth = Ctx.getIntWidth(ToType); 3904d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall 3914d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (FromWidth > ToWidth || 3924d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall (FromWidth == ToWidth && FromSigned != ToSigned) || 3934d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall (FromSigned && !ToSigned)) { 3944d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // Not all values of FromType can be represented in ToType. 3954d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall llvm::APSInt InitializerValue; 3964d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall const Expr *Initializer = IgnoreNarrowingConversion(Converted); 3974d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 3984d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // Such conversions on variables are always narrowing. 3993023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall return NK_Variable_Narrowing; 4003023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall } 4014d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall bool Narrowing = false; 4024d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (FromWidth < ToWidth) { 4034d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // Negative -> unsigned is narrowing. Otherwise, more bits is never 4044d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // narrowing. 4053023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall if (InitializerValue.isSigned() && InitializerValue.isNegative()) 4064d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall Narrowing = true; 4074d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } else { 4084d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // Add a bit to the InitializerValue so we don't have to worry about 4094d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // signed vs. unsigned comparisons. 4104d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall InitializerValue = InitializerValue.extend( 4114d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall InitializerValue.getBitWidth() + 1); 4124d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // Convert the initializer to and from the target width and signed-ness. 4134d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall llvm::APSInt ConvertedValue = InitializerValue; 4143023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall ConvertedValue = ConvertedValue.trunc(ToWidth); 4154d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall ConvertedValue.setIsSigned(ToSigned); 4164d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 4174d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall ConvertedValue.setIsSigned(InitializerValue.isSigned()); 4184d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall // If the result is different, this was a narrowing conversion. 4194d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (ConvertedValue != InitializerValue) 4203023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall Narrowing = true; 4214d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4224d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (Narrowing) { 4234d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall ConstantType = Initializer->getType(); 4244d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall ConstantValue = APValue(InitializerValue); 4254d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall return NK_Constant_Narrowing; 4264d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4273023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall } 4284d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall return NK_Not_Narrowing; 4294d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4304d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall 4314d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall default: 4323023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall // Other kinds of conversions are not narrowings. 4334d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall return NK_Not_Narrowing; 4344d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4354d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall} 4364d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall 4374d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall/// DebugPrint - Print this standard conversion sequence to standard 4384d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall/// error. Useful for debugging overloading issues. 4394d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCallvoid StandardConversionSequence::DebugPrint() const { 4404d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall raw_ostream &OS = llvm::errs(); 4414d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall bool PrintedSomething = false; 4424d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (First != ICK_Identity) { 4434d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall OS << GetImplicitConversionName(First); 4443023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall PrintedSomething = true; 4454d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4464d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall 4474d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (Second != ICK_Identity) { 4484d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (PrintedSomething) { 4494d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall OS << " -> "; 4504d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4514d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall OS << GetImplicitConversionName(Second); 4524d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall 4534d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (CopyConstructor) { 4544d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall OS << " (by copy constructor)"; 4554d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } else if (DirectBinding) { 456875ab10245d3bf37252dd822aa1616bb0a391095John McCall OS << " (direct reference binding)"; 4570bab0cdab751248ca389a5592bcb70eac5d39260John McCall } else if (ReferenceBinding) { 4580bab0cdab751248ca389a5592bcb70eac5d39260John McCall OS << " (reference binding)"; 4594d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4604d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall PrintedSomething = true; 4614d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4620bab0cdab751248ca389a5592bcb70eac5d39260John McCall 4634d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (Third != ICK_Identity) { 4644d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (PrintedSomething) { 4654d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall OS << " -> "; 4664d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4670bab0cdab751248ca389a5592bcb70eac5d39260John McCall OS << GetImplicitConversionName(Third); 4680bab0cdab751248ca389a5592bcb70eac5d39260John McCall PrintedSomething = true; 469d608cdb7c044365cf4e8764ade1e11e99c176078John McCall } 470d608cdb7c044365cf4e8764ade1e11e99c176078John McCall 4714d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall if (!PrintedSomething) { 4724d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall OS << "No conversions required"; 4734d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 474d608cdb7c044365cf4e8764ade1e11e99c176078John McCall} 475d608cdb7c044365cf4e8764ade1e11e99c176078John McCall 4764d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall/// DebugPrint - Print this user-defined conversion sequence to standard 4774d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall/// error. Useful for debugging overloading issues. 4784d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCallvoid UserDefinedConversionSequence::DebugPrint() const { 4794d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall raw_ostream &OS = llvm::errs(); 480d608cdb7c044365cf4e8764ade1e11e99c176078John McCall if (Before.First || Before.Second || Before.Third) { 4814d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall Before.DebugPrint(); 482d608cdb7c044365cf4e8764ade1e11e99c176078John McCall OS << " -> "; 4834d4e5c1ae83f4510caa486b3ad19de13048f9f04John McCall } 4843023def6bea3af6dbb51eea51f8cb8ea892d26cfJohn McCall if (ConversionFunction) 485cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCall OS << '\'' << *ConversionFunction << '\''; 486cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCall else 4870bab0cdab751248ca389a5592bcb70eac5d39260John McCall OS << "aggregate initialization"; 4880bab0cdab751248ca389a5592bcb70eac5d39260John McCall if (After.First || After.Second || After.Third) { 4890bab0cdab751248ca389a5592bcb70eac5d39260John McCall OS << " -> "; 4900bab0cdab751248ca389a5592bcb70eac5d39260John McCall After.DebugPrint(); 49192e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner } 492d608cdb7c044365cf4e8764ade1e11e99c176078John McCall} 49392e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner 494d608cdb7c044365cf4e8764ade1e11e99c176078John McCall/// DebugPrint - Print this implicit conversion sequence to standard 495c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner/// error. Useful for debugging overloading issues. 496cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCallvoid ImplicitConversionSequence::DebugPrint() const { 497cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCall raw_ostream &OS = llvm::errs(); 4985808ce43f8d7e71f5acacc9ca320268c4f37565aJohn McCall switch (ConversionKind) { 4995808ce43f8d7e71f5acacc9ca320268c4f37565aJohn McCall case StandardConversion: 5005808ce43f8d7e71f5acacc9ca320268c4f37565aJohn McCall OS << "Standard conversion: "; 5010bab0cdab751248ca389a5592bcb70eac5d39260John McCall Standard.DebugPrint(); 5020bab0cdab751248ca389a5592bcb70eac5d39260John McCall break; 5030bab0cdab751248ca389a5592bcb70eac5d39260John McCall case UserDefinedConversion: 50492e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner OS << "User-defined conversion: "; 5050bab0cdab751248ca389a5592bcb70eac5d39260John McCall UserDefined.DebugPrint(); 5060bab0cdab751248ca389a5592bcb70eac5d39260John McCall break; 507755d8497e39071aa24acc173ff07083e3256b8f8John McCall case EllipsisConversion: 5082d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith OS << "Ellipsis conversion"; 5092d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith break; 5102d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case AmbiguousConversion: 5112d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith OS << "Ambiguous conversion"; 5122d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith break; 513d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case BadConversion: 514d608cdb7c044365cf4e8764ade1e11e99c176078John McCall OS << "Bad conversion"; 515875ab10245d3bf37252dd822aa1616bb0a391095John McCall break; 516d608cdb7c044365cf4e8764ade1e11e99c176078John McCall } 517875ab10245d3bf37252dd822aa1616bb0a391095John McCall 518d608cdb7c044365cf4e8764ade1e11e99c176078John McCall OS << "\n"; 519d608cdb7c044365cf4e8764ade1e11e99c176078John McCall} 520d608cdb7c044365cf4e8764ade1e11e99c176078John McCall 5211d2b31710539d705a3850c9fc3aa1804c2a5efeePeter Collingbournevoid AmbiguousConversionSequence::construct() { 522875ab10245d3bf37252dd822aa1616bb0a391095John McCall new (&conversions()) ConversionSet(); 5231246ba6f6801390ffc0e1d4b83a2b45e72283b8fKen Dyck} 5241246ba6f6801390ffc0e1d4b83a2b45e72283b8fKen Dyck 525bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregorvoid AmbiguousConversionSequence::destruct() { 5261246ba6f6801390ffc0e1d4b83a2b45e72283b8fKen Dyck conversions().~ConversionSet(); 527d608cdb7c044365cf4e8764ade1e11e99c176078John McCall} 528d608cdb7c044365cf4e8764ade1e11e99c176078John McCall 529d608cdb7c044365cf4e8764ade1e11e99c176078John McCallvoid 530d608cdb7c044365cf4e8764ade1e11e99c176078John McCallAmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 531d608cdb7c044365cf4e8764ade1e11e99c176078John McCall FromTypePtr = O.FromTypePtr; 532d608cdb7c044365cf4e8764ade1e11e99c176078John McCall ToTypePtr = O.ToTypePtr; 533d608cdb7c044365cf4e8764ade1e11e99c176078John McCall new (&conversions()) ConversionSet(O.conversions()); 534d608cdb7c044365cf4e8764ade1e11e99c176078John McCall} 53592e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner 53692e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Klecknernamespace { 5372d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith // Structure used by OverloadCandidate::DeductionFailureInfo to store 538d608cdb7c044365cf4e8764ade1e11e99c176078John McCall // template parameter and template argument information. 539d608cdb7c044365cf4e8764ade1e11e99c176078John McCall struct DFIParamWithArguments { 540d608cdb7c044365cf4e8764ade1e11e99c176078John McCall TemplateParameter Param; 541d608cdb7c044365cf4e8764ade1e11e99c176078John McCall TemplateArgument FirstArg; 542d608cdb7c044365cf4e8764ade1e11e99c176078John McCall TemplateArgument SecondArg; 54392e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner }; 54492e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner} 5452d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith 546d608cdb7c044365cf4e8764ade1e11e99c176078John McCall/// \brief Convert from Sema's representation of template deduction information 547d608cdb7c044365cf4e8764ade1e11e99c176078John McCall/// to the form used in overload-candidate information. 548755d8497e39071aa24acc173ff07083e3256b8f8John McCallOverloadCandidate::DeductionFailureInfo 5492acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattnerstatic MakeDeductionFailureInfo(ASTContext &Context, 550755d8497e39071aa24acc173ff07083e3256b8f8John McCall Sema::TemplateDeductionResult TDK, 551f742eb0196e1b25c0b71e91da4a2b856d16a1dabChris Lattner TemplateDeductionInfo &Info) { 552755d8497e39071aa24acc173ff07083e3256b8f8John McCall OverloadCandidate::DeductionFailureInfo Result; 553de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall Result.Result = static_cast<unsigned>(TDK); 554d608cdb7c044365cf4e8764ade1e11e99c176078John McCall Result.HasDiagnostic = false; 555755d8497e39071aa24acc173ff07083e3256b8f8John McCall Result.Data = 0; 556755d8497e39071aa24acc173ff07083e3256b8f8John McCall switch (TDK) { 55792e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner case Sema::TDK_Success: 558d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case Sema::TDK_Invalid: 559755d8497e39071aa24acc173ff07083e3256b8f8John McCall case Sema::TDK_InstantiationDepth: 560d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case Sema::TDK_TooManyArguments: 56192e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner case Sema::TDK_TooFewArguments: 56292e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner break; 5632d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith 564d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case Sema::TDK_Incomplete: 565d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case Sema::TDK_InvalidExplicitArguments: 566c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner Result.Data = Info.Param.getOpaqueValue(); 567875ab10245d3bf37252dd822aa1616bb0a391095John McCall break; 568875ab10245d3bf37252dd822aa1616bb0a391095John McCall 5692d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case Sema::TDK_Inconsistent: 5702d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case Sema::TDK_Underqualified: { 5712d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith // FIXME: Should allocate from normal heap so that we can free this later. 5722d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 5732d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Saved->Param = Info.Param; 5742d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Saved->FirstArg = Info.FirstArg; 5752d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Saved->SecondArg = Info.SecondArg; 5762d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Result.Data = Saved; 5772d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith break; 5782d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith } 5792d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith 5802d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case Sema::TDK_SubstitutionFailure: 5812d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Result.Data = Info.take(); 5822d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith if (Info.hasSFINAEDiagnostic()) { 5832d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 5842d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith SourceLocation(), PartialDiagnostic::NullDiagnostic()); 5852d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Info.takeSFINAEDiagnostic(*Diag); 5862d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith Result.HasDiagnostic = true; 5872d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith } 5882d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith break; 5892d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith 5902d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case Sema::TDK_NonDeducedMismatch: 5912d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case Sema::TDK_FailedOverloadResolution: 5922d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith break; 5932d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith } 5942d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith 5952d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith return Result; 5962d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith} 5972d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith 5982d6a5670465cb3f1d811695a9f23e372508240d2Richard Smithvoid OverloadCandidate::DeductionFailureInfo::Destroy() { 5992d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 6002d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith case Sema::TDK_Success: 601e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Invalid: 602e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_InstantiationDepth: 603e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Incomplete: 604e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooManyArguments: 605e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooFewArguments: 6060bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_InvalidExplicitArguments: 6070bab0cdab751248ca389a5592bcb70eac5d39260John McCall break; 6080bab0cdab751248ca389a5592bcb70eac5d39260John McCall 6090bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_Inconsistent: 6100bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_Underqualified: 611e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall // FIXME: Destroy the data? 612e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall Data = 0; 613e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall break; 614e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 615e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_SubstitutionFailure: 616e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall // FIXME: Destroy the template argument list? 617e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall Data = 0; 618e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 619e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall Diag->~PartialDiagnosticAt(); 620e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall HasDiagnostic = false; 621e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall } 622e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall break; 623e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 624e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall // Unhandled 6250bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_NonDeducedMismatch: 6260bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_FailedOverloadResolution: 6270bab0cdab751248ca389a5592bcb70eac5d39260John McCall break; 6280bab0cdab751248ca389a5592bcb70eac5d39260John McCall } 6290bab0cdab751248ca389a5592bcb70eac5d39260John McCall} 6300bab0cdab751248ca389a5592bcb70eac5d39260John McCall 6310bab0cdab751248ca389a5592bcb70eac5d39260John McCallPartialDiagnosticAt * 632de719f7131e1ece5c9d6b5ffe21b83286d29f10fJohn McCallOverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 6330bab0cdab751248ca389a5592bcb70eac5d39260John McCall if (HasDiagnostic) 634de719f7131e1ece5c9d6b5ffe21b83286d29f10fJohn McCall return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 635de719f7131e1ece5c9d6b5ffe21b83286d29f10fJohn McCall return 0; 636de719f7131e1ece5c9d6b5ffe21b83286d29f10fJohn McCall} 6370bab0cdab751248ca389a5592bcb70eac5d39260John McCall 6380bab0cdab751248ca389a5592bcb70eac5d39260John McCallTemplateParameter 6390bab0cdab751248ca389a5592bcb70eac5d39260John McCallOverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 6400bab0cdab751248ca389a5592bcb70eac5d39260John McCall switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 6410bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_Success: 6420bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_Invalid: 643e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_InstantiationDepth: 644e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooManyArguments: 645e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooFewArguments: 646e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_SubstitutionFailure: 647e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall return TemplateParameter(); 648e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 649e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Incomplete: 650e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_InvalidExplicitArguments: 651e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall return TemplateParameter::getFromOpaqueValue(Data); 652e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 653e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Inconsistent: 654e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Underqualified: 655d608cdb7c044365cf4e8764ade1e11e99c176078John McCall return static_cast<DFIParamWithArguments*>(Data)->Param; 656d608cdb7c044365cf4e8764ade1e11e99c176078John McCall 657e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall // Unhandled 658e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_NonDeducedMismatch: 659e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_FailedOverloadResolution: 660e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall break; 661e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall } 662e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 663e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall return TemplateParameter(); 664e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall} 665e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 666e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCallTemplateArgumentList * 667e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCallOverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 668e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 669e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Success: 670e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Invalid: 671e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_InstantiationDepth: 672e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooManyArguments: 673e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooFewArguments: 674e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Incomplete: 675e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_InvalidExplicitArguments: 676e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Inconsistent: 677e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Underqualified: 678e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall return 0; 679e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall 6800bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_SubstitutionFailure: 6810bab0cdab751248ca389a5592bcb70eac5d39260John McCall return static_cast<TemplateArgumentList*>(Data); 6820bab0cdab751248ca389a5592bcb70eac5d39260John McCall 683e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall // Unhandled 6840bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_NonDeducedMismatch: 6850bab0cdab751248ca389a5592bcb70eac5d39260John McCall case Sema::TDK_FailedOverloadResolution: 6860bab0cdab751248ca389a5592bcb70eac5d39260John McCall break; 68792e44d911c748f2ef0d578bbf7b0703fb2ed4d9cReid Kleckner } 6880bab0cdab751248ca389a5592bcb70eac5d39260John McCall 6890bab0cdab751248ca389a5592bcb70eac5d39260John McCall return 0; 6900bab0cdab751248ca389a5592bcb70eac5d39260John McCall} 6910bab0cdab751248ca389a5592bcb70eac5d39260John McCall 692e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCallconst TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 693db27b5fb2d7fc50b8962b2c95e4d43b90c69b1f0Daniel Dunbar switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 694d608cdb7c044365cf4e8764ade1e11e99c176078John McCall case Sema::TDK_Success: 695e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Invalid: 696e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_InstantiationDepth: 697e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Incomplete: 698e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_TooManyArguments: 699db27b5fb2d7fc50b8962b2c95e4d43b90c69b1f0Daniel Dunbar case Sema::TDK_TooFewArguments: 700db27b5fb2d7fc50b8962b2c95e4d43b90c69b1f0Daniel Dunbar case Sema::TDK_InvalidExplicitArguments: 701e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_SubstitutionFailure: 702e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall return 0; 703d608cdb7c044365cf4e8764ade1e11e99c176078John McCall 704e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_Inconsistent: 705db27b5fb2d7fc50b8962b2c95e4d43b90c69b1f0Daniel Dunbar case Sema::TDK_Underqualified: 706db27b5fb2d7fc50b8962b2c95e4d43b90c69b1f0Daniel Dunbar return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 707db27b5fb2d7fc50b8962b2c95e4d43b90c69b1f0Daniel Dunbar 708e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall // Unhandled 709e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_NonDeducedMismatch: 710e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall case Sema::TDK_FailedOverloadResolution: 711e9fd7eb6c67676dc27e84eac429aec4f3be51f26John McCall break; 712875ab10245d3bf37252dd822aa1616bb0a391095John McCall } 713f16aa103d3afd42fbca2ab346f191bf745cec092John McCall 714f16aa103d3afd42fbca2ab346f191bf745cec092John McCall return 0; 715f16aa103d3afd42fbca2ab346f191bf745cec092John McCall} 716f16aa103d3afd42fbca2ab346f191bf745cec092John McCall 717cf2c85e76fdafe7e634810a292321a6c8322483dJohn McCallconst TemplateArgument * 7184c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCallOverloadCandidate::DeductionFailureInfo::getSecondArg() { 719ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 720ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_Success: 721ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_Invalid: 722ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_InstantiationDepth: 723ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_Incomplete: 724ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_TooManyArguments: 725ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_TooFewArguments: 726ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_InvalidExplicitArguments: 727ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_SubstitutionFailure: 728ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall return 0; 729ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall 730ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_Inconsistent: 731ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_Underqualified: 732ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 733ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall 734ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall // Unhandled 735ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_NonDeducedMismatch: 736ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall case Sema::TDK_FailedOverloadResolution: 737ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall break; 7384c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 7394c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7404c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return 0; 7414c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall} 7424c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7435f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnervoid OverloadCandidateSet::destroyCandidates() { 7449cb2cee212d708220c52249ceac4cdd9f2b8aeb0John McCall for (iterator i = begin(), e = end(); i != e; ++i) { 7454c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 7464c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall i->Conversions[ii].~ImplicitConversionSequence(); 7474c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 7484c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall i->DeductionFailure.Destroy(); 7494c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 7504c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall} 7514c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7524c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCallvoid OverloadCandidateSet::clear() { 7534c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall destroyCandidates(); 7544c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall NumInlineSequences = 0; 7554c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Candidates.clear(); 7564c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Functions.clear(); 7575f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner} 7584c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7594c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCallnamespace { 7604c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall class UnbridgedCastsSet { 7614c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall struct Entry { 7624c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Expr **Addr; 7634c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Expr *Saved; 7644c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall }; 7654c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall SmallVector<Entry, 2> Entries; 7664c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7675f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner public: 7689cb2cee212d708220c52249ceac4cdd9f2b8aeb0John McCall void save(Sema &S, Expr *&E) { 7694c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 7704c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Entry entry = { &E, E }; 7714c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall Entries.push_back(entry); 7724c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall E = S.stripARCUnbridgedCast(E); 7734c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 7744c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7754c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall void restore() { 7764c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall for (SmallVectorImpl<Entry>::iterator 7774c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall i = Entries.begin(), e = Entries.end(); i != e; ++i) 7784c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall *i->Addr = i->Saved; 7794c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 7804c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall }; 7814c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall} 7825f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner 7834c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// checkPlaceholderForOverload - Do any interesting placeholder-like 7844c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// preprocessing on the given expression. 7854c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// 7864c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// \param unbridgedCasts a collection to which to add unbridged casts; 7874c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// without this, they will be immediately diagnosed as errors 7884c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// 7894c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// Return true on unrecoverable error. 7904c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCallstatic bool checkPlaceholderForOverload(Sema &S, Expr *&E, 7914c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall UnbridgedCastsSet *unbridgedCasts = 0) { 7924c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 7934c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // We can't handle overloaded expressions here because overload 7944c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // resolution might reasonably tweak them. 7954c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall if (placeholder->getKind() == BuiltinType::Overload) return false; 7964c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 7974c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // If the context potentially accepts unbridged ARC casts, strip 7984c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // the unbridged cast and add it to the collection for later restoration. 7994c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 8009cb2cee212d708220c52249ceac4cdd9f2b8aeb0John McCall unbridgedCasts) { 8014c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall unbridgedCasts->save(S, E); 8024c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return false; 8034c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 8044c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8054c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // Go ahead and check everything else. 8064c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall ExprResult result = S.CheckPlaceholderExpr(E); 807d26bc76c98006609002d9930f8840490e88ac5b5John McCall if (result.isInvalid()) 8084c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return true; 8094c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8104c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall E = result.take(); 8114c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return false; 8124c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 8134c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8144c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // Nothing to do. 8154c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return false; 8164c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall} 8174c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8184c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall/// checkArgPlaceholdersForOverload - Check a set of call operands for 819d26bc76c98006609002d9930f8840490e88ac5b5John McCall/// placeholders. 8204c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCallstatic bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 8214c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall unsigned numArgs, 8224c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall UnbridgedCastsSet &unbridged) { 8234c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall for (unsigned i = 0; i != numArgs; ++i) 8244c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall if (checkPlaceholderForOverload(S, args[i], &unbridged)) 8254c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return true; 8264c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8274c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall return false; 8284c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall} 8294c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8304c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// IsOverload - Determine whether the given New declaration is an 8314c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// overload of the declarations in Old. This routine returns false if 8324c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// New and Old cannot be overloaded, e.g., if New has the same 8334c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// signature as some function in Old (C++ 1.3.10) or if the Old 8344c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// declarations aren't functions (or function templates) at all. When 8354c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// it does return false, MatchedDecl will point to the decl that New 8364c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// cannot be overloaded with. This decl may be a UsingShadowDecl on 8374c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// top of the underlying declaration. 8384c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// 8394c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// Example: Given the following input: 840cec5ebd4a6a89a7023d04cec728fd340b541ed61Eli Friedman// 8414c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// void f(int, float); // #1 8424c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall// void f(int, int); // #2 84363fd408a61ae9b94e8d8a986832f526f7cdbfa84Manman Ren// int f(int, int); // #3 8441d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// 8451d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// When we process #1, there is no previous declaration of "f", 8461d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// so IsOverload will not be used. 8471d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// 8481d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// When we process #2, Old contains only the FunctionDecl for #1. By 8491d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// comparing the parameter types, we see that #1 and #2 are overloaded 8501d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// (since they have different signatures), so this routine returns 8511d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// false; MatchedDecl is unchanged. 8521d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// 8531d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// When we process #3, Old is an overload set containing #1 and #2. We 8541d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// compare the signatures of #3 to #1 (they're overloaded, so we do 8551d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 8561d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// identical (return types of functions are not part of the 8571d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// signature), IsOverload returns false and MatchedDecl will be set to 85863fd408a61ae9b94e8d8a986832f526f7cdbfa84Manman Ren// point to the FunctionDecl for #2. 8591d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// 8601d4fff5551c2347010b955b4337a2aa7d65a050eTimur Iskhodzhanov// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 8610f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov// into a class by a using declaration. The rules for whether to hide 8620f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov// shadow declarations ignore some properties which otherwise figure 8630f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov// into a function template's signature. 8640f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur IskhodzhanovSema::OverloadKind 8650f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur IskhodzhanovSema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 8660f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov NamedDecl *&Match, bool NewIsUsingDecl) { 8670f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov for (LookupResult::iterator I = Old.begin(), E = Old.end(); 8680f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov I != E; ++I) { 8690f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov NamedDecl *OldD = *I; 8700f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov 8710f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov bool OldIsUsingDecl = false; 8720f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov if (isa<UsingShadowDecl>(OldD)) { 8730f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov OldIsUsingDecl = true; 8740f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov 8750f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov // We can always introduce two using declarations into the same 8760f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov // context, even if they have identical signatures. 8770f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov if (NewIsUsingDecl) continue; 8784c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8794c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 8804c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall } 8814c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall 8824c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // If either declaration was introduced by a using declaration, 8834c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // we'll need to use slightly different rules for matching. 8842acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner // Essentially, these rules are the normal rules, except that 8854c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // function templates hide function templates with different 8864c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall // return types or template parameter lists. 8874c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall bool UseMemberUsingDeclRules = 8884c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 8891e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall 8901e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 8911e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 892e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall if (UseMemberUsingDeclRules && OldIsUsingDecl) { 893e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 894e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall continue; 895e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall } 896e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall 8971e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall Match = *I; 8981e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall return Ovl_Match; 8991e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } 9001e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 9011e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 9026ec278d1a354517e20f13a877481453ee7940c78John McCall if (UseMemberUsingDeclRules && OldIsUsingDecl) { 9031e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 904e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall continue; 9051e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } 906956a5a17713deb1b5b27893303c4f308a1bd2a62Micah Villmow 9071e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall Match = *I; 9089cb2cee212d708220c52249ceac4cdd9f2b8aeb0John McCall return Ovl_Match; 9091e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } 9101e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } else if (isa<UsingDecl>(OldD)) { 9111e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // We can overload with these, which can show up when doing 9121e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // redeclaration checks for UsingDecls. 9131e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall assert(Old.getLookupKind() == LookupUsingDeclName); 9141e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } else if (isa<TagDecl>(OldD)) { 915e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // We can always overload with tags by hiding them. 9161e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 9171e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // Optimistically assume that an unresolved using decl will 9181e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // overload; if it doesn't, we'll have to diagnose during 9191e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // template instantiation. 9201e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } else { 9211e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // (C++ 13p1): 9221e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // Only function declarations can be overloaded; object and type 9231e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // declarations cannot be overloaded. 9241e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall Match = *I; 9251e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall return Ovl_NonFunction; 9261e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } 9271e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall } 9281e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall 9291e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall return Ovl_Overload; 9301e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall} 9311e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall 9321e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCallbool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 9331e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall bool UseUsingDeclRules) { 9341e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // If both of the functions are extern "C", then they are not 9351e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // overloads. 936e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall if (Old->isExternC() && New->isExternC()) 937e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall return false; 938e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall 939e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 940e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 941e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall 942e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // C++ [temp.fct]p2: 943e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // A function template can be overloaded with other function templates 944e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // and with normal (non-template) functions. 945e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall if ((OldTemplate == 0) != (NewTemplate == 0)) 946e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall return true; 9471e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall 948956a5a17713deb1b5b27893303c4f308a1bd2a62Micah Villmow // Is the function New an overload of the function Old? 949e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall QualType OldQType = Context.getCanonicalType(Old->getType()); 950e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall QualType NewQType = Context.getCanonicalType(New->getType()); 951e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall 9521e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // Compare the signatures (C++ 1.3.10) of the two functions to 9531e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // determine whether they are overloads. If we find any mismatch 954e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // in the signature, they are overloads. 955f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall 9561e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // If either of these functions is a K&R-style function (no 9571e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // prototype), then we consider them to have matching signatures. 9581e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 9591e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall isa<FunctionNoProtoType>(NewQType.getTypePtr())) 960f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall return false; 961f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall 962f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 963f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 964f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall 9651e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // The signature of a function includes the types of its 9661e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // parameters (C++ 1.3.10), which includes the presence or absence 9671e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // of the ellipsis; see C++ DR 357). 968f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall if (OldQType != NewQType && 969f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall (OldType->getNumArgs() != NewType->getNumArgs() || 9706ec278d1a354517e20f13a877481453ee7940c78John McCall OldType->isVariadic() != NewType->isVariadic() || 971f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall !FunctionArgTypesAreEqual(OldType, NewType))) 972e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall return true; 9731e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall 974f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // C++ [temp.over.link]p4: 975f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // The signature of a function template consists of its function 9761e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // signature, its return type and its template parameter list. The names 9771e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // of the template parameters are significant only for establishing the 978f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // relationship between the template parameters and the rest of the 9791e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // signature. 9801e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // 981f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // We check the return type and template parameter lists for function 982f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // templates first; the remaining checks follow. 983f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // 984f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // However, we don't consider either of these when deciding whether 9851e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // a member introduced by a shadow declaration is hidden. 9861e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall if (!UseUsingDeclRules && NewTemplate && 987f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 988f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall OldTemplate->getTemplateParameters(), 9891e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall false, TPL_TemplateMatch) || 9901e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall OldType->getResultType() != NewType->getResultType())) 9911e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall return true; 992f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall 993f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // If the function is a class member, its signature includes the 994f3bbb155beb69cdad1c6b0472bc0ca20cece6c50John McCall // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 9951e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // 9961e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall // As part of this, also check whether one of the member functions 997e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // is static, in which case they are not overloads (C++ 998e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // 13.1p2). While not part of the definition of the signature, 999e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // this check is important to determine whether these functions 1000e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall // can be overloaded. 1001e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1002e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1003e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall if (OldMethod && NewMethod && 10041e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall !OldMethod->isStatic() && !NewMethod->isStatic() && 1005956a5a17713deb1b5b27893303c4f308a1bd2a62Micah Villmow (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 1006e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 1007e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall if (!UseUsingDeclRules && 1008e2b45e2a43ae46bc00026b63ba7c04ef2b78c3ffJohn McCall OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 10091e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall (OldMethod->getRefQualifier() == RQ_None || 10101e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall NewMethod->getRefQualifier() == RQ_None)) { 10115cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // C++0x [over.load]p2: 10125cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // - Member function declarations with the same name and the same 10135cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // parameter-type-list as well as member function template 10149cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner // declarations with the same name, the same parameter-type-list, and 10155cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // the same template parameter lists cannot be overloaded if any of 10162acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner // them, but not all, have a ref-qualifier (8.3.5). 10175cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1018da549e8995c447542d5631b8b67fcc3a9582797aJay Foad << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1019e76872e81ea32fbc863d8d7ef6eadc91a8f8673bNick Lewycky Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1020c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling } 1021c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling 102272390b39c545426023ec104afe8706395d732badBill Wendling return true; 10235cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall } 10245cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 10255cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // The signatures match; this is not an overload. 10269cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner return false; 10275cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall} 10282acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner 10298b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner/// \brief Checks availability of the function depending on the current 1030e76872e81ea32fbc863d8d7ef6eadc91a8f8673bNick Lewycky/// function context. Inside an unavailable function, unavailability is ignored. 1031c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling/// 1032c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling/// \returns true if \arg FD is unavailable and current context is inside 103372390b39c545426023ec104afe8706395d732badBill Wendling/// an available function, false otherwise. 10345cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCallbool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 10355cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 10365cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall} 10379cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner 10385cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// \brief Tries a user-defined conversion from From to ToType. 10392acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner/// 10408b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner/// Produces an implicit conversion sequence for when a standard conversion 1041e76872e81ea32fbc863d8d7ef6eadc91a8f8673bNick Lewycky/// is not an option. See TryImplicitConversion for more information. 1042c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendlingstatic ImplicitConversionSequence 1043c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill WendlingTryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 104472390b39c545426023ec104afe8706395d732badBill Wendling bool SuppressUserConversions, 10455cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool AllowExplicit, 10465cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool InOverloadResolution, 10475cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool CStyle, 10485cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool AllowObjCWritebackConversion) { 10495cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ImplicitConversionSequence ICS; 10500f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth 10515cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall if (SuppressUserConversions) { 1052ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall // We're not in the case above, so there is no conversion that 1053bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall // we can perform. 1054bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 10555cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall return ICS; 10565cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall } 10575cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 10585cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // Attempt user-defined conversion. 10595cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall OverloadCandidateSet Conversions(From->getExprLoc()); 10605cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall OverloadingResult UserDefResult 10613030eb82593097502469a8b3fc26112c79c75605John McCall = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 10623030eb82593097502469a8b3fc26112c79c75605John McCall AllowExplicit); 1063355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall 1064355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall if (UserDefResult == OR_Success) { 10655cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.setUserDefined(); 10663030eb82593097502469a8b3fc26112c79c75605John McCall // C++ [over.ics.user]p4: 106704e517650569598e847c2ab609672e6df93effe5Richard Smith // A conversion of an expression of class type to the same class 10683030eb82593097502469a8b3fc26112c79c75605John McCall // type is given Exact Match rank, and a conversion of an 106904e517650569598e847c2ab609672e6df93effe5Richard Smith // expression of class type to a base class of that type is 107004e517650569598e847c2ab609672e6df93effe5Richard Smith // given Conversion rank, in spite of the fact that a copy 1071173d51286bcaff4b6b76eebf6542d3b1311142e2Anders Carlsson // constructor (i.e., a user-defined conversion function) is 1072173d51286bcaff4b6b76eebf6542d3b1311142e2Anders Carlsson // called for those cases. 1073173d51286bcaff4b6b76eebf6542d3b1311142e2Anders Carlsson if (CXXConstructorDecl *Constructor 1074355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1075355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall QualType FromCanon 1076355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 10770502a224984a26087ea4d64e8e5d2dd4dca432f6John McCall QualType ToCanon 1078355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 10790502a224984a26087ea4d64e8e5d2dd4dca432f6John McCall if (Constructor->isCopyConstructor() && 1080c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1081c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover // Turn this into a "standard" conversion sequence, so that it 1082c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover // gets ranked with standard conversion sequences. 1083355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.setStandard(); 1084355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.Standard.setAsIdentityConversion(); 1085355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.Standard.setFromType(From->getType()); 1086355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.Standard.setAllToTypes(ToType); 1087355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.Standard.CopyConstructor = Constructor; 1088355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall if (ToCanon != FromCanon) 1089355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.Standard.Second = ICK_Derived_To_Base; 1090355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall } 1091355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall } 1092355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall 1093355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // C++ [over.best.ics]p4: 1094355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // However, when considering the argument of a user-defined 1095355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // conversion function that is a candidate by 13.3.1.3 when 1096355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // invoked for the copying of the temporary in the second step 1097355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1098355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // 13.3.1.6 in all cases, only standard conversion sequences and 1099355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // ellipsis conversion sequences are allowed. 1100355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall if (SuppressUserConversions && ICS.isUserDefined()) { 1101355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1102355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall } 1103355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1104355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.setAmbiguous(); 110504e517650569598e847c2ab609672e6df93effe5Richard Smith ICS.Ambiguous.setFromType(From->getType()); 110604e517650569598e847c2ab609672e6df93effe5Richard Smith ICS.Ambiguous.setToType(ToType); 1107355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1108355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall Cand != Conversions.end(); ++Cand) 1109173d51286bcaff4b6b76eebf6542d3b1311142e2Anders Carlsson if (Cand->Viable) 11105cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.Ambiguous.addConversion(Cand->Function); 11115cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall } else { 1112355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 11135cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall } 11145cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 11155cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall return ICS; 11165cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall} 11175cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 11185cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// TryImplicitConversion - Attempt to perform an implicit conversion 11195cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// from the given expression (Expr) to the given type (ToType). This 11205cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// function returns an implicit conversion sequence that can be used 11215cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// to perform the initialization. Given 11225cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// 11235cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// void f(float f); 11245cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// void g(int i) { f(i); } 11250502a224984a26087ea4d64e8e5d2dd4dca432f6John McCall/// 1126355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall/// this routine would produce an implicit conversion sequence to 1127c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover/// describe the initialization of f from i, which will be a standard 1128c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1129355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall/// 4.1) followed by a floating-integral conversion (C++ 4.9). 11305cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall// 11315cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// Note that this routine only determines how the conversion can be 11325cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// performed; it does not actually perform the conversion. As such, 11335cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// it will not produce any diagnostics if no conversion is available, 11345cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// but will instead return an implicit conversion sequence of kind 11355cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// "BadConversion". 11365cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// 11375cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// If @p SuppressUserConversions, then user-defined conversions are 11385cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// not permitted. 11395cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// If @p AllowExplicit, then explicit user-defined conversions are 11405cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// permitted. 11415cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// 11425cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 11435cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// writeback conversion, which allows __autoreleasing id* parameters to 11445cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall/// be initialized with __strong id* or __weak id* arguments. 11455cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCallstatic ImplicitConversionSequence 11465cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCallTryImplicitConversion(Sema &S, Expr *From, QualType ToType, 11470f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth bool SuppressUserConversions, 1148355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall bool AllowExplicit, 11490f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth bool InOverloadResolution, 1150eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman bool CStyle, 1151eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman bool AllowObjCWritebackConversion) { 1152eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman ImplicitConversionSequence ICS; 1153eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1154eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1155eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman ICS.setStandard(); 1156eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman return ICS; 1157eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman } 11580f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth 1159eb43f4a8f133c2bc510ae136a556e92b68a6ff44Eli Friedman if (!S.getLangOpts().CPlusPlus) { 1160355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 11615cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall return ICS; 11625cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall } 11635cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 11645cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // C++ [over.ics.user]p4: 11655cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // A conversion of an expression of class type to the same class 11665cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // type is given Exact Match rank, and a conversion of an 1167355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // expression of class type to a base class of that type is 11685cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // given Conversion rank, in spite of the fact that a copy/move 11695cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // constructor (i.e., a user-defined conversion function) is 11705cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // called for those cases. 11715cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall QualType FromType = From->getType(); 11720502a224984a26087ea4d64e8e5d2dd4dca432f6John McCall if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 11735cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall (S.Context.hasSameUnqualifiedType(FromType, ToType) || 11745cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall S.IsDerivedFrom(FromType, ToType))) { 1175bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall ICS.setStandard(); 11765cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.Standard.setAsIdentityConversion(); 11775cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.Standard.setFromType(FromType); 11785cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.Standard.setAllToTypes(ToType); 11795cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 11805cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // We don't actually check at this point whether there is a valid 11815cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // copy/move constructor, since overloading just assumes that it 11825cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // exists. When we actually perform initialization, we'll find the 1183355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall // appropriate constructor to copy the returned object, if needed. 11845cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.Standard.CopyConstructor = 0; 11855cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 11865cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall // Determine whether this is considered a derived-to-base conversion. 11875cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 11885cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall ICS.Standard.Second = ICK_Derived_To_Base; 1189355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall 11905cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall return ICS; 11910502a224984a26087ea4d64e8e5d2dd4dca432f6John McCall } 11925cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 11935cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 11945cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall AllowExplicit, InOverloadResolution, CStyle, 11955cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall AllowObjCWritebackConversion); 1196bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall} 11975cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall 1198355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCallImplicitConversionSequence 11995cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCallSema::TryImplicitConversion(Expr *From, QualType ToType, 12005cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool SuppressUserConversions, 12015cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool AllowExplicit, 12025cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall bool InOverloadResolution, 120320bb175cb8ae5844034828db094fb948c0e3454aJohn McCall bool CStyle, 120420bb175cb8ae5844034828db094fb948c0e3454aJohn McCall bool AllowObjCWritebackConversion) { 120520bb175cb8ae5844034828db094fb948c0e3454aJohn McCall return clang::TryImplicitConversion(*this, From, ToType, 120620bb175cb8ae5844034828db094fb948c0e3454aJohn McCall SuppressUserConversions, AllowExplicit, 120704e517650569598e847c2ab609672e6df93effe5Richard Smith InOverloadResolution, CStyle, 120804e517650569598e847c2ab609672e6df93effe5Richard Smith AllowObjCWritebackConversion); 120904e517650569598e847c2ab609672e6df93effe5Richard Smith} 121004e517650569598e847c2ab609672e6df93effe5Richard Smith 121120bb175cb8ae5844034828db094fb948c0e3454aJohn McCall/// PerformImplicitConversion - Perform an implicit conversion of the 121220bb175cb8ae5844034828db094fb948c0e3454aJohn McCall/// expression From to the type ToType. Returns the 121320bb175cb8ae5844034828db094fb948c0e3454aJohn McCall/// converted expression. Flavor is the kind of conversion we're 121420bb175cb8ae5844034828db094fb948c0e3454aJohn McCall/// performing, used in the error message. If @p AllowExplicit, 121520bb175cb8ae5844034828db094fb948c0e3454aJohn McCall/// explicit user-defined conversions are permitted. 121620bb175cb8ae5844034828db094fb948c0e3454aJohn McCallExprResult 121720bb175cb8ae5844034828db094fb948c0e3454aJohn McCallSema::PerformImplicitConversion(Expr *From, QualType ToType, 121820bb175cb8ae5844034828db094fb948c0e3454aJohn McCall AssignmentAction Action, bool AllowExplicit) { 121920bb175cb8ae5844034828db094fb948c0e3454aJohn McCall ImplicitConversionSequence ICS; 122020bb175cb8ae5844034828db094fb948c0e3454aJohn McCall return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 122120bb175cb8ae5844034828db094fb948c0e3454aJohn McCall} 122220bb175cb8ae5844034828db094fb948c0e3454aJohn McCall 122304e517650569598e847c2ab609672e6df93effe5Richard SmithExprResult 122420bb175cb8ae5844034828db094fb948c0e3454aJohn McCallSema::PerformImplicitConversion(Expr *From, QualType ToType, 122520bb175cb8ae5844034828db094fb948c0e3454aJohn McCall AssignmentAction Action, bool AllowExplicit, 122620bb175cb8ae5844034828db094fb948c0e3454aJohn McCall ImplicitConversionSequence& ICS) { 122720bb175cb8ae5844034828db094fb948c0e3454aJohn McCall if (checkPlaceholderForOverload(*this, From)) 122820bb175cb8ae5844034828db094fb948c0e3454aJohn McCall return ExprError(); 122920bb175cb8ae5844034828db094fb948c0e3454aJohn McCall 123020bb175cb8ae5844034828db094fb948c0e3454aJohn McCall // Objective-C ARC: Determine whether we will allow the writeback conversion. 123120bb175cb8ae5844034828db094fb948c0e3454aJohn McCall bool AllowObjCWritebackConversion 123220bb175cb8ae5844034828db094fb948c0e3454aJohn McCall = getLangOpts().ObjCAutoRefCount && 123320bb175cb8ae5844034828db094fb948c0e3454aJohn McCall (Action == AA_Passing || Action == AA_Sending); 123420bb175cb8ae5844034828db094fb948c0e3454aJohn McCall 123520bb175cb8ae5844034828db094fb948c0e3454aJohn McCall ICS = clang::TryImplicitConversion(*this, From, ToType, 1236bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall /*SuppressUserConversions=*/false, 123720bb175cb8ae5844034828db094fb948c0e3454aJohn McCall AllowExplicit, 123820bb175cb8ae5844034828db094fb948c0e3454aJohn McCall /*InOverloadResolution=*/false, 123920bb175cb8ae5844034828db094fb948c0e3454aJohn McCall /*CStyle=*/false, 124020bb175cb8ae5844034828db094fb948c0e3454aJohn McCall AllowObjCWritebackConversion); 124104e517650569598e847c2ab609672e6df93effe5Richard Smith return PerformImplicitConversion(From, ToType, ICS, Action); 124220bb175cb8ae5844034828db094fb948c0e3454aJohn McCall} 124320bb175cb8ae5844034828db094fb948c0e3454aJohn McCall 124420bb175cb8ae5844034828db094fb948c0e3454aJohn McCall/// \brief Determine whether the conversion from FromType to ToType is a valid 124504e517650569598e847c2ab609672e6df93effe5Richard Smith/// conversion that strips "noreturn" off the nested function type. 124604e517650569598e847c2ab609672e6df93effe5Richard Smithbool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 124704e517650569598e847c2ab609672e6df93effe5Richard Smith QualType &ResultTy) { 124804e517650569598e847c2ab609672e6df93effe5Richard Smith if (Context.hasSameUnqualifiedType(FromType, ToType)) 124904e517650569598e847c2ab609672e6df93effe5Richard Smith return false; 125020bb175cb8ae5844034828db094fb948c0e3454aJohn McCall 125120bb175cb8ae5844034828db094fb948c0e3454aJohn McCall // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 125220bb175cb8ae5844034828db094fb948c0e3454aJohn McCall // where F adds one of the following at most once: 12537edf9e38b91917b661277601c0e448eef0eb2b56Richard Smith // - a pointer 125420bb175cb8ae5844034828db094fb948c0e3454aJohn McCall // - a member pointer 125520bb175cb8ae5844034828db094fb948c0e3454aJohn McCall // - a block pointer 125620bb175cb8ae5844034828db094fb948c0e3454aJohn McCall CanQualType CanTo = Context.getCanonicalType(ToType); 125720bb175cb8ae5844034828db094fb948c0e3454aJohn McCall CanQualType CanFrom = Context.getCanonicalType(FromType); 125820bb175cb8ae5844034828db094fb948c0e3454aJohn McCall Type::TypeClass TyClass = CanTo->getTypeClass(); 125920bb175cb8ae5844034828db094fb948c0e3454aJohn McCall if (TyClass != CanFrom->getTypeClass()) return false; 1260b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1261b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (TyClass == Type::Pointer) { 1262b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1263b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1264b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } else if (TyClass == Type::BlockPointer) { 1265b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1266b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1267b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } else if (TyClass == Type::MemberPointer) { 1268b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1269b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1270b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } else { 1271b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1272b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1273b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1274b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith TyClass = CanTo->getTypeClass(); 1275b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (TyClass != CanFrom->getTypeClass()) return false; 1276b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1277b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1278b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1279b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1280b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1281b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1282b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (!EInfo.getNoReturn()) return false; 1283b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1284b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1285b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith assert(QualType(FromFn, 0).isCanonical()); 1286b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (QualType(FromFn, 0) != CanTo) return false; 1287b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1288b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith ResultTy = ToType; 1289b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return true; 1290b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith} 1291b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1292b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// \brief Determine whether the conversion from FromType to ToType is a valid 1293b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// vector conversion. 1294b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// 1295b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// \param ICK Will be set to the vector conversion kind, if this is a vector 1296b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// conversion. 1297b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smithstatic bool IsVectorConversion(ASTContext &Context, QualType FromType, 1298b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith QualType ToType, ImplicitConversionKind &ICK) { 1299b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // We need at least one of these types to be a vector type to have a vector 1300b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // conversion. 1301b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (!ToType->isVectorType() && !FromType->isVectorType()) 1302b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1303b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1304b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // Identical types require no conversions. 1305b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (Context.hasSameUnqualifiedType(FromType, ToType)) 1306b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1307b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1308b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // There are no conversions between extended vector types, only identity. 1309b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (ToType->isExtVectorType()) { 1310b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // There are no conversions between extended vector types other than the 1311b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // identity conversion. 1312b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (FromType->isExtVectorType()) 1313b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1314b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1315b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // Vector splat from any arithmetic type to a vector. 1316b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (FromType->isArithmeticType()) { 1317b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith ICK = ICK_Vector_Splat; 1318b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return true; 1319b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1320b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1321b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1322b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // We can perform the conversion between vector types in the following cases: 1323b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // 1)vector types are equivalent AltiVec and GCC vector types 1324b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // 2)lax vector conversions are permitted and the vector types are of the 1325b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // same size 1326b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (ToType->isVectorType() && FromType->isVectorType()) { 1327b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (Context.areCompatibleVectorTypes(FromType, ToType) || 1328b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith (Context.getLangOpts().LaxVectorConversions && 1329b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1330b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith ICK = ICK_Vector_Conversion; 1331b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return true; 1332b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1333b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1334b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1335b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1336b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith} 1337b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1338b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smithstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1339b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith bool InOverloadResolution, 1340b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith StandardConversionSequence &SCS, 1341b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith bool CStyle); 1342b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1343b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// IsStandardConversion - Determines whether there is a standard 1344b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1345b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// expression From to the type ToType. Standard conversion sequences 1346b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// only consider non-class types; for conversions that involve class 1347b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// types, use TryImplicitConversion. If a conversion exists, SCS will 1348b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// contain the standard conversion sequence required to perform this 1349b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// conversion and this routine will return true. Otherwise, this 1350b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith/// routine will return false and the value of SCS is unspecified. 1351b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smithstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1352b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith bool InOverloadResolution, 1353b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith StandardConversionSequence &SCS, 1354b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith bool CStyle, 1355b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith bool AllowObjCWritebackConversion) { 1356b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith QualType FromType = From->getType(); 1357b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1358b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // Standard conversions (C++ [conv]) 1359b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith SCS.setAsIdentityConversion(); 1360b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith SCS.DeprecatedStringLiteralToCharPtr = false; 1361b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith SCS.IncompatibleObjC = false; 1362b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith SCS.setFromType(FromType); 1363b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith SCS.CopyConstructor = 0; 1364b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1365b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // There are no standard conversions for class types in C++, so 1366b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // abort early. When overloading in C, however, we do permit 1367b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (FromType->isRecordType() || ToType->isRecordType()) { 1368b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (S.getLangOpts().CPlusPlus) 1369b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith return false; 1370b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1371b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // When we're overloading in C, we allow, as standard conversions, 1372b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith } 1373b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1374b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // The first conversion can be an lvalue-to-rvalue conversion, 1375b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // array-to-pointer conversion, or function-to-pointer conversion 1376b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // (C++ 4p1). 1377b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1378b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (FromType == S.Context.OverloadTy) { 1379b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith DeclAccessPair AccessPair; 1380b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (FunctionDecl *Fn 1381b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1382b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith AccessPair)) { 1383b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // We were able to resolve the address of the overloaded function, 1384b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // so we can convert to the type of that function. 1385b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith FromType = Fn->getType(); 1386b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith 1387b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // we can sometimes resolve &foo<int> regardless of ToType, so check 1388b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // if the type matches (identity) or we are converting to bool 1389b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (!S.Context.hasSameUnqualifiedType( 1390b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1391b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith QualType resultTy; 1392b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith // if the function type matches except for [[noreturn]], it's ok 1393b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith if (!S.IsNoReturnConversion(FromType, 1394b80a16eadd0dacabfc1c32412e243ccb99dd664dRichard Smith S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1395 // otherwise, only a boolean conversion is standard 1396 if (!ToType->isBooleanType()) 1397 return false; 1398 } 1399 1400 // Check if the "from" expression is taking the address of an overloaded 1401 // function and recompute the FromType accordingly. Take advantage of the 1402 // fact that non-static member functions *must* have such an address-of 1403 // expression. 1404 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1405 if (Method && !Method->isStatic()) { 1406 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1407 "Non-unary operator on non-static member address"); 1408 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1409 == UO_AddrOf && 1410 "Non-address-of operator on non-static member address"); 1411 const Type *ClassType 1412 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1413 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1414 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1415 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1416 UO_AddrOf && 1417 "Non-address-of operator for overloaded function expression"); 1418 FromType = S.Context.getPointerType(FromType); 1419 } 1420 1421 // Check that we've computed the proper type after overload resolution. 1422 assert(S.Context.hasSameType( 1423 FromType, 1424 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1425 } else { 1426 return false; 1427 } 1428 } 1429 // Lvalue-to-rvalue conversion (C++11 4.1): 1430 // A glvalue (3.10) of a non-function, non-array type T can 1431 // be converted to a prvalue. 1432 bool argIsLValue = From->isGLValue(); 1433 if (argIsLValue && 1434 !FromType->isFunctionType() && !FromType->isArrayType() && 1435 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1436 SCS.First = ICK_Lvalue_To_Rvalue; 1437 1438 // C11 6.3.2.1p2: 1439 // ... if the lvalue has atomic type, the value has the non-atomic version 1440 // of the type of the lvalue ... 1441 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1442 FromType = Atomic->getValueType(); 1443 1444 // If T is a non-class type, the type of the rvalue is the 1445 // cv-unqualified version of T. Otherwise, the type of the rvalue 1446 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1447 // just strip the qualifiers because they don't matter. 1448 FromType = FromType.getUnqualifiedType(); 1449 } else if (FromType->isArrayType()) { 1450 // Array-to-pointer conversion (C++ 4.2) 1451 SCS.First = ICK_Array_To_Pointer; 1452 1453 // An lvalue or rvalue of type "array of N T" or "array of unknown 1454 // bound of T" can be converted to an rvalue of type "pointer to 1455 // T" (C++ 4.2p1). 1456 FromType = S.Context.getArrayDecayedType(FromType); 1457 1458 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1459 // This conversion is deprecated. (C++ D.4). 1460 SCS.DeprecatedStringLiteralToCharPtr = true; 1461 1462 // For the purpose of ranking in overload resolution 1463 // (13.3.3.1.1), this conversion is considered an 1464 // array-to-pointer conversion followed by a qualification 1465 // conversion (4.4). (C++ 4.2p2) 1466 SCS.Second = ICK_Identity; 1467 SCS.Third = ICK_Qualification; 1468 SCS.QualificationIncludesObjCLifetime = false; 1469 SCS.setAllToTypes(FromType); 1470 return true; 1471 } 1472 } else if (FromType->isFunctionType() && argIsLValue) { 1473 // Function-to-pointer conversion (C++ 4.3). 1474 SCS.First = ICK_Function_To_Pointer; 1475 1476 // An lvalue of function type T can be converted to an rvalue of 1477 // type "pointer to T." The result is a pointer to the 1478 // function. (C++ 4.3p1). 1479 FromType = S.Context.getPointerType(FromType); 1480 } else { 1481 // We don't require any conversions for the first step. 1482 SCS.First = ICK_Identity; 1483 } 1484 SCS.setToType(0, FromType); 1485 1486 // The second conversion can be an integral promotion, floating 1487 // point promotion, integral conversion, floating point conversion, 1488 // floating-integral conversion, pointer conversion, 1489 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1490 // For overloading in C, this can also be a "compatible-type" 1491 // conversion. 1492 bool IncompatibleObjC = false; 1493 ImplicitConversionKind SecondICK = ICK_Identity; 1494 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1495 // The unqualified versions of the types are the same: there's no 1496 // conversion to do. 1497 SCS.Second = ICK_Identity; 1498 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1499 // Integral promotion (C++ 4.5). 1500 SCS.Second = ICK_Integral_Promotion; 1501 FromType = ToType.getUnqualifiedType(); 1502 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1503 // Floating point promotion (C++ 4.6). 1504 SCS.Second = ICK_Floating_Promotion; 1505 FromType = ToType.getUnqualifiedType(); 1506 } else if (S.IsComplexPromotion(FromType, ToType)) { 1507 // Complex promotion (Clang extension) 1508 SCS.Second = ICK_Complex_Promotion; 1509 FromType = ToType.getUnqualifiedType(); 1510 } else if (ToType->isBooleanType() && 1511 (FromType->isArithmeticType() || 1512 FromType->isAnyPointerType() || 1513 FromType->isBlockPointerType() || 1514 FromType->isMemberPointerType() || 1515 FromType->isNullPtrType())) { 1516 // Boolean conversions (C++ 4.12). 1517 SCS.Second = ICK_Boolean_Conversion; 1518 FromType = S.Context.BoolTy; 1519 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1520 ToType->isIntegralType(S.Context)) { 1521 // Integral conversions (C++ 4.7). 1522 SCS.Second = ICK_Integral_Conversion; 1523 FromType = ToType.getUnqualifiedType(); 1524 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1525 // Complex conversions (C99 6.3.1.6) 1526 SCS.Second = ICK_Complex_Conversion; 1527 FromType = ToType.getUnqualifiedType(); 1528 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1529 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1530 // Complex-real conversions (C99 6.3.1.7) 1531 SCS.Second = ICK_Complex_Real; 1532 FromType = ToType.getUnqualifiedType(); 1533 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1534 // Floating point conversions (C++ 4.8). 1535 SCS.Second = ICK_Floating_Conversion; 1536 FromType = ToType.getUnqualifiedType(); 1537 } else if ((FromType->isRealFloatingType() && 1538 ToType->isIntegralType(S.Context)) || 1539 (FromType->isIntegralOrUnscopedEnumerationType() && 1540 ToType->isRealFloatingType())) { 1541 // Floating-integral conversions (C++ 4.9). 1542 SCS.Second = ICK_Floating_Integral; 1543 FromType = ToType.getUnqualifiedType(); 1544 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1545 SCS.Second = ICK_Block_Pointer_Conversion; 1546 } else if (AllowObjCWritebackConversion && 1547 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1548 SCS.Second = ICK_Writeback_Conversion; 1549 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1550 FromType, IncompatibleObjC)) { 1551 // Pointer conversions (C++ 4.10). 1552 SCS.Second = ICK_Pointer_Conversion; 1553 SCS.IncompatibleObjC = IncompatibleObjC; 1554 FromType = FromType.getUnqualifiedType(); 1555 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1556 InOverloadResolution, FromType)) { 1557 // Pointer to member conversions (4.11). 1558 SCS.Second = ICK_Pointer_Member; 1559 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1560 SCS.Second = SecondICK; 1561 FromType = ToType.getUnqualifiedType(); 1562 } else if (!S.getLangOpts().CPlusPlus && 1563 S.Context.typesAreCompatible(ToType, FromType)) { 1564 // Compatible conversions (Clang extension for C function overloading) 1565 SCS.Second = ICK_Compatible_Conversion; 1566 FromType = ToType.getUnqualifiedType(); 1567 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1568 // Treat a conversion that strips "noreturn" as an identity conversion. 1569 SCS.Second = ICK_NoReturn_Adjustment; 1570 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1571 InOverloadResolution, 1572 SCS, CStyle)) { 1573 SCS.Second = ICK_TransparentUnionConversion; 1574 FromType = ToType; 1575 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1576 CStyle)) { 1577 // tryAtomicConversion has updated the standard conversion sequence 1578 // appropriately. 1579 return true; 1580 } else { 1581 // No second conversion required. 1582 SCS.Second = ICK_Identity; 1583 } 1584 SCS.setToType(1, FromType); 1585 1586 QualType CanonFrom; 1587 QualType CanonTo; 1588 // The third conversion can be a qualification conversion (C++ 4p1). 1589 bool ObjCLifetimeConversion; 1590 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1591 ObjCLifetimeConversion)) { 1592 SCS.Third = ICK_Qualification; 1593 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1594 FromType = ToType; 1595 CanonFrom = S.Context.getCanonicalType(FromType); 1596 CanonTo = S.Context.getCanonicalType(ToType); 1597 } else { 1598 // No conversion required 1599 SCS.Third = ICK_Identity; 1600 1601 // C++ [over.best.ics]p6: 1602 // [...] Any difference in top-level cv-qualification is 1603 // subsumed by the initialization itself and does not constitute 1604 // a conversion. [...] 1605 CanonFrom = S.Context.getCanonicalType(FromType); 1606 CanonTo = S.Context.getCanonicalType(ToType); 1607 if (CanonFrom.getLocalUnqualifiedType() 1608 == CanonTo.getLocalUnqualifiedType() && 1609 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1610 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1611 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1612 FromType = ToType; 1613 CanonFrom = CanonTo; 1614 } 1615 } 1616 SCS.setToType(2, FromType); 1617 1618 // If we have not converted the argument type to the parameter type, 1619 // this is a bad conversion sequence. 1620 if (CanonFrom != CanonTo) 1621 return false; 1622 1623 return true; 1624} 1625 1626static bool 1627IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1628 QualType &ToType, 1629 bool InOverloadResolution, 1630 StandardConversionSequence &SCS, 1631 bool CStyle) { 1632 1633 const RecordType *UT = ToType->getAsUnionType(); 1634 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1635 return false; 1636 // The field to initialize within the transparent union. 1637 RecordDecl *UD = UT->getDecl(); 1638 // It's compatible if the expression matches any of the fields. 1639 for (RecordDecl::field_iterator it = UD->field_begin(), 1640 itend = UD->field_end(); 1641 it != itend; ++it) { 1642 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1643 CStyle, /*ObjCWritebackConversion=*/false)) { 1644 ToType = it->getType(); 1645 return true; 1646 } 1647 } 1648 return false; 1649} 1650 1651/// IsIntegralPromotion - Determines whether the conversion from the 1652/// expression From (whose potentially-adjusted type is FromType) to 1653/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1654/// sets PromotedType to the promoted type. 1655bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1656 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1657 // All integers are built-in. 1658 if (!To) { 1659 return false; 1660 } 1661 1662 // An rvalue of type char, signed char, unsigned char, short int, or 1663 // unsigned short int can be converted to an rvalue of type int if 1664 // int can represent all the values of the source type; otherwise, 1665 // the source rvalue can be converted to an rvalue of type unsigned 1666 // int (C++ 4.5p1). 1667 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1668 !FromType->isEnumeralType()) { 1669 if (// We can promote any signed, promotable integer type to an int 1670 (FromType->isSignedIntegerType() || 1671 // We can promote any unsigned integer type whose size is 1672 // less than int to an int. 1673 (!FromType->isSignedIntegerType() && 1674 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1675 return To->getKind() == BuiltinType::Int; 1676 } 1677 1678 return To->getKind() == BuiltinType::UInt; 1679 } 1680 1681 // C++11 [conv.prom]p3: 1682 // A prvalue of an unscoped enumeration type whose underlying type is not 1683 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1684 // following types that can represent all the values of the enumeration 1685 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1686 // unsigned int, long int, unsigned long int, long long int, or unsigned 1687 // long long int. If none of the types in that list can represent all the 1688 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1689 // type can be converted to an rvalue a prvalue of the extended integer type 1690 // with lowest integer conversion rank (4.13) greater than the rank of long 1691 // long in which all the values of the enumeration can be represented. If 1692 // there are two such extended types, the signed one is chosen. 1693 // C++11 [conv.prom]p4: 1694 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1695 // can be converted to a prvalue of its underlying type. Moreover, if 1696 // integral promotion can be applied to its underlying type, a prvalue of an 1697 // unscoped enumeration type whose underlying type is fixed can also be 1698 // converted to a prvalue of the promoted underlying type. 1699 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1700 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1701 // provided for a scoped enumeration. 1702 if (FromEnumType->getDecl()->isScoped()) 1703 return false; 1704 1705 // We can perform an integral promotion to the underlying type of the enum, 1706 // even if that's not the promoted type. 1707 if (FromEnumType->getDecl()->isFixed()) { 1708 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1709 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1710 IsIntegralPromotion(From, Underlying, ToType); 1711 } 1712 1713 // We have already pre-calculated the promotion type, so this is trivial. 1714 if (ToType->isIntegerType() && 1715 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1716 return Context.hasSameUnqualifiedType(ToType, 1717 FromEnumType->getDecl()->getPromotionType()); 1718 } 1719 1720 // C++0x [conv.prom]p2: 1721 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1722 // to an rvalue a prvalue of the first of the following types that can 1723 // represent all the values of its underlying type: int, unsigned int, 1724 // long int, unsigned long int, long long int, or unsigned long long int. 1725 // If none of the types in that list can represent all the values of its 1726 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1727 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1728 // type. 1729 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1730 ToType->isIntegerType()) { 1731 // Determine whether the type we're converting from is signed or 1732 // unsigned. 1733 bool FromIsSigned = FromType->isSignedIntegerType(); 1734 uint64_t FromSize = Context.getTypeSize(FromType); 1735 1736 // The types we'll try to promote to, in the appropriate 1737 // order. Try each of these types. 1738 QualType PromoteTypes[6] = { 1739 Context.IntTy, Context.UnsignedIntTy, 1740 Context.LongTy, Context.UnsignedLongTy , 1741 Context.LongLongTy, Context.UnsignedLongLongTy 1742 }; 1743 for (int Idx = 0; Idx < 6; ++Idx) { 1744 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1745 if (FromSize < ToSize || 1746 (FromSize == ToSize && 1747 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1748 // We found the type that we can promote to. If this is the 1749 // type we wanted, we have a promotion. Otherwise, no 1750 // promotion. 1751 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1752 } 1753 } 1754 } 1755 1756 // An rvalue for an integral bit-field (9.6) can be converted to an 1757 // rvalue of type int if int can represent all the values of the 1758 // bit-field; otherwise, it can be converted to unsigned int if 1759 // unsigned int can represent all the values of the bit-field. If 1760 // the bit-field is larger yet, no integral promotion applies to 1761 // it. If the bit-field has an enumerated type, it is treated as any 1762 // other value of that type for promotion purposes (C++ 4.5p3). 1763 // FIXME: We should delay checking of bit-fields until we actually perform the 1764 // conversion. 1765 using llvm::APSInt; 1766 if (From) 1767 if (FieldDecl *MemberDecl = From->getBitField()) { 1768 APSInt BitWidth; 1769 if (FromType->isIntegralType(Context) && 1770 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1771 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1772 ToSize = Context.getTypeSize(ToType); 1773 1774 // Are we promoting to an int from a bitfield that fits in an int? 1775 if (BitWidth < ToSize || 1776 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1777 return To->getKind() == BuiltinType::Int; 1778 } 1779 1780 // Are we promoting to an unsigned int from an unsigned bitfield 1781 // that fits into an unsigned int? 1782 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1783 return To->getKind() == BuiltinType::UInt; 1784 } 1785 1786 return false; 1787 } 1788 } 1789 1790 // An rvalue of type bool can be converted to an rvalue of type int, 1791 // with false becoming zero and true becoming one (C++ 4.5p4). 1792 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1793 return true; 1794 } 1795 1796 return false; 1797} 1798 1799/// IsFloatingPointPromotion - Determines whether the conversion from 1800/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1801/// returns true and sets PromotedType to the promoted type. 1802bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1803 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1804 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1805 /// An rvalue of type float can be converted to an rvalue of type 1806 /// double. (C++ 4.6p1). 1807 if (FromBuiltin->getKind() == BuiltinType::Float && 1808 ToBuiltin->getKind() == BuiltinType::Double) 1809 return true; 1810 1811 // C99 6.3.1.5p1: 1812 // When a float is promoted to double or long double, or a 1813 // double is promoted to long double [...]. 1814 if (!getLangOpts().CPlusPlus && 1815 (FromBuiltin->getKind() == BuiltinType::Float || 1816 FromBuiltin->getKind() == BuiltinType::Double) && 1817 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1818 return true; 1819 1820 // Half can be promoted to float. 1821 if (FromBuiltin->getKind() == BuiltinType::Half && 1822 ToBuiltin->getKind() == BuiltinType::Float) 1823 return true; 1824 } 1825 1826 return false; 1827} 1828 1829/// \brief Determine if a conversion is a complex promotion. 1830/// 1831/// A complex promotion is defined as a complex -> complex conversion 1832/// where the conversion between the underlying real types is a 1833/// floating-point or integral promotion. 1834bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1835 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1836 if (!FromComplex) 1837 return false; 1838 1839 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1840 if (!ToComplex) 1841 return false; 1842 1843 return IsFloatingPointPromotion(FromComplex->getElementType(), 1844 ToComplex->getElementType()) || 1845 IsIntegralPromotion(0, FromComplex->getElementType(), 1846 ToComplex->getElementType()); 1847} 1848 1849/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1850/// the pointer type FromPtr to a pointer to type ToPointee, with the 1851/// same type qualifiers as FromPtr has on its pointee type. ToType, 1852/// if non-empty, will be a pointer to ToType that may or may not have 1853/// the right set of qualifiers on its pointee. 1854/// 1855static QualType 1856BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1857 QualType ToPointee, QualType ToType, 1858 ASTContext &Context, 1859 bool StripObjCLifetime = false) { 1860 assert((FromPtr->getTypeClass() == Type::Pointer || 1861 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1862 "Invalid similarly-qualified pointer type"); 1863 1864 /// Conversions to 'id' subsume cv-qualifier conversions. 1865 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1866 return ToType.getUnqualifiedType(); 1867 1868 QualType CanonFromPointee 1869 = Context.getCanonicalType(FromPtr->getPointeeType()); 1870 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1871 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1872 1873 if (StripObjCLifetime) 1874 Quals.removeObjCLifetime(); 1875 1876 // Exact qualifier match -> return the pointer type we're converting to. 1877 if (CanonToPointee.getLocalQualifiers() == Quals) { 1878 // ToType is exactly what we need. Return it. 1879 if (!ToType.isNull()) 1880 return ToType.getUnqualifiedType(); 1881 1882 // Build a pointer to ToPointee. It has the right qualifiers 1883 // already. 1884 if (isa<ObjCObjectPointerType>(ToType)) 1885 return Context.getObjCObjectPointerType(ToPointee); 1886 return Context.getPointerType(ToPointee); 1887 } 1888 1889 // Just build a canonical type that has the right qualifiers. 1890 QualType QualifiedCanonToPointee 1891 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1892 1893 if (isa<ObjCObjectPointerType>(ToType)) 1894 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1895 return Context.getPointerType(QualifiedCanonToPointee); 1896} 1897 1898static bool isNullPointerConstantForConversion(Expr *Expr, 1899 bool InOverloadResolution, 1900 ASTContext &Context) { 1901 // Handle value-dependent integral null pointer constants correctly. 1902 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1903 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1904 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1905 return !InOverloadResolution; 1906 1907 return Expr->isNullPointerConstant(Context, 1908 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1909 : Expr::NPC_ValueDependentIsNull); 1910} 1911 1912/// IsPointerConversion - Determines whether the conversion of the 1913/// expression From, which has the (possibly adjusted) type FromType, 1914/// can be converted to the type ToType via a pointer conversion (C++ 1915/// 4.10). If so, returns true and places the converted type (that 1916/// might differ from ToType in its cv-qualifiers at some level) into 1917/// ConvertedType. 1918/// 1919/// This routine also supports conversions to and from block pointers 1920/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1921/// pointers to interfaces. FIXME: Once we've determined the 1922/// appropriate overloading rules for Objective-C, we may want to 1923/// split the Objective-C checks into a different routine; however, 1924/// GCC seems to consider all of these conversions to be pointer 1925/// conversions, so for now they live here. IncompatibleObjC will be 1926/// set if the conversion is an allowed Objective-C conversion that 1927/// should result in a warning. 1928bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1929 bool InOverloadResolution, 1930 QualType& ConvertedType, 1931 bool &IncompatibleObjC) { 1932 IncompatibleObjC = false; 1933 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1934 IncompatibleObjC)) 1935 return true; 1936 1937 // Conversion from a null pointer constant to any Objective-C pointer type. 1938 if (ToType->isObjCObjectPointerType() && 1939 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1940 ConvertedType = ToType; 1941 return true; 1942 } 1943 1944 // Blocks: Block pointers can be converted to void*. 1945 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1946 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1947 ConvertedType = ToType; 1948 return true; 1949 } 1950 // Blocks: A null pointer constant can be converted to a block 1951 // pointer type. 1952 if (ToType->isBlockPointerType() && 1953 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1954 ConvertedType = ToType; 1955 return true; 1956 } 1957 1958 // If the left-hand-side is nullptr_t, the right side can be a null 1959 // pointer constant. 1960 if (ToType->isNullPtrType() && 1961 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1962 ConvertedType = ToType; 1963 return true; 1964 } 1965 1966 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1967 if (!ToTypePtr) 1968 return false; 1969 1970 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1971 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1972 ConvertedType = ToType; 1973 return true; 1974 } 1975 1976 // Beyond this point, both types need to be pointers 1977 // , including objective-c pointers. 1978 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1979 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1980 !getLangOpts().ObjCAutoRefCount) { 1981 ConvertedType = BuildSimilarlyQualifiedPointerType( 1982 FromType->getAs<ObjCObjectPointerType>(), 1983 ToPointeeType, 1984 ToType, Context); 1985 return true; 1986 } 1987 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1988 if (!FromTypePtr) 1989 return false; 1990 1991 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1992 1993 // If the unqualified pointee types are the same, this can't be a 1994 // pointer conversion, so don't do all of the work below. 1995 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1996 return false; 1997 1998 // An rvalue of type "pointer to cv T," where T is an object type, 1999 // can be converted to an rvalue of type "pointer to cv void" (C++ 2000 // 4.10p2). 2001 if (FromPointeeType->isIncompleteOrObjectType() && 2002 ToPointeeType->isVoidType()) { 2003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2004 ToPointeeType, 2005 ToType, Context, 2006 /*StripObjCLifetime=*/true); 2007 return true; 2008 } 2009 2010 // MSVC allows implicit function to void* type conversion. 2011 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2012 ToPointeeType->isVoidType()) { 2013 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2014 ToPointeeType, 2015 ToType, Context); 2016 return true; 2017 } 2018 2019 // When we're overloading in C, we allow a special kind of pointer 2020 // conversion for compatible-but-not-identical pointee types. 2021 if (!getLangOpts().CPlusPlus && 2022 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2023 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2024 ToPointeeType, 2025 ToType, Context); 2026 return true; 2027 } 2028 2029 // C++ [conv.ptr]p3: 2030 // 2031 // An rvalue of type "pointer to cv D," where D is a class type, 2032 // can be converted to an rvalue of type "pointer to cv B," where 2033 // B is a base class (clause 10) of D. If B is an inaccessible 2034 // (clause 11) or ambiguous (10.2) base class of D, a program that 2035 // necessitates this conversion is ill-formed. The result of the 2036 // conversion is a pointer to the base class sub-object of the 2037 // derived class object. The null pointer value is converted to 2038 // the null pointer value of the destination type. 2039 // 2040 // Note that we do not check for ambiguity or inaccessibility 2041 // here. That is handled by CheckPointerConversion. 2042 if (getLangOpts().CPlusPlus && 2043 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2044 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2045 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2046 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2048 ToPointeeType, 2049 ToType, Context); 2050 return true; 2051 } 2052 2053 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2054 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2056 ToPointeeType, 2057 ToType, Context); 2058 return true; 2059 } 2060 2061 return false; 2062} 2063 2064/// \brief Adopt the given qualifiers for the given type. 2065static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2066 Qualifiers TQs = T.getQualifiers(); 2067 2068 // Check whether qualifiers already match. 2069 if (TQs == Qs) 2070 return T; 2071 2072 if (Qs.compatiblyIncludes(TQs)) 2073 return Context.getQualifiedType(T, Qs); 2074 2075 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2076} 2077 2078/// isObjCPointerConversion - Determines whether this is an 2079/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2080/// with the same arguments and return values. 2081bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2082 QualType& ConvertedType, 2083 bool &IncompatibleObjC) { 2084 if (!getLangOpts().ObjC1) 2085 return false; 2086 2087 // The set of qualifiers on the type we're converting from. 2088 Qualifiers FromQualifiers = FromType.getQualifiers(); 2089 2090 // First, we handle all conversions on ObjC object pointer types. 2091 const ObjCObjectPointerType* ToObjCPtr = 2092 ToType->getAs<ObjCObjectPointerType>(); 2093 const ObjCObjectPointerType *FromObjCPtr = 2094 FromType->getAs<ObjCObjectPointerType>(); 2095 2096 if (ToObjCPtr && FromObjCPtr) { 2097 // If the pointee types are the same (ignoring qualifications), 2098 // then this is not a pointer conversion. 2099 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2100 FromObjCPtr->getPointeeType())) 2101 return false; 2102 2103 // Check for compatible 2104 // Objective C++: We're able to convert between "id" or "Class" and a 2105 // pointer to any interface (in both directions). 2106 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2107 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2108 return true; 2109 } 2110 // Conversions with Objective-C's id<...>. 2111 if ((FromObjCPtr->isObjCQualifiedIdType() || 2112 ToObjCPtr->isObjCQualifiedIdType()) && 2113 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2114 /*compare=*/false)) { 2115 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2116 return true; 2117 } 2118 // Objective C++: We're able to convert from a pointer to an 2119 // interface to a pointer to a different interface. 2120 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2121 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2122 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2123 if (getLangOpts().CPlusPlus && LHS && RHS && 2124 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2125 FromObjCPtr->getPointeeType())) 2126 return false; 2127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2128 ToObjCPtr->getPointeeType(), 2129 ToType, Context); 2130 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2131 return true; 2132 } 2133 2134 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2135 // Okay: this is some kind of implicit downcast of Objective-C 2136 // interfaces, which is permitted. However, we're going to 2137 // complain about it. 2138 IncompatibleObjC = true; 2139 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2140 ToObjCPtr->getPointeeType(), 2141 ToType, Context); 2142 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2143 return true; 2144 } 2145 } 2146 // Beyond this point, both types need to be C pointers or block pointers. 2147 QualType ToPointeeType; 2148 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2149 ToPointeeType = ToCPtr->getPointeeType(); 2150 else if (const BlockPointerType *ToBlockPtr = 2151 ToType->getAs<BlockPointerType>()) { 2152 // Objective C++: We're able to convert from a pointer to any object 2153 // to a block pointer type. 2154 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2155 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2156 return true; 2157 } 2158 ToPointeeType = ToBlockPtr->getPointeeType(); 2159 } 2160 else if (FromType->getAs<BlockPointerType>() && 2161 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2162 // Objective C++: We're able to convert from a block pointer type to a 2163 // pointer to any object. 2164 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2165 return true; 2166 } 2167 else 2168 return false; 2169 2170 QualType FromPointeeType; 2171 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2172 FromPointeeType = FromCPtr->getPointeeType(); 2173 else if (const BlockPointerType *FromBlockPtr = 2174 FromType->getAs<BlockPointerType>()) 2175 FromPointeeType = FromBlockPtr->getPointeeType(); 2176 else 2177 return false; 2178 2179 // If we have pointers to pointers, recursively check whether this 2180 // is an Objective-C conversion. 2181 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2182 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2183 IncompatibleObjC)) { 2184 // We always complain about this conversion. 2185 IncompatibleObjC = true; 2186 ConvertedType = Context.getPointerType(ConvertedType); 2187 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2188 return true; 2189 } 2190 // Allow conversion of pointee being objective-c pointer to another one; 2191 // as in I* to id. 2192 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2193 ToPointeeType->getAs<ObjCObjectPointerType>() && 2194 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2195 IncompatibleObjC)) { 2196 2197 ConvertedType = Context.getPointerType(ConvertedType); 2198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2199 return true; 2200 } 2201 2202 // If we have pointers to functions or blocks, check whether the only 2203 // differences in the argument and result types are in Objective-C 2204 // pointer conversions. If so, we permit the conversion (but 2205 // complain about it). 2206 const FunctionProtoType *FromFunctionType 2207 = FromPointeeType->getAs<FunctionProtoType>(); 2208 const FunctionProtoType *ToFunctionType 2209 = ToPointeeType->getAs<FunctionProtoType>(); 2210 if (FromFunctionType && ToFunctionType) { 2211 // If the function types are exactly the same, this isn't an 2212 // Objective-C pointer conversion. 2213 if (Context.getCanonicalType(FromPointeeType) 2214 == Context.getCanonicalType(ToPointeeType)) 2215 return false; 2216 2217 // Perform the quick checks that will tell us whether these 2218 // function types are obviously different. 2219 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2220 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2221 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2222 return false; 2223 2224 bool HasObjCConversion = false; 2225 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2226 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2227 // Okay, the types match exactly. Nothing to do. 2228 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2229 ToFunctionType->getResultType(), 2230 ConvertedType, IncompatibleObjC)) { 2231 // Okay, we have an Objective-C pointer conversion. 2232 HasObjCConversion = true; 2233 } else { 2234 // Function types are too different. Abort. 2235 return false; 2236 } 2237 2238 // Check argument types. 2239 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2240 ArgIdx != NumArgs; ++ArgIdx) { 2241 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2242 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2243 if (Context.getCanonicalType(FromArgType) 2244 == Context.getCanonicalType(ToArgType)) { 2245 // Okay, the types match exactly. Nothing to do. 2246 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2247 ConvertedType, IncompatibleObjC)) { 2248 // Okay, we have an Objective-C pointer conversion. 2249 HasObjCConversion = true; 2250 } else { 2251 // Argument types are too different. Abort. 2252 return false; 2253 } 2254 } 2255 2256 if (HasObjCConversion) { 2257 // We had an Objective-C conversion. Allow this pointer 2258 // conversion, but complain about it. 2259 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2260 IncompatibleObjC = true; 2261 return true; 2262 } 2263 } 2264 2265 return false; 2266} 2267 2268/// \brief Determine whether this is an Objective-C writeback conversion, 2269/// used for parameter passing when performing automatic reference counting. 2270/// 2271/// \param FromType The type we're converting form. 2272/// 2273/// \param ToType The type we're converting to. 2274/// 2275/// \param ConvertedType The type that will be produced after applying 2276/// this conversion. 2277bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2278 QualType &ConvertedType) { 2279 if (!getLangOpts().ObjCAutoRefCount || 2280 Context.hasSameUnqualifiedType(FromType, ToType)) 2281 return false; 2282 2283 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2284 QualType ToPointee; 2285 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2286 ToPointee = ToPointer->getPointeeType(); 2287 else 2288 return false; 2289 2290 Qualifiers ToQuals = ToPointee.getQualifiers(); 2291 if (!ToPointee->isObjCLifetimeType() || 2292 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2293 !ToQuals.withoutObjCLifetime().empty()) 2294 return false; 2295 2296 // Argument must be a pointer to __strong to __weak. 2297 QualType FromPointee; 2298 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2299 FromPointee = FromPointer->getPointeeType(); 2300 else 2301 return false; 2302 2303 Qualifiers FromQuals = FromPointee.getQualifiers(); 2304 if (!FromPointee->isObjCLifetimeType() || 2305 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2306 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2307 return false; 2308 2309 // Make sure that we have compatible qualifiers. 2310 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2311 if (!ToQuals.compatiblyIncludes(FromQuals)) 2312 return false; 2313 2314 // Remove qualifiers from the pointee type we're converting from; they 2315 // aren't used in the compatibility check belong, and we'll be adding back 2316 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2317 FromPointee = FromPointee.getUnqualifiedType(); 2318 2319 // The unqualified form of the pointee types must be compatible. 2320 ToPointee = ToPointee.getUnqualifiedType(); 2321 bool IncompatibleObjC; 2322 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2323 FromPointee = ToPointee; 2324 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2325 IncompatibleObjC)) 2326 return false; 2327 2328 /// \brief Construct the type we're converting to, which is a pointer to 2329 /// __autoreleasing pointee. 2330 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2331 ConvertedType = Context.getPointerType(FromPointee); 2332 return true; 2333} 2334 2335bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2336 QualType& ConvertedType) { 2337 QualType ToPointeeType; 2338 if (const BlockPointerType *ToBlockPtr = 2339 ToType->getAs<BlockPointerType>()) 2340 ToPointeeType = ToBlockPtr->getPointeeType(); 2341 else 2342 return false; 2343 2344 QualType FromPointeeType; 2345 if (const BlockPointerType *FromBlockPtr = 2346 FromType->getAs<BlockPointerType>()) 2347 FromPointeeType = FromBlockPtr->getPointeeType(); 2348 else 2349 return false; 2350 // We have pointer to blocks, check whether the only 2351 // differences in the argument and result types are in Objective-C 2352 // pointer conversions. If so, we permit the conversion. 2353 2354 const FunctionProtoType *FromFunctionType 2355 = FromPointeeType->getAs<FunctionProtoType>(); 2356 const FunctionProtoType *ToFunctionType 2357 = ToPointeeType->getAs<FunctionProtoType>(); 2358 2359 if (!FromFunctionType || !ToFunctionType) 2360 return false; 2361 2362 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2363 return true; 2364 2365 // Perform the quick checks that will tell us whether these 2366 // function types are obviously different. 2367 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2368 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2369 return false; 2370 2371 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2372 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2373 if (FromEInfo != ToEInfo) 2374 return false; 2375 2376 bool IncompatibleObjC = false; 2377 if (Context.hasSameType(FromFunctionType->getResultType(), 2378 ToFunctionType->getResultType())) { 2379 // Okay, the types match exactly. Nothing to do. 2380 } else { 2381 QualType RHS = FromFunctionType->getResultType(); 2382 QualType LHS = ToFunctionType->getResultType(); 2383 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2384 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2385 LHS = LHS.getUnqualifiedType(); 2386 2387 if (Context.hasSameType(RHS,LHS)) { 2388 // OK exact match. 2389 } else if (isObjCPointerConversion(RHS, LHS, 2390 ConvertedType, IncompatibleObjC)) { 2391 if (IncompatibleObjC) 2392 return false; 2393 // Okay, we have an Objective-C pointer conversion. 2394 } 2395 else 2396 return false; 2397 } 2398 2399 // Check argument types. 2400 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2401 ArgIdx != NumArgs; ++ArgIdx) { 2402 IncompatibleObjC = false; 2403 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2404 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2405 if (Context.hasSameType(FromArgType, ToArgType)) { 2406 // Okay, the types match exactly. Nothing to do. 2407 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2408 ConvertedType, IncompatibleObjC)) { 2409 if (IncompatibleObjC) 2410 return false; 2411 // Okay, we have an Objective-C pointer conversion. 2412 } else 2413 // Argument types are too different. Abort. 2414 return false; 2415 } 2416 if (LangOpts.ObjCAutoRefCount && 2417 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2418 ToFunctionType)) 2419 return false; 2420 2421 ConvertedType = ToType; 2422 return true; 2423} 2424 2425enum { 2426 ft_default, 2427 ft_different_class, 2428 ft_parameter_arity, 2429 ft_parameter_mismatch, 2430 ft_return_type, 2431 ft_qualifer_mismatch 2432}; 2433 2434/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2435/// function types. Catches different number of parameter, mismatch in 2436/// parameter types, and different return types. 2437void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2438 QualType FromType, QualType ToType) { 2439 // If either type is not valid, include no extra info. 2440 if (FromType.isNull() || ToType.isNull()) { 2441 PDiag << ft_default; 2442 return; 2443 } 2444 2445 // Get the function type from the pointers. 2446 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2447 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2448 *ToMember = ToType->getAs<MemberPointerType>(); 2449 if (FromMember->getClass() != ToMember->getClass()) { 2450 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2451 << QualType(FromMember->getClass(), 0); 2452 return; 2453 } 2454 FromType = FromMember->getPointeeType(); 2455 ToType = ToMember->getPointeeType(); 2456 } 2457 2458 if (FromType->isPointerType()) 2459 FromType = FromType->getPointeeType(); 2460 if (ToType->isPointerType()) 2461 ToType = ToType->getPointeeType(); 2462 2463 // Remove references. 2464 FromType = FromType.getNonReferenceType(); 2465 ToType = ToType.getNonReferenceType(); 2466 2467 // Don't print extra info for non-specialized template functions. 2468 if (FromType->isInstantiationDependentType() && 2469 !FromType->getAs<TemplateSpecializationType>()) { 2470 PDiag << ft_default; 2471 return; 2472 } 2473 2474 // No extra info for same types. 2475 if (Context.hasSameType(FromType, ToType)) { 2476 PDiag << ft_default; 2477 return; 2478 } 2479 2480 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2481 *ToFunction = ToType->getAs<FunctionProtoType>(); 2482 2483 // Both types need to be function types. 2484 if (!FromFunction || !ToFunction) { 2485 PDiag << ft_default; 2486 return; 2487 } 2488 2489 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2490 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2491 << FromFunction->getNumArgs(); 2492 return; 2493 } 2494 2495 // Handle different parameter types. 2496 unsigned ArgPos; 2497 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2498 PDiag << ft_parameter_mismatch << ArgPos + 1 2499 << ToFunction->getArgType(ArgPos) 2500 << FromFunction->getArgType(ArgPos); 2501 return; 2502 } 2503 2504 // Handle different return type. 2505 if (!Context.hasSameType(FromFunction->getResultType(), 2506 ToFunction->getResultType())) { 2507 PDiag << ft_return_type << ToFunction->getResultType() 2508 << FromFunction->getResultType(); 2509 return; 2510 } 2511 2512 unsigned FromQuals = FromFunction->getTypeQuals(), 2513 ToQuals = ToFunction->getTypeQuals(); 2514 if (FromQuals != ToQuals) { 2515 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2516 return; 2517 } 2518 2519 // Unable to find a difference, so add no extra info. 2520 PDiag << ft_default; 2521} 2522 2523/// FunctionArgTypesAreEqual - This routine checks two function proto types 2524/// for equality of their argument types. Caller has already checked that 2525/// they have same number of arguments. This routine assumes that Objective-C 2526/// pointer types which only differ in their protocol qualifiers are equal. 2527/// If the parameters are different, ArgPos will have the parameter index 2528/// of the first different parameter. 2529bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2530 const FunctionProtoType *NewType, 2531 unsigned *ArgPos) { 2532 if (!getLangOpts().ObjC1) { 2533 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2534 N = NewType->arg_type_begin(), 2535 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2536 if (!Context.hasSameType(*O, *N)) { 2537 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2538 return false; 2539 } 2540 } 2541 return true; 2542 } 2543 2544 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2545 N = NewType->arg_type_begin(), 2546 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2547 QualType ToType = (*O); 2548 QualType FromType = (*N); 2549 if (!Context.hasSameType(ToType, FromType)) { 2550 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2551 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2552 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2553 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2554 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2555 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2556 continue; 2557 } 2558 else if (const ObjCObjectPointerType *PTTo = 2559 ToType->getAs<ObjCObjectPointerType>()) { 2560 if (const ObjCObjectPointerType *PTFr = 2561 FromType->getAs<ObjCObjectPointerType>()) 2562 if (Context.hasSameUnqualifiedType( 2563 PTTo->getObjectType()->getBaseType(), 2564 PTFr->getObjectType()->getBaseType())) 2565 continue; 2566 } 2567 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2568 return false; 2569 } 2570 } 2571 return true; 2572} 2573 2574/// CheckPointerConversion - Check the pointer conversion from the 2575/// expression From to the type ToType. This routine checks for 2576/// ambiguous or inaccessible derived-to-base pointer 2577/// conversions for which IsPointerConversion has already returned 2578/// true. It returns true and produces a diagnostic if there was an 2579/// error, or returns false otherwise. 2580bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2581 CastKind &Kind, 2582 CXXCastPath& BasePath, 2583 bool IgnoreBaseAccess) { 2584 QualType FromType = From->getType(); 2585 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2586 2587 Kind = CK_BitCast; 2588 2589 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2590 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2591 Expr::NPCK_ZeroExpression) { 2592 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2593 DiagRuntimeBehavior(From->getExprLoc(), From, 2594 PDiag(diag::warn_impcast_bool_to_null_pointer) 2595 << ToType << From->getSourceRange()); 2596 else if (!isUnevaluatedContext()) 2597 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2598 << ToType << From->getSourceRange(); 2599 } 2600 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2601 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2602 QualType FromPointeeType = FromPtrType->getPointeeType(), 2603 ToPointeeType = ToPtrType->getPointeeType(); 2604 2605 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2606 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2607 // We must have a derived-to-base conversion. Check an 2608 // ambiguous or inaccessible conversion. 2609 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2610 From->getExprLoc(), 2611 From->getSourceRange(), &BasePath, 2612 IgnoreBaseAccess)) 2613 return true; 2614 2615 // The conversion was successful. 2616 Kind = CK_DerivedToBase; 2617 } 2618 } 2619 } else if (const ObjCObjectPointerType *ToPtrType = 2620 ToType->getAs<ObjCObjectPointerType>()) { 2621 if (const ObjCObjectPointerType *FromPtrType = 2622 FromType->getAs<ObjCObjectPointerType>()) { 2623 // Objective-C++ conversions are always okay. 2624 // FIXME: We should have a different class of conversions for the 2625 // Objective-C++ implicit conversions. 2626 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2627 return false; 2628 } else if (FromType->isBlockPointerType()) { 2629 Kind = CK_BlockPointerToObjCPointerCast; 2630 } else { 2631 Kind = CK_CPointerToObjCPointerCast; 2632 } 2633 } else if (ToType->isBlockPointerType()) { 2634 if (!FromType->isBlockPointerType()) 2635 Kind = CK_AnyPointerToBlockPointerCast; 2636 } 2637 2638 // We shouldn't fall into this case unless it's valid for other 2639 // reasons. 2640 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2641 Kind = CK_NullToPointer; 2642 2643 return false; 2644} 2645 2646/// IsMemberPointerConversion - Determines whether the conversion of the 2647/// expression From, which has the (possibly adjusted) type FromType, can be 2648/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2649/// If so, returns true and places the converted type (that might differ from 2650/// ToType in its cv-qualifiers at some level) into ConvertedType. 2651bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2652 QualType ToType, 2653 bool InOverloadResolution, 2654 QualType &ConvertedType) { 2655 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2656 if (!ToTypePtr) 2657 return false; 2658 2659 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2660 if (From->isNullPointerConstant(Context, 2661 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2662 : Expr::NPC_ValueDependentIsNull)) { 2663 ConvertedType = ToType; 2664 return true; 2665 } 2666 2667 // Otherwise, both types have to be member pointers. 2668 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2669 if (!FromTypePtr) 2670 return false; 2671 2672 // A pointer to member of B can be converted to a pointer to member of D, 2673 // where D is derived from B (C++ 4.11p2). 2674 QualType FromClass(FromTypePtr->getClass(), 0); 2675 QualType ToClass(ToTypePtr->getClass(), 0); 2676 2677 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2678 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2679 IsDerivedFrom(ToClass, FromClass)) { 2680 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2681 ToClass.getTypePtr()); 2682 return true; 2683 } 2684 2685 return false; 2686} 2687 2688/// CheckMemberPointerConversion - Check the member pointer conversion from the 2689/// expression From to the type ToType. This routine checks for ambiguous or 2690/// virtual or inaccessible base-to-derived member pointer conversions 2691/// for which IsMemberPointerConversion has already returned true. It returns 2692/// true and produces a diagnostic if there was an error, or returns false 2693/// otherwise. 2694bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2695 CastKind &Kind, 2696 CXXCastPath &BasePath, 2697 bool IgnoreBaseAccess) { 2698 QualType FromType = From->getType(); 2699 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2700 if (!FromPtrType) { 2701 // This must be a null pointer to member pointer conversion 2702 assert(From->isNullPointerConstant(Context, 2703 Expr::NPC_ValueDependentIsNull) && 2704 "Expr must be null pointer constant!"); 2705 Kind = CK_NullToMemberPointer; 2706 return false; 2707 } 2708 2709 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2710 assert(ToPtrType && "No member pointer cast has a target type " 2711 "that is not a member pointer."); 2712 2713 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2714 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2715 2716 // FIXME: What about dependent types? 2717 assert(FromClass->isRecordType() && "Pointer into non-class."); 2718 assert(ToClass->isRecordType() && "Pointer into non-class."); 2719 2720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2721 /*DetectVirtual=*/true); 2722 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2723 assert(DerivationOkay && 2724 "Should not have been called if derivation isn't OK."); 2725 (void)DerivationOkay; 2726 2727 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2728 getUnqualifiedType())) { 2729 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2730 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2731 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2732 return true; 2733 } 2734 2735 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2736 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2737 << FromClass << ToClass << QualType(VBase, 0) 2738 << From->getSourceRange(); 2739 return true; 2740 } 2741 2742 if (!IgnoreBaseAccess) 2743 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2744 Paths.front(), 2745 diag::err_downcast_from_inaccessible_base); 2746 2747 // Must be a base to derived member conversion. 2748 BuildBasePathArray(Paths, BasePath); 2749 Kind = CK_BaseToDerivedMemberPointer; 2750 return false; 2751} 2752 2753/// IsQualificationConversion - Determines whether the conversion from 2754/// an rvalue of type FromType to ToType is a qualification conversion 2755/// (C++ 4.4). 2756/// 2757/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2758/// when the qualification conversion involves a change in the Objective-C 2759/// object lifetime. 2760bool 2761Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2762 bool CStyle, bool &ObjCLifetimeConversion) { 2763 FromType = Context.getCanonicalType(FromType); 2764 ToType = Context.getCanonicalType(ToType); 2765 ObjCLifetimeConversion = false; 2766 2767 // If FromType and ToType are the same type, this is not a 2768 // qualification conversion. 2769 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2770 return false; 2771 2772 // (C++ 4.4p4): 2773 // A conversion can add cv-qualifiers at levels other than the first 2774 // in multi-level pointers, subject to the following rules: [...] 2775 bool PreviousToQualsIncludeConst = true; 2776 bool UnwrappedAnyPointer = false; 2777 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2778 // Within each iteration of the loop, we check the qualifiers to 2779 // determine if this still looks like a qualification 2780 // conversion. Then, if all is well, we unwrap one more level of 2781 // pointers or pointers-to-members and do it all again 2782 // until there are no more pointers or pointers-to-members left to 2783 // unwrap. 2784 UnwrappedAnyPointer = true; 2785 2786 Qualifiers FromQuals = FromType.getQualifiers(); 2787 Qualifiers ToQuals = ToType.getQualifiers(); 2788 2789 // Objective-C ARC: 2790 // Check Objective-C lifetime conversions. 2791 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2792 UnwrappedAnyPointer) { 2793 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2794 ObjCLifetimeConversion = true; 2795 FromQuals.removeObjCLifetime(); 2796 ToQuals.removeObjCLifetime(); 2797 } else { 2798 // Qualification conversions cannot cast between different 2799 // Objective-C lifetime qualifiers. 2800 return false; 2801 } 2802 } 2803 2804 // Allow addition/removal of GC attributes but not changing GC attributes. 2805 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2806 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2807 FromQuals.removeObjCGCAttr(); 2808 ToQuals.removeObjCGCAttr(); 2809 } 2810 2811 // -- for every j > 0, if const is in cv 1,j then const is in cv 2812 // 2,j, and similarly for volatile. 2813 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2814 return false; 2815 2816 // -- if the cv 1,j and cv 2,j are different, then const is in 2817 // every cv for 0 < k < j. 2818 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2819 && !PreviousToQualsIncludeConst) 2820 return false; 2821 2822 // Keep track of whether all prior cv-qualifiers in the "to" type 2823 // include const. 2824 PreviousToQualsIncludeConst 2825 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2826 } 2827 2828 // We are left with FromType and ToType being the pointee types 2829 // after unwrapping the original FromType and ToType the same number 2830 // of types. If we unwrapped any pointers, and if FromType and 2831 // ToType have the same unqualified type (since we checked 2832 // qualifiers above), then this is a qualification conversion. 2833 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2834} 2835 2836/// \brief - Determine whether this is a conversion from a scalar type to an 2837/// atomic type. 2838/// 2839/// If successful, updates \c SCS's second and third steps in the conversion 2840/// sequence to finish the conversion. 2841static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2842 bool InOverloadResolution, 2843 StandardConversionSequence &SCS, 2844 bool CStyle) { 2845 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2846 if (!ToAtomic) 2847 return false; 2848 2849 StandardConversionSequence InnerSCS; 2850 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2851 InOverloadResolution, InnerSCS, 2852 CStyle, /*AllowObjCWritebackConversion=*/false)) 2853 return false; 2854 2855 SCS.Second = InnerSCS.Second; 2856 SCS.setToType(1, InnerSCS.getToType(1)); 2857 SCS.Third = InnerSCS.Third; 2858 SCS.QualificationIncludesObjCLifetime 2859 = InnerSCS.QualificationIncludesObjCLifetime; 2860 SCS.setToType(2, InnerSCS.getToType(2)); 2861 return true; 2862} 2863 2864static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2865 CXXConstructorDecl *Constructor, 2866 QualType Type) { 2867 const FunctionProtoType *CtorType = 2868 Constructor->getType()->getAs<FunctionProtoType>(); 2869 if (CtorType->getNumArgs() > 0) { 2870 QualType FirstArg = CtorType->getArgType(0); 2871 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2872 return true; 2873 } 2874 return false; 2875} 2876 2877static OverloadingResult 2878IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2879 CXXRecordDecl *To, 2880 UserDefinedConversionSequence &User, 2881 OverloadCandidateSet &CandidateSet, 2882 bool AllowExplicit) { 2883 DeclContext::lookup_iterator Con, ConEnd; 2884 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2885 Con != ConEnd; ++Con) { 2886 NamedDecl *D = *Con; 2887 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2888 2889 // Find the constructor (which may be a template). 2890 CXXConstructorDecl *Constructor = 0; 2891 FunctionTemplateDecl *ConstructorTmpl 2892 = dyn_cast<FunctionTemplateDecl>(D); 2893 if (ConstructorTmpl) 2894 Constructor 2895 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2896 else 2897 Constructor = cast<CXXConstructorDecl>(D); 2898 2899 bool Usable = !Constructor->isInvalidDecl() && 2900 S.isInitListConstructor(Constructor) && 2901 (AllowExplicit || !Constructor->isExplicit()); 2902 if (Usable) { 2903 // If the first argument is (a reference to) the target type, 2904 // suppress conversions. 2905 bool SuppressUserConversions = 2906 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2907 if (ConstructorTmpl) 2908 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2909 /*ExplicitArgs*/ 0, 2910 From, CandidateSet, 2911 SuppressUserConversions); 2912 else 2913 S.AddOverloadCandidate(Constructor, FoundDecl, 2914 From, CandidateSet, 2915 SuppressUserConversions); 2916 } 2917 } 2918 2919 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2920 2921 OverloadCandidateSet::iterator Best; 2922 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2923 case OR_Success: { 2924 // Record the standard conversion we used and the conversion function. 2925 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2926 QualType ThisType = Constructor->getThisType(S.Context); 2927 // Initializer lists don't have conversions as such. 2928 User.Before.setAsIdentityConversion(); 2929 User.HadMultipleCandidates = HadMultipleCandidates; 2930 User.ConversionFunction = Constructor; 2931 User.FoundConversionFunction = Best->FoundDecl; 2932 User.After.setAsIdentityConversion(); 2933 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2934 User.After.setAllToTypes(ToType); 2935 return OR_Success; 2936 } 2937 2938 case OR_No_Viable_Function: 2939 return OR_No_Viable_Function; 2940 case OR_Deleted: 2941 return OR_Deleted; 2942 case OR_Ambiguous: 2943 return OR_Ambiguous; 2944 } 2945 2946 llvm_unreachable("Invalid OverloadResult!"); 2947} 2948 2949/// Determines whether there is a user-defined conversion sequence 2950/// (C++ [over.ics.user]) that converts expression From to the type 2951/// ToType. If such a conversion exists, User will contain the 2952/// user-defined conversion sequence that performs such a conversion 2953/// and this routine will return true. Otherwise, this routine returns 2954/// false and User is unspecified. 2955/// 2956/// \param AllowExplicit true if the conversion should consider C++0x 2957/// "explicit" conversion functions as well as non-explicit conversion 2958/// functions (C++0x [class.conv.fct]p2). 2959static OverloadingResult 2960IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2961 UserDefinedConversionSequence &User, 2962 OverloadCandidateSet &CandidateSet, 2963 bool AllowExplicit) { 2964 // Whether we will only visit constructors. 2965 bool ConstructorsOnly = false; 2966 2967 // If the type we are conversion to is a class type, enumerate its 2968 // constructors. 2969 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2970 // C++ [over.match.ctor]p1: 2971 // When objects of class type are direct-initialized (8.5), or 2972 // copy-initialized from an expression of the same or a 2973 // derived class type (8.5), overload resolution selects the 2974 // constructor. [...] For copy-initialization, the candidate 2975 // functions are all the converting constructors (12.3.1) of 2976 // that class. The argument list is the expression-list within 2977 // the parentheses of the initializer. 2978 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2979 (From->getType()->getAs<RecordType>() && 2980 S.IsDerivedFrom(From->getType(), ToType))) 2981 ConstructorsOnly = true; 2982 2983 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2984 // RequireCompleteType may have returned true due to some invalid decl 2985 // during template instantiation, but ToType may be complete enough now 2986 // to try to recover. 2987 if (ToType->isIncompleteType()) { 2988 // We're not going to find any constructors. 2989 } else if (CXXRecordDecl *ToRecordDecl 2990 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2991 2992 Expr **Args = &From; 2993 unsigned NumArgs = 1; 2994 bool ListInitializing = false; 2995 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2996 // But first, see if there is an init-list-contructor that will work. 2997 OverloadingResult Result = IsInitializerListConstructorConversion( 2998 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2999 if (Result != OR_No_Viable_Function) 3000 return Result; 3001 // Never mind. 3002 CandidateSet.clear(); 3003 3004 // If we're list-initializing, we pass the individual elements as 3005 // arguments, not the entire list. 3006 Args = InitList->getInits(); 3007 NumArgs = InitList->getNumInits(); 3008 ListInitializing = true; 3009 } 3010 3011 DeclContext::lookup_iterator Con, ConEnd; 3012 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 3013 Con != ConEnd; ++Con) { 3014 NamedDecl *D = *Con; 3015 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3016 3017 // Find the constructor (which may be a template). 3018 CXXConstructorDecl *Constructor = 0; 3019 FunctionTemplateDecl *ConstructorTmpl 3020 = dyn_cast<FunctionTemplateDecl>(D); 3021 if (ConstructorTmpl) 3022 Constructor 3023 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3024 else 3025 Constructor = cast<CXXConstructorDecl>(D); 3026 3027 bool Usable = !Constructor->isInvalidDecl(); 3028 if (ListInitializing) 3029 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3030 else 3031 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3032 if (Usable) { 3033 bool SuppressUserConversions = !ConstructorsOnly; 3034 if (SuppressUserConversions && ListInitializing) { 3035 SuppressUserConversions = false; 3036 if (NumArgs == 1) { 3037 // If the first argument is (a reference to) the target type, 3038 // suppress conversions. 3039 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3040 S.Context, Constructor, ToType); 3041 } 3042 } 3043 if (ConstructorTmpl) 3044 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3045 /*ExplicitArgs*/ 0, 3046 llvm::makeArrayRef(Args, NumArgs), 3047 CandidateSet, SuppressUserConversions); 3048 else 3049 // Allow one user-defined conversion when user specifies a 3050 // From->ToType conversion via an static cast (c-style, etc). 3051 S.AddOverloadCandidate(Constructor, FoundDecl, 3052 llvm::makeArrayRef(Args, NumArgs), 3053 CandidateSet, SuppressUserConversions); 3054 } 3055 } 3056 } 3057 } 3058 3059 // Enumerate conversion functions, if we're allowed to. 3060 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3061 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3062 // No conversion functions from incomplete types. 3063 } else if (const RecordType *FromRecordType 3064 = From->getType()->getAs<RecordType>()) { 3065 if (CXXRecordDecl *FromRecordDecl 3066 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3067 // Add all of the conversion functions as candidates. 3068 const UnresolvedSetImpl *Conversions 3069 = FromRecordDecl->getVisibleConversionFunctions(); 3070 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3071 E = Conversions->end(); I != E; ++I) { 3072 DeclAccessPair FoundDecl = I.getPair(); 3073 NamedDecl *D = FoundDecl.getDecl(); 3074 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3075 if (isa<UsingShadowDecl>(D)) 3076 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3077 3078 CXXConversionDecl *Conv; 3079 FunctionTemplateDecl *ConvTemplate; 3080 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3081 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3082 else 3083 Conv = cast<CXXConversionDecl>(D); 3084 3085 if (AllowExplicit || !Conv->isExplicit()) { 3086 if (ConvTemplate) 3087 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3088 ActingContext, From, ToType, 3089 CandidateSet); 3090 else 3091 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3092 From, ToType, CandidateSet); 3093 } 3094 } 3095 } 3096 } 3097 3098 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3099 3100 OverloadCandidateSet::iterator Best; 3101 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3102 case OR_Success: 3103 // Record the standard conversion we used and the conversion function. 3104 if (CXXConstructorDecl *Constructor 3105 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3106 // C++ [over.ics.user]p1: 3107 // If the user-defined conversion is specified by a 3108 // constructor (12.3.1), the initial standard conversion 3109 // sequence converts the source type to the type required by 3110 // the argument of the constructor. 3111 // 3112 QualType ThisType = Constructor->getThisType(S.Context); 3113 if (isa<InitListExpr>(From)) { 3114 // Initializer lists don't have conversions as such. 3115 User.Before.setAsIdentityConversion(); 3116 } else { 3117 if (Best->Conversions[0].isEllipsis()) 3118 User.EllipsisConversion = true; 3119 else { 3120 User.Before = Best->Conversions[0].Standard; 3121 User.EllipsisConversion = false; 3122 } 3123 } 3124 User.HadMultipleCandidates = HadMultipleCandidates; 3125 User.ConversionFunction = Constructor; 3126 User.FoundConversionFunction = Best->FoundDecl; 3127 User.After.setAsIdentityConversion(); 3128 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3129 User.After.setAllToTypes(ToType); 3130 return OR_Success; 3131 } 3132 if (CXXConversionDecl *Conversion 3133 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3134 // C++ [over.ics.user]p1: 3135 // 3136 // [...] If the user-defined conversion is specified by a 3137 // conversion function (12.3.2), the initial standard 3138 // conversion sequence converts the source type to the 3139 // implicit object parameter of the conversion function. 3140 User.Before = Best->Conversions[0].Standard; 3141 User.HadMultipleCandidates = HadMultipleCandidates; 3142 User.ConversionFunction = Conversion; 3143 User.FoundConversionFunction = Best->FoundDecl; 3144 User.EllipsisConversion = false; 3145 3146 // C++ [over.ics.user]p2: 3147 // The second standard conversion sequence converts the 3148 // result of the user-defined conversion to the target type 3149 // for the sequence. Since an implicit conversion sequence 3150 // is an initialization, the special rules for 3151 // initialization by user-defined conversion apply when 3152 // selecting the best user-defined conversion for a 3153 // user-defined conversion sequence (see 13.3.3 and 3154 // 13.3.3.1). 3155 User.After = Best->FinalConversion; 3156 return OR_Success; 3157 } 3158 llvm_unreachable("Not a constructor or conversion function?"); 3159 3160 case OR_No_Viable_Function: 3161 return OR_No_Viable_Function; 3162 case OR_Deleted: 3163 // No conversion here! We're done. 3164 return OR_Deleted; 3165 3166 case OR_Ambiguous: 3167 return OR_Ambiguous; 3168 } 3169 3170 llvm_unreachable("Invalid OverloadResult!"); 3171} 3172 3173bool 3174Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3175 ImplicitConversionSequence ICS; 3176 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3177 OverloadingResult OvResult = 3178 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3179 CandidateSet, false); 3180 if (OvResult == OR_Ambiguous) 3181 Diag(From->getLocStart(), 3182 diag::err_typecheck_ambiguous_condition) 3183 << From->getType() << ToType << From->getSourceRange(); 3184 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3185 Diag(From->getLocStart(), 3186 diag::err_typecheck_nonviable_condition) 3187 << From->getType() << ToType << From->getSourceRange(); 3188 else 3189 return false; 3190 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3191 return true; 3192} 3193 3194/// \brief Compare the user-defined conversion functions or constructors 3195/// of two user-defined conversion sequences to determine whether any ordering 3196/// is possible. 3197static ImplicitConversionSequence::CompareKind 3198compareConversionFunctions(Sema &S, 3199 FunctionDecl *Function1, 3200 FunctionDecl *Function2) { 3201 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3202 return ImplicitConversionSequence::Indistinguishable; 3203 3204 // Objective-C++: 3205 // If both conversion functions are implicitly-declared conversions from 3206 // a lambda closure type to a function pointer and a block pointer, 3207 // respectively, always prefer the conversion to a function pointer, 3208 // because the function pointer is more lightweight and is more likely 3209 // to keep code working. 3210 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3211 if (!Conv1) 3212 return ImplicitConversionSequence::Indistinguishable; 3213 3214 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3215 if (!Conv2) 3216 return ImplicitConversionSequence::Indistinguishable; 3217 3218 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3219 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3220 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3221 if (Block1 != Block2) 3222 return Block1? ImplicitConversionSequence::Worse 3223 : ImplicitConversionSequence::Better; 3224 } 3225 3226 return ImplicitConversionSequence::Indistinguishable; 3227} 3228 3229/// CompareImplicitConversionSequences - Compare two implicit 3230/// conversion sequences to determine whether one is better than the 3231/// other or if they are indistinguishable (C++ 13.3.3.2). 3232static ImplicitConversionSequence::CompareKind 3233CompareImplicitConversionSequences(Sema &S, 3234 const ImplicitConversionSequence& ICS1, 3235 const ImplicitConversionSequence& ICS2) 3236{ 3237 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3238 // conversion sequences (as defined in 13.3.3.1) 3239 // -- a standard conversion sequence (13.3.3.1.1) is a better 3240 // conversion sequence than a user-defined conversion sequence or 3241 // an ellipsis conversion sequence, and 3242 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3243 // conversion sequence than an ellipsis conversion sequence 3244 // (13.3.3.1.3). 3245 // 3246 // C++0x [over.best.ics]p10: 3247 // For the purpose of ranking implicit conversion sequences as 3248 // described in 13.3.3.2, the ambiguous conversion sequence is 3249 // treated as a user-defined sequence that is indistinguishable 3250 // from any other user-defined conversion sequence. 3251 if (ICS1.getKindRank() < ICS2.getKindRank()) 3252 return ImplicitConversionSequence::Better; 3253 if (ICS2.getKindRank() < ICS1.getKindRank()) 3254 return ImplicitConversionSequence::Worse; 3255 3256 // The following checks require both conversion sequences to be of 3257 // the same kind. 3258 if (ICS1.getKind() != ICS2.getKind()) 3259 return ImplicitConversionSequence::Indistinguishable; 3260 3261 ImplicitConversionSequence::CompareKind Result = 3262 ImplicitConversionSequence::Indistinguishable; 3263 3264 // Two implicit conversion sequences of the same form are 3265 // indistinguishable conversion sequences unless one of the 3266 // following rules apply: (C++ 13.3.3.2p3): 3267 if (ICS1.isStandard()) 3268 Result = CompareStandardConversionSequences(S, 3269 ICS1.Standard, ICS2.Standard); 3270 else if (ICS1.isUserDefined()) { 3271 // User-defined conversion sequence U1 is a better conversion 3272 // sequence than another user-defined conversion sequence U2 if 3273 // they contain the same user-defined conversion function or 3274 // constructor and if the second standard conversion sequence of 3275 // U1 is better than the second standard conversion sequence of 3276 // U2 (C++ 13.3.3.2p3). 3277 if (ICS1.UserDefined.ConversionFunction == 3278 ICS2.UserDefined.ConversionFunction) 3279 Result = CompareStandardConversionSequences(S, 3280 ICS1.UserDefined.After, 3281 ICS2.UserDefined.After); 3282 else 3283 Result = compareConversionFunctions(S, 3284 ICS1.UserDefined.ConversionFunction, 3285 ICS2.UserDefined.ConversionFunction); 3286 } 3287 3288 // List-initialization sequence L1 is a better conversion sequence than 3289 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3290 // for some X and L2 does not. 3291 if (Result == ImplicitConversionSequence::Indistinguishable && 3292 !ICS1.isBad() && 3293 ICS1.isListInitializationSequence() && 3294 ICS2.isListInitializationSequence()) { 3295 if (ICS1.isStdInitializerListElement() && 3296 !ICS2.isStdInitializerListElement()) 3297 return ImplicitConversionSequence::Better; 3298 if (!ICS1.isStdInitializerListElement() && 3299 ICS2.isStdInitializerListElement()) 3300 return ImplicitConversionSequence::Worse; 3301 } 3302 3303 return Result; 3304} 3305 3306static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3307 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3308 Qualifiers Quals; 3309 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3310 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3311 } 3312 3313 return Context.hasSameUnqualifiedType(T1, T2); 3314} 3315 3316// Per 13.3.3.2p3, compare the given standard conversion sequences to 3317// determine if one is a proper subset of the other. 3318static ImplicitConversionSequence::CompareKind 3319compareStandardConversionSubsets(ASTContext &Context, 3320 const StandardConversionSequence& SCS1, 3321 const StandardConversionSequence& SCS2) { 3322 ImplicitConversionSequence::CompareKind Result 3323 = ImplicitConversionSequence::Indistinguishable; 3324 3325 // the identity conversion sequence is considered to be a subsequence of 3326 // any non-identity conversion sequence 3327 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3328 return ImplicitConversionSequence::Better; 3329 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3330 return ImplicitConversionSequence::Worse; 3331 3332 if (SCS1.Second != SCS2.Second) { 3333 if (SCS1.Second == ICK_Identity) 3334 Result = ImplicitConversionSequence::Better; 3335 else if (SCS2.Second == ICK_Identity) 3336 Result = ImplicitConversionSequence::Worse; 3337 else 3338 return ImplicitConversionSequence::Indistinguishable; 3339 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3340 return ImplicitConversionSequence::Indistinguishable; 3341 3342 if (SCS1.Third == SCS2.Third) { 3343 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3344 : ImplicitConversionSequence::Indistinguishable; 3345 } 3346 3347 if (SCS1.Third == ICK_Identity) 3348 return Result == ImplicitConversionSequence::Worse 3349 ? ImplicitConversionSequence::Indistinguishable 3350 : ImplicitConversionSequence::Better; 3351 3352 if (SCS2.Third == ICK_Identity) 3353 return Result == ImplicitConversionSequence::Better 3354 ? ImplicitConversionSequence::Indistinguishable 3355 : ImplicitConversionSequence::Worse; 3356 3357 return ImplicitConversionSequence::Indistinguishable; 3358} 3359 3360/// \brief Determine whether one of the given reference bindings is better 3361/// than the other based on what kind of bindings they are. 3362static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3363 const StandardConversionSequence &SCS2) { 3364 // C++0x [over.ics.rank]p3b4: 3365 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3366 // implicit object parameter of a non-static member function declared 3367 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3368 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3369 // lvalue reference to a function lvalue and S2 binds an rvalue 3370 // reference*. 3371 // 3372 // FIXME: Rvalue references. We're going rogue with the above edits, 3373 // because the semantics in the current C++0x working paper (N3225 at the 3374 // time of this writing) break the standard definition of std::forward 3375 // and std::reference_wrapper when dealing with references to functions. 3376 // Proposed wording changes submitted to CWG for consideration. 3377 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3378 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3379 return false; 3380 3381 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3382 SCS2.IsLvalueReference) || 3383 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3384 !SCS2.IsLvalueReference); 3385} 3386 3387/// CompareStandardConversionSequences - Compare two standard 3388/// conversion sequences to determine whether one is better than the 3389/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3390static ImplicitConversionSequence::CompareKind 3391CompareStandardConversionSequences(Sema &S, 3392 const StandardConversionSequence& SCS1, 3393 const StandardConversionSequence& SCS2) 3394{ 3395 // Standard conversion sequence S1 is a better conversion sequence 3396 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3397 3398 // -- S1 is a proper subsequence of S2 (comparing the conversion 3399 // sequences in the canonical form defined by 13.3.3.1.1, 3400 // excluding any Lvalue Transformation; the identity conversion 3401 // sequence is considered to be a subsequence of any 3402 // non-identity conversion sequence) or, if not that, 3403 if (ImplicitConversionSequence::CompareKind CK 3404 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3405 return CK; 3406 3407 // -- the rank of S1 is better than the rank of S2 (by the rules 3408 // defined below), or, if not that, 3409 ImplicitConversionRank Rank1 = SCS1.getRank(); 3410 ImplicitConversionRank Rank2 = SCS2.getRank(); 3411 if (Rank1 < Rank2) 3412 return ImplicitConversionSequence::Better; 3413 else if (Rank2 < Rank1) 3414 return ImplicitConversionSequence::Worse; 3415 3416 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3417 // are indistinguishable unless one of the following rules 3418 // applies: 3419 3420 // A conversion that is not a conversion of a pointer, or 3421 // pointer to member, to bool is better than another conversion 3422 // that is such a conversion. 3423 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3424 return SCS2.isPointerConversionToBool() 3425 ? ImplicitConversionSequence::Better 3426 : ImplicitConversionSequence::Worse; 3427 3428 // C++ [over.ics.rank]p4b2: 3429 // 3430 // If class B is derived directly or indirectly from class A, 3431 // conversion of B* to A* is better than conversion of B* to 3432 // void*, and conversion of A* to void* is better than conversion 3433 // of B* to void*. 3434 bool SCS1ConvertsToVoid 3435 = SCS1.isPointerConversionToVoidPointer(S.Context); 3436 bool SCS2ConvertsToVoid 3437 = SCS2.isPointerConversionToVoidPointer(S.Context); 3438 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3439 // Exactly one of the conversion sequences is a conversion to 3440 // a void pointer; it's the worse conversion. 3441 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3442 : ImplicitConversionSequence::Worse; 3443 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3444 // Neither conversion sequence converts to a void pointer; compare 3445 // their derived-to-base conversions. 3446 if (ImplicitConversionSequence::CompareKind DerivedCK 3447 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3448 return DerivedCK; 3449 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3450 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3451 // Both conversion sequences are conversions to void 3452 // pointers. Compare the source types to determine if there's an 3453 // inheritance relationship in their sources. 3454 QualType FromType1 = SCS1.getFromType(); 3455 QualType FromType2 = SCS2.getFromType(); 3456 3457 // Adjust the types we're converting from via the array-to-pointer 3458 // conversion, if we need to. 3459 if (SCS1.First == ICK_Array_To_Pointer) 3460 FromType1 = S.Context.getArrayDecayedType(FromType1); 3461 if (SCS2.First == ICK_Array_To_Pointer) 3462 FromType2 = S.Context.getArrayDecayedType(FromType2); 3463 3464 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3465 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3466 3467 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3468 return ImplicitConversionSequence::Better; 3469 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3470 return ImplicitConversionSequence::Worse; 3471 3472 // Objective-C++: If one interface is more specific than the 3473 // other, it is the better one. 3474 const ObjCObjectPointerType* FromObjCPtr1 3475 = FromType1->getAs<ObjCObjectPointerType>(); 3476 const ObjCObjectPointerType* FromObjCPtr2 3477 = FromType2->getAs<ObjCObjectPointerType>(); 3478 if (FromObjCPtr1 && FromObjCPtr2) { 3479 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3480 FromObjCPtr2); 3481 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3482 FromObjCPtr1); 3483 if (AssignLeft != AssignRight) { 3484 return AssignLeft? ImplicitConversionSequence::Better 3485 : ImplicitConversionSequence::Worse; 3486 } 3487 } 3488 } 3489 3490 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3491 // bullet 3). 3492 if (ImplicitConversionSequence::CompareKind QualCK 3493 = CompareQualificationConversions(S, SCS1, SCS2)) 3494 return QualCK; 3495 3496 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3497 // Check for a better reference binding based on the kind of bindings. 3498 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3499 return ImplicitConversionSequence::Better; 3500 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3501 return ImplicitConversionSequence::Worse; 3502 3503 // C++ [over.ics.rank]p3b4: 3504 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3505 // which the references refer are the same type except for 3506 // top-level cv-qualifiers, and the type to which the reference 3507 // initialized by S2 refers is more cv-qualified than the type 3508 // to which the reference initialized by S1 refers. 3509 QualType T1 = SCS1.getToType(2); 3510 QualType T2 = SCS2.getToType(2); 3511 T1 = S.Context.getCanonicalType(T1); 3512 T2 = S.Context.getCanonicalType(T2); 3513 Qualifiers T1Quals, T2Quals; 3514 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3515 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3516 if (UnqualT1 == UnqualT2) { 3517 // Objective-C++ ARC: If the references refer to objects with different 3518 // lifetimes, prefer bindings that don't change lifetime. 3519 if (SCS1.ObjCLifetimeConversionBinding != 3520 SCS2.ObjCLifetimeConversionBinding) { 3521 return SCS1.ObjCLifetimeConversionBinding 3522 ? ImplicitConversionSequence::Worse 3523 : ImplicitConversionSequence::Better; 3524 } 3525 3526 // If the type is an array type, promote the element qualifiers to the 3527 // type for comparison. 3528 if (isa<ArrayType>(T1) && T1Quals) 3529 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3530 if (isa<ArrayType>(T2) && T2Quals) 3531 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3532 if (T2.isMoreQualifiedThan(T1)) 3533 return ImplicitConversionSequence::Better; 3534 else if (T1.isMoreQualifiedThan(T2)) 3535 return ImplicitConversionSequence::Worse; 3536 } 3537 } 3538 3539 // In Microsoft mode, prefer an integral conversion to a 3540 // floating-to-integral conversion if the integral conversion 3541 // is between types of the same size. 3542 // For example: 3543 // void f(float); 3544 // void f(int); 3545 // int main { 3546 // long a; 3547 // f(a); 3548 // } 3549 // Here, MSVC will call f(int) instead of generating a compile error 3550 // as clang will do in standard mode. 3551 if (S.getLangOpts().MicrosoftMode && 3552 SCS1.Second == ICK_Integral_Conversion && 3553 SCS2.Second == ICK_Floating_Integral && 3554 S.Context.getTypeSize(SCS1.getFromType()) == 3555 S.Context.getTypeSize(SCS1.getToType(2))) 3556 return ImplicitConversionSequence::Better; 3557 3558 return ImplicitConversionSequence::Indistinguishable; 3559} 3560 3561/// CompareQualificationConversions - Compares two standard conversion 3562/// sequences to determine whether they can be ranked based on their 3563/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3564ImplicitConversionSequence::CompareKind 3565CompareQualificationConversions(Sema &S, 3566 const StandardConversionSequence& SCS1, 3567 const StandardConversionSequence& SCS2) { 3568 // C++ 13.3.3.2p3: 3569 // -- S1 and S2 differ only in their qualification conversion and 3570 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3571 // cv-qualification signature of type T1 is a proper subset of 3572 // the cv-qualification signature of type T2, and S1 is not the 3573 // deprecated string literal array-to-pointer conversion (4.2). 3574 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3575 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3576 return ImplicitConversionSequence::Indistinguishable; 3577 3578 // FIXME: the example in the standard doesn't use a qualification 3579 // conversion (!) 3580 QualType T1 = SCS1.getToType(2); 3581 QualType T2 = SCS2.getToType(2); 3582 T1 = S.Context.getCanonicalType(T1); 3583 T2 = S.Context.getCanonicalType(T2); 3584 Qualifiers T1Quals, T2Quals; 3585 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3586 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3587 3588 // If the types are the same, we won't learn anything by unwrapped 3589 // them. 3590 if (UnqualT1 == UnqualT2) 3591 return ImplicitConversionSequence::Indistinguishable; 3592 3593 // If the type is an array type, promote the element qualifiers to the type 3594 // for comparison. 3595 if (isa<ArrayType>(T1) && T1Quals) 3596 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3597 if (isa<ArrayType>(T2) && T2Quals) 3598 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3599 3600 ImplicitConversionSequence::CompareKind Result 3601 = ImplicitConversionSequence::Indistinguishable; 3602 3603 // Objective-C++ ARC: 3604 // Prefer qualification conversions not involving a change in lifetime 3605 // to qualification conversions that do not change lifetime. 3606 if (SCS1.QualificationIncludesObjCLifetime != 3607 SCS2.QualificationIncludesObjCLifetime) { 3608 Result = SCS1.QualificationIncludesObjCLifetime 3609 ? ImplicitConversionSequence::Worse 3610 : ImplicitConversionSequence::Better; 3611 } 3612 3613 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3614 // Within each iteration of the loop, we check the qualifiers to 3615 // determine if this still looks like a qualification 3616 // conversion. Then, if all is well, we unwrap one more level of 3617 // pointers or pointers-to-members and do it all again 3618 // until there are no more pointers or pointers-to-members left 3619 // to unwrap. This essentially mimics what 3620 // IsQualificationConversion does, but here we're checking for a 3621 // strict subset of qualifiers. 3622 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3623 // The qualifiers are the same, so this doesn't tell us anything 3624 // about how the sequences rank. 3625 ; 3626 else if (T2.isMoreQualifiedThan(T1)) { 3627 // T1 has fewer qualifiers, so it could be the better sequence. 3628 if (Result == ImplicitConversionSequence::Worse) 3629 // Neither has qualifiers that are a subset of the other's 3630 // qualifiers. 3631 return ImplicitConversionSequence::Indistinguishable; 3632 3633 Result = ImplicitConversionSequence::Better; 3634 } else if (T1.isMoreQualifiedThan(T2)) { 3635 // T2 has fewer qualifiers, so it could be the better sequence. 3636 if (Result == ImplicitConversionSequence::Better) 3637 // Neither has qualifiers that are a subset of the other's 3638 // qualifiers. 3639 return ImplicitConversionSequence::Indistinguishable; 3640 3641 Result = ImplicitConversionSequence::Worse; 3642 } else { 3643 // Qualifiers are disjoint. 3644 return ImplicitConversionSequence::Indistinguishable; 3645 } 3646 3647 // If the types after this point are equivalent, we're done. 3648 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3649 break; 3650 } 3651 3652 // Check that the winning standard conversion sequence isn't using 3653 // the deprecated string literal array to pointer conversion. 3654 switch (Result) { 3655 case ImplicitConversionSequence::Better: 3656 if (SCS1.DeprecatedStringLiteralToCharPtr) 3657 Result = ImplicitConversionSequence::Indistinguishable; 3658 break; 3659 3660 case ImplicitConversionSequence::Indistinguishable: 3661 break; 3662 3663 case ImplicitConversionSequence::Worse: 3664 if (SCS2.DeprecatedStringLiteralToCharPtr) 3665 Result = ImplicitConversionSequence::Indistinguishable; 3666 break; 3667 } 3668 3669 return Result; 3670} 3671 3672/// CompareDerivedToBaseConversions - Compares two standard conversion 3673/// sequences to determine whether they can be ranked based on their 3674/// various kinds of derived-to-base conversions (C++ 3675/// [over.ics.rank]p4b3). As part of these checks, we also look at 3676/// conversions between Objective-C interface types. 3677ImplicitConversionSequence::CompareKind 3678CompareDerivedToBaseConversions(Sema &S, 3679 const StandardConversionSequence& SCS1, 3680 const StandardConversionSequence& SCS2) { 3681 QualType FromType1 = SCS1.getFromType(); 3682 QualType ToType1 = SCS1.getToType(1); 3683 QualType FromType2 = SCS2.getFromType(); 3684 QualType ToType2 = SCS2.getToType(1); 3685 3686 // Adjust the types we're converting from via the array-to-pointer 3687 // conversion, if we need to. 3688 if (SCS1.First == ICK_Array_To_Pointer) 3689 FromType1 = S.Context.getArrayDecayedType(FromType1); 3690 if (SCS2.First == ICK_Array_To_Pointer) 3691 FromType2 = S.Context.getArrayDecayedType(FromType2); 3692 3693 // Canonicalize all of the types. 3694 FromType1 = S.Context.getCanonicalType(FromType1); 3695 ToType1 = S.Context.getCanonicalType(ToType1); 3696 FromType2 = S.Context.getCanonicalType(FromType2); 3697 ToType2 = S.Context.getCanonicalType(ToType2); 3698 3699 // C++ [over.ics.rank]p4b3: 3700 // 3701 // If class B is derived directly or indirectly from class A and 3702 // class C is derived directly or indirectly from B, 3703 // 3704 // Compare based on pointer conversions. 3705 if (SCS1.Second == ICK_Pointer_Conversion && 3706 SCS2.Second == ICK_Pointer_Conversion && 3707 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3708 FromType1->isPointerType() && FromType2->isPointerType() && 3709 ToType1->isPointerType() && ToType2->isPointerType()) { 3710 QualType FromPointee1 3711 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3712 QualType ToPointee1 3713 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3714 QualType FromPointee2 3715 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3716 QualType ToPointee2 3717 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3718 3719 // -- conversion of C* to B* is better than conversion of C* to A*, 3720 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3721 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3722 return ImplicitConversionSequence::Better; 3723 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3724 return ImplicitConversionSequence::Worse; 3725 } 3726 3727 // -- conversion of B* to A* is better than conversion of C* to A*, 3728 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3729 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3730 return ImplicitConversionSequence::Better; 3731 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3732 return ImplicitConversionSequence::Worse; 3733 } 3734 } else if (SCS1.Second == ICK_Pointer_Conversion && 3735 SCS2.Second == ICK_Pointer_Conversion) { 3736 const ObjCObjectPointerType *FromPtr1 3737 = FromType1->getAs<ObjCObjectPointerType>(); 3738 const ObjCObjectPointerType *FromPtr2 3739 = FromType2->getAs<ObjCObjectPointerType>(); 3740 const ObjCObjectPointerType *ToPtr1 3741 = ToType1->getAs<ObjCObjectPointerType>(); 3742 const ObjCObjectPointerType *ToPtr2 3743 = ToType2->getAs<ObjCObjectPointerType>(); 3744 3745 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3746 // Apply the same conversion ranking rules for Objective-C pointer types 3747 // that we do for C++ pointers to class types. However, we employ the 3748 // Objective-C pseudo-subtyping relationship used for assignment of 3749 // Objective-C pointer types. 3750 bool FromAssignLeft 3751 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3752 bool FromAssignRight 3753 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3754 bool ToAssignLeft 3755 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3756 bool ToAssignRight 3757 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3758 3759 // A conversion to an a non-id object pointer type or qualified 'id' 3760 // type is better than a conversion to 'id'. 3761 if (ToPtr1->isObjCIdType() && 3762 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3763 return ImplicitConversionSequence::Worse; 3764 if (ToPtr2->isObjCIdType() && 3765 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3766 return ImplicitConversionSequence::Better; 3767 3768 // A conversion to a non-id object pointer type is better than a 3769 // conversion to a qualified 'id' type 3770 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3771 return ImplicitConversionSequence::Worse; 3772 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3773 return ImplicitConversionSequence::Better; 3774 3775 // A conversion to an a non-Class object pointer type or qualified 'Class' 3776 // type is better than a conversion to 'Class'. 3777 if (ToPtr1->isObjCClassType() && 3778 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3779 return ImplicitConversionSequence::Worse; 3780 if (ToPtr2->isObjCClassType() && 3781 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3782 return ImplicitConversionSequence::Better; 3783 3784 // A conversion to a non-Class object pointer type is better than a 3785 // conversion to a qualified 'Class' type. 3786 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3787 return ImplicitConversionSequence::Worse; 3788 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3789 return ImplicitConversionSequence::Better; 3790 3791 // -- "conversion of C* to B* is better than conversion of C* to A*," 3792 if (S.Context.hasSameType(FromType1, FromType2) && 3793 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3794 (ToAssignLeft != ToAssignRight)) 3795 return ToAssignLeft? ImplicitConversionSequence::Worse 3796 : ImplicitConversionSequence::Better; 3797 3798 // -- "conversion of B* to A* is better than conversion of C* to A*," 3799 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3800 (FromAssignLeft != FromAssignRight)) 3801 return FromAssignLeft? ImplicitConversionSequence::Better 3802 : ImplicitConversionSequence::Worse; 3803 } 3804 } 3805 3806 // Ranking of member-pointer types. 3807 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3808 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3809 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3810 const MemberPointerType * FromMemPointer1 = 3811 FromType1->getAs<MemberPointerType>(); 3812 const MemberPointerType * ToMemPointer1 = 3813 ToType1->getAs<MemberPointerType>(); 3814 const MemberPointerType * FromMemPointer2 = 3815 FromType2->getAs<MemberPointerType>(); 3816 const MemberPointerType * ToMemPointer2 = 3817 ToType2->getAs<MemberPointerType>(); 3818 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3819 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3820 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3821 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3822 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3823 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3824 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3825 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3826 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3827 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3828 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3829 return ImplicitConversionSequence::Worse; 3830 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3831 return ImplicitConversionSequence::Better; 3832 } 3833 // conversion of B::* to C::* is better than conversion of A::* to C::* 3834 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3835 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3836 return ImplicitConversionSequence::Better; 3837 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3838 return ImplicitConversionSequence::Worse; 3839 } 3840 } 3841 3842 if (SCS1.Second == ICK_Derived_To_Base) { 3843 // -- conversion of C to B is better than conversion of C to A, 3844 // -- binding of an expression of type C to a reference of type 3845 // B& is better than binding an expression of type C to a 3846 // reference of type A&, 3847 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3848 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3849 if (S.IsDerivedFrom(ToType1, ToType2)) 3850 return ImplicitConversionSequence::Better; 3851 else if (S.IsDerivedFrom(ToType2, ToType1)) 3852 return ImplicitConversionSequence::Worse; 3853 } 3854 3855 // -- conversion of B to A is better than conversion of C to A. 3856 // -- binding of an expression of type B to a reference of type 3857 // A& is better than binding an expression of type C to a 3858 // reference of type A&, 3859 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3860 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3861 if (S.IsDerivedFrom(FromType2, FromType1)) 3862 return ImplicitConversionSequence::Better; 3863 else if (S.IsDerivedFrom(FromType1, FromType2)) 3864 return ImplicitConversionSequence::Worse; 3865 } 3866 } 3867 3868 return ImplicitConversionSequence::Indistinguishable; 3869} 3870 3871/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3872/// determine whether they are reference-related, 3873/// reference-compatible, reference-compatible with added 3874/// qualification, or incompatible, for use in C++ initialization by 3875/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3876/// type, and the first type (T1) is the pointee type of the reference 3877/// type being initialized. 3878Sema::ReferenceCompareResult 3879Sema::CompareReferenceRelationship(SourceLocation Loc, 3880 QualType OrigT1, QualType OrigT2, 3881 bool &DerivedToBase, 3882 bool &ObjCConversion, 3883 bool &ObjCLifetimeConversion) { 3884 assert(!OrigT1->isReferenceType() && 3885 "T1 must be the pointee type of the reference type"); 3886 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3887 3888 QualType T1 = Context.getCanonicalType(OrigT1); 3889 QualType T2 = Context.getCanonicalType(OrigT2); 3890 Qualifiers T1Quals, T2Quals; 3891 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3892 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3893 3894 // C++ [dcl.init.ref]p4: 3895 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3896 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3897 // T1 is a base class of T2. 3898 DerivedToBase = false; 3899 ObjCConversion = false; 3900 ObjCLifetimeConversion = false; 3901 if (UnqualT1 == UnqualT2) { 3902 // Nothing to do. 3903 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3904 IsDerivedFrom(UnqualT2, UnqualT1)) 3905 DerivedToBase = true; 3906 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3907 UnqualT2->isObjCObjectOrInterfaceType() && 3908 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3909 ObjCConversion = true; 3910 else 3911 return Ref_Incompatible; 3912 3913 // At this point, we know that T1 and T2 are reference-related (at 3914 // least). 3915 3916 // If the type is an array type, promote the element qualifiers to the type 3917 // for comparison. 3918 if (isa<ArrayType>(T1) && T1Quals) 3919 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3920 if (isa<ArrayType>(T2) && T2Quals) 3921 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3922 3923 // C++ [dcl.init.ref]p4: 3924 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3925 // reference-related to T2 and cv1 is the same cv-qualification 3926 // as, or greater cv-qualification than, cv2. For purposes of 3927 // overload resolution, cases for which cv1 is greater 3928 // cv-qualification than cv2 are identified as 3929 // reference-compatible with added qualification (see 13.3.3.2). 3930 // 3931 // Note that we also require equivalence of Objective-C GC and address-space 3932 // qualifiers when performing these computations, so that e.g., an int in 3933 // address space 1 is not reference-compatible with an int in address 3934 // space 2. 3935 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3936 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3937 T1Quals.removeObjCLifetime(); 3938 T2Quals.removeObjCLifetime(); 3939 ObjCLifetimeConversion = true; 3940 } 3941 3942 if (T1Quals == T2Quals) 3943 return Ref_Compatible; 3944 else if (T1Quals.compatiblyIncludes(T2Quals)) 3945 return Ref_Compatible_With_Added_Qualification; 3946 else 3947 return Ref_Related; 3948} 3949 3950/// \brief Look for a user-defined conversion to an value reference-compatible 3951/// with DeclType. Return true if something definite is found. 3952static bool 3953FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3954 QualType DeclType, SourceLocation DeclLoc, 3955 Expr *Init, QualType T2, bool AllowRvalues, 3956 bool AllowExplicit) { 3957 assert(T2->isRecordType() && "Can only find conversions of record types."); 3958 CXXRecordDecl *T2RecordDecl 3959 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3960 3961 OverloadCandidateSet CandidateSet(DeclLoc); 3962 const UnresolvedSetImpl *Conversions 3963 = T2RecordDecl->getVisibleConversionFunctions(); 3964 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3965 E = Conversions->end(); I != E; ++I) { 3966 NamedDecl *D = *I; 3967 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3968 if (isa<UsingShadowDecl>(D)) 3969 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3970 3971 FunctionTemplateDecl *ConvTemplate 3972 = dyn_cast<FunctionTemplateDecl>(D); 3973 CXXConversionDecl *Conv; 3974 if (ConvTemplate) 3975 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3976 else 3977 Conv = cast<CXXConversionDecl>(D); 3978 3979 // If this is an explicit conversion, and we're not allowed to consider 3980 // explicit conversions, skip it. 3981 if (!AllowExplicit && Conv->isExplicit()) 3982 continue; 3983 3984 if (AllowRvalues) { 3985 bool DerivedToBase = false; 3986 bool ObjCConversion = false; 3987 bool ObjCLifetimeConversion = false; 3988 3989 // If we are initializing an rvalue reference, don't permit conversion 3990 // functions that return lvalues. 3991 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3992 const ReferenceType *RefType 3993 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3994 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3995 continue; 3996 } 3997 3998 if (!ConvTemplate && 3999 S.CompareReferenceRelationship( 4000 DeclLoc, 4001 Conv->getConversionType().getNonReferenceType() 4002 .getUnqualifiedType(), 4003 DeclType.getNonReferenceType().getUnqualifiedType(), 4004 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4005 Sema::Ref_Incompatible) 4006 continue; 4007 } else { 4008 // If the conversion function doesn't return a reference type, 4009 // it can't be considered for this conversion. An rvalue reference 4010 // is only acceptable if its referencee is a function type. 4011 4012 const ReferenceType *RefType = 4013 Conv->getConversionType()->getAs<ReferenceType>(); 4014 if (!RefType || 4015 (!RefType->isLValueReferenceType() && 4016 !RefType->getPointeeType()->isFunctionType())) 4017 continue; 4018 } 4019 4020 if (ConvTemplate) 4021 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4022 Init, DeclType, CandidateSet); 4023 else 4024 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4025 DeclType, CandidateSet); 4026 } 4027 4028 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4029 4030 OverloadCandidateSet::iterator Best; 4031 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4032 case OR_Success: 4033 // C++ [over.ics.ref]p1: 4034 // 4035 // [...] If the parameter binds directly to the result of 4036 // applying a conversion function to the argument 4037 // expression, the implicit conversion sequence is a 4038 // user-defined conversion sequence (13.3.3.1.2), with the 4039 // second standard conversion sequence either an identity 4040 // conversion or, if the conversion function returns an 4041 // entity of a type that is a derived class of the parameter 4042 // type, a derived-to-base Conversion. 4043 if (!Best->FinalConversion.DirectBinding) 4044 return false; 4045 4046 ICS.setUserDefined(); 4047 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4048 ICS.UserDefined.After = Best->FinalConversion; 4049 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4050 ICS.UserDefined.ConversionFunction = Best->Function; 4051 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4052 ICS.UserDefined.EllipsisConversion = false; 4053 assert(ICS.UserDefined.After.ReferenceBinding && 4054 ICS.UserDefined.After.DirectBinding && 4055 "Expected a direct reference binding!"); 4056 return true; 4057 4058 case OR_Ambiguous: 4059 ICS.setAmbiguous(); 4060 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4061 Cand != CandidateSet.end(); ++Cand) 4062 if (Cand->Viable) 4063 ICS.Ambiguous.addConversion(Cand->Function); 4064 return true; 4065 4066 case OR_No_Viable_Function: 4067 case OR_Deleted: 4068 // There was no suitable conversion, or we found a deleted 4069 // conversion; continue with other checks. 4070 return false; 4071 } 4072 4073 llvm_unreachable("Invalid OverloadResult!"); 4074} 4075 4076/// \brief Compute an implicit conversion sequence for reference 4077/// initialization. 4078static ImplicitConversionSequence 4079TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4080 SourceLocation DeclLoc, 4081 bool SuppressUserConversions, 4082 bool AllowExplicit) { 4083 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4084 4085 // Most paths end in a failed conversion. 4086 ImplicitConversionSequence ICS; 4087 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4088 4089 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4090 QualType T2 = Init->getType(); 4091 4092 // If the initializer is the address of an overloaded function, try 4093 // to resolve the overloaded function. If all goes well, T2 is the 4094 // type of the resulting function. 4095 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4096 DeclAccessPair Found; 4097 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4098 false, Found)) 4099 T2 = Fn->getType(); 4100 } 4101 4102 // Compute some basic properties of the types and the initializer. 4103 bool isRValRef = DeclType->isRValueReferenceType(); 4104 bool DerivedToBase = false; 4105 bool ObjCConversion = false; 4106 bool ObjCLifetimeConversion = false; 4107 Expr::Classification InitCategory = Init->Classify(S.Context); 4108 Sema::ReferenceCompareResult RefRelationship 4109 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4110 ObjCConversion, ObjCLifetimeConversion); 4111 4112 4113 // C++0x [dcl.init.ref]p5: 4114 // A reference to type "cv1 T1" is initialized by an expression 4115 // of type "cv2 T2" as follows: 4116 4117 // -- If reference is an lvalue reference and the initializer expression 4118 if (!isRValRef) { 4119 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4120 // reference-compatible with "cv2 T2," or 4121 // 4122 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4123 if (InitCategory.isLValue() && 4124 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4125 // C++ [over.ics.ref]p1: 4126 // When a parameter of reference type binds directly (8.5.3) 4127 // to an argument expression, the implicit conversion sequence 4128 // is the identity conversion, unless the argument expression 4129 // has a type that is a derived class of the parameter type, 4130 // in which case the implicit conversion sequence is a 4131 // derived-to-base Conversion (13.3.3.1). 4132 ICS.setStandard(); 4133 ICS.Standard.First = ICK_Identity; 4134 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4135 : ObjCConversion? ICK_Compatible_Conversion 4136 : ICK_Identity; 4137 ICS.Standard.Third = ICK_Identity; 4138 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4139 ICS.Standard.setToType(0, T2); 4140 ICS.Standard.setToType(1, T1); 4141 ICS.Standard.setToType(2, T1); 4142 ICS.Standard.ReferenceBinding = true; 4143 ICS.Standard.DirectBinding = true; 4144 ICS.Standard.IsLvalueReference = !isRValRef; 4145 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4146 ICS.Standard.BindsToRvalue = false; 4147 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4148 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4149 ICS.Standard.CopyConstructor = 0; 4150 4151 // Nothing more to do: the inaccessibility/ambiguity check for 4152 // derived-to-base conversions is suppressed when we're 4153 // computing the implicit conversion sequence (C++ 4154 // [over.best.ics]p2). 4155 return ICS; 4156 } 4157 4158 // -- has a class type (i.e., T2 is a class type), where T1 is 4159 // not reference-related to T2, and can be implicitly 4160 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4161 // is reference-compatible with "cv3 T3" 92) (this 4162 // conversion is selected by enumerating the applicable 4163 // conversion functions (13.3.1.6) and choosing the best 4164 // one through overload resolution (13.3)), 4165 if (!SuppressUserConversions && T2->isRecordType() && 4166 !S.RequireCompleteType(DeclLoc, T2, 0) && 4167 RefRelationship == Sema::Ref_Incompatible) { 4168 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4169 Init, T2, /*AllowRvalues=*/false, 4170 AllowExplicit)) 4171 return ICS; 4172 } 4173 } 4174 4175 // -- Otherwise, the reference shall be an lvalue reference to a 4176 // non-volatile const type (i.e., cv1 shall be const), or the reference 4177 // shall be an rvalue reference. 4178 // 4179 // We actually handle one oddity of C++ [over.ics.ref] at this 4180 // point, which is that, due to p2 (which short-circuits reference 4181 // binding by only attempting a simple conversion for non-direct 4182 // bindings) and p3's strange wording, we allow a const volatile 4183 // reference to bind to an rvalue. Hence the check for the presence 4184 // of "const" rather than checking for "const" being the only 4185 // qualifier. 4186 // This is also the point where rvalue references and lvalue inits no longer 4187 // go together. 4188 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4189 return ICS; 4190 4191 // -- If the initializer expression 4192 // 4193 // -- is an xvalue, class prvalue, array prvalue or function 4194 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4195 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4196 (InitCategory.isXValue() || 4197 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4198 (InitCategory.isLValue() && T2->isFunctionType()))) { 4199 ICS.setStandard(); 4200 ICS.Standard.First = ICK_Identity; 4201 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4202 : ObjCConversion? ICK_Compatible_Conversion 4203 : ICK_Identity; 4204 ICS.Standard.Third = ICK_Identity; 4205 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4206 ICS.Standard.setToType(0, T2); 4207 ICS.Standard.setToType(1, T1); 4208 ICS.Standard.setToType(2, T1); 4209 ICS.Standard.ReferenceBinding = true; 4210 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4211 // binding unless we're binding to a class prvalue. 4212 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4213 // allow the use of rvalue references in C++98/03 for the benefit of 4214 // standard library implementors; therefore, we need the xvalue check here. 4215 ICS.Standard.DirectBinding = 4216 S.getLangOpts().CPlusPlus0x || 4217 (InitCategory.isPRValue() && !T2->isRecordType()); 4218 ICS.Standard.IsLvalueReference = !isRValRef; 4219 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4220 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4221 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4222 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4223 ICS.Standard.CopyConstructor = 0; 4224 return ICS; 4225 } 4226 4227 // -- has a class type (i.e., T2 is a class type), where T1 is not 4228 // reference-related to T2, and can be implicitly converted to 4229 // an xvalue, class prvalue, or function lvalue of type 4230 // "cv3 T3", where "cv1 T1" is reference-compatible with 4231 // "cv3 T3", 4232 // 4233 // then the reference is bound to the value of the initializer 4234 // expression in the first case and to the result of the conversion 4235 // in the second case (or, in either case, to an appropriate base 4236 // class subobject). 4237 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4238 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4239 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4240 Init, T2, /*AllowRvalues=*/true, 4241 AllowExplicit)) { 4242 // In the second case, if the reference is an rvalue reference 4243 // and the second standard conversion sequence of the 4244 // user-defined conversion sequence includes an lvalue-to-rvalue 4245 // conversion, the program is ill-formed. 4246 if (ICS.isUserDefined() && isRValRef && 4247 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4248 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4249 4250 return ICS; 4251 } 4252 4253 // -- Otherwise, a temporary of type "cv1 T1" is created and 4254 // initialized from the initializer expression using the 4255 // rules for a non-reference copy initialization (8.5). The 4256 // reference is then bound to the temporary. If T1 is 4257 // reference-related to T2, cv1 must be the same 4258 // cv-qualification as, or greater cv-qualification than, 4259 // cv2; otherwise, the program is ill-formed. 4260 if (RefRelationship == Sema::Ref_Related) { 4261 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4262 // we would be reference-compatible or reference-compatible with 4263 // added qualification. But that wasn't the case, so the reference 4264 // initialization fails. 4265 // 4266 // Note that we only want to check address spaces and cvr-qualifiers here. 4267 // ObjC GC and lifetime qualifiers aren't important. 4268 Qualifiers T1Quals = T1.getQualifiers(); 4269 Qualifiers T2Quals = T2.getQualifiers(); 4270 T1Quals.removeObjCGCAttr(); 4271 T1Quals.removeObjCLifetime(); 4272 T2Quals.removeObjCGCAttr(); 4273 T2Quals.removeObjCLifetime(); 4274 if (!T1Quals.compatiblyIncludes(T2Quals)) 4275 return ICS; 4276 } 4277 4278 // If at least one of the types is a class type, the types are not 4279 // related, and we aren't allowed any user conversions, the 4280 // reference binding fails. This case is important for breaking 4281 // recursion, since TryImplicitConversion below will attempt to 4282 // create a temporary through the use of a copy constructor. 4283 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4284 (T1->isRecordType() || T2->isRecordType())) 4285 return ICS; 4286 4287 // If T1 is reference-related to T2 and the reference is an rvalue 4288 // reference, the initializer expression shall not be an lvalue. 4289 if (RefRelationship >= Sema::Ref_Related && 4290 isRValRef && Init->Classify(S.Context).isLValue()) 4291 return ICS; 4292 4293 // C++ [over.ics.ref]p2: 4294 // When a parameter of reference type is not bound directly to 4295 // an argument expression, the conversion sequence is the one 4296 // required to convert the argument expression to the 4297 // underlying type of the reference according to 4298 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4299 // to copy-initializing a temporary of the underlying type with 4300 // the argument expression. Any difference in top-level 4301 // cv-qualification is subsumed by the initialization itself 4302 // and does not constitute a conversion. 4303 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4304 /*AllowExplicit=*/false, 4305 /*InOverloadResolution=*/false, 4306 /*CStyle=*/false, 4307 /*AllowObjCWritebackConversion=*/false); 4308 4309 // Of course, that's still a reference binding. 4310 if (ICS.isStandard()) { 4311 ICS.Standard.ReferenceBinding = true; 4312 ICS.Standard.IsLvalueReference = !isRValRef; 4313 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4314 ICS.Standard.BindsToRvalue = true; 4315 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4316 ICS.Standard.ObjCLifetimeConversionBinding = false; 4317 } else if (ICS.isUserDefined()) { 4318 // Don't allow rvalue references to bind to lvalues. 4319 if (DeclType->isRValueReferenceType()) { 4320 if (const ReferenceType *RefType 4321 = ICS.UserDefined.ConversionFunction->getResultType() 4322 ->getAs<LValueReferenceType>()) { 4323 if (!RefType->getPointeeType()->isFunctionType()) { 4324 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4325 DeclType); 4326 return ICS; 4327 } 4328 } 4329 } 4330 4331 ICS.UserDefined.After.ReferenceBinding = true; 4332 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4333 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4334 ICS.UserDefined.After.BindsToRvalue = true; 4335 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4336 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4337 } 4338 4339 return ICS; 4340} 4341 4342static ImplicitConversionSequence 4343TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4344 bool SuppressUserConversions, 4345 bool InOverloadResolution, 4346 bool AllowObjCWritebackConversion, 4347 bool AllowExplicit = false); 4348 4349/// TryListConversion - Try to copy-initialize a value of type ToType from the 4350/// initializer list From. 4351static ImplicitConversionSequence 4352TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4353 bool SuppressUserConversions, 4354 bool InOverloadResolution, 4355 bool AllowObjCWritebackConversion) { 4356 // C++11 [over.ics.list]p1: 4357 // When an argument is an initializer list, it is not an expression and 4358 // special rules apply for converting it to a parameter type. 4359 4360 ImplicitConversionSequence Result; 4361 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4362 Result.setListInitializationSequence(); 4363 4364 // We need a complete type for what follows. Incomplete types can never be 4365 // initialized from init lists. 4366 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4367 return Result; 4368 4369 // C++11 [over.ics.list]p2: 4370 // If the parameter type is std::initializer_list<X> or "array of X" and 4371 // all the elements can be implicitly converted to X, the implicit 4372 // conversion sequence is the worst conversion necessary to convert an 4373 // element of the list to X. 4374 bool toStdInitializerList = false; 4375 QualType X; 4376 if (ToType->isArrayType()) 4377 X = S.Context.getBaseElementType(ToType); 4378 else 4379 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4380 if (!X.isNull()) { 4381 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4382 Expr *Init = From->getInit(i); 4383 ImplicitConversionSequence ICS = 4384 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4385 InOverloadResolution, 4386 AllowObjCWritebackConversion); 4387 // If a single element isn't convertible, fail. 4388 if (ICS.isBad()) { 4389 Result = ICS; 4390 break; 4391 } 4392 // Otherwise, look for the worst conversion. 4393 if (Result.isBad() || 4394 CompareImplicitConversionSequences(S, ICS, Result) == 4395 ImplicitConversionSequence::Worse) 4396 Result = ICS; 4397 } 4398 4399 // For an empty list, we won't have computed any conversion sequence. 4400 // Introduce the identity conversion sequence. 4401 if (From->getNumInits() == 0) { 4402 Result.setStandard(); 4403 Result.Standard.setAsIdentityConversion(); 4404 Result.Standard.setFromType(ToType); 4405 Result.Standard.setAllToTypes(ToType); 4406 } 4407 4408 Result.setListInitializationSequence(); 4409 Result.setStdInitializerListElement(toStdInitializerList); 4410 return Result; 4411 } 4412 4413 // C++11 [over.ics.list]p3: 4414 // Otherwise, if the parameter is a non-aggregate class X and overload 4415 // resolution chooses a single best constructor [...] the implicit 4416 // conversion sequence is a user-defined conversion sequence. If multiple 4417 // constructors are viable but none is better than the others, the 4418 // implicit conversion sequence is a user-defined conversion sequence. 4419 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4420 // This function can deal with initializer lists. 4421 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4422 /*AllowExplicit=*/false, 4423 InOverloadResolution, /*CStyle=*/false, 4424 AllowObjCWritebackConversion); 4425 Result.setListInitializationSequence(); 4426 return Result; 4427 } 4428 4429 // C++11 [over.ics.list]p4: 4430 // Otherwise, if the parameter has an aggregate type which can be 4431 // initialized from the initializer list [...] the implicit conversion 4432 // sequence is a user-defined conversion sequence. 4433 if (ToType->isAggregateType()) { 4434 // Type is an aggregate, argument is an init list. At this point it comes 4435 // down to checking whether the initialization works. 4436 // FIXME: Find out whether this parameter is consumed or not. 4437 InitializedEntity Entity = 4438 InitializedEntity::InitializeParameter(S.Context, ToType, 4439 /*Consumed=*/false); 4440 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4441 Result.setUserDefined(); 4442 Result.UserDefined.Before.setAsIdentityConversion(); 4443 // Initializer lists don't have a type. 4444 Result.UserDefined.Before.setFromType(QualType()); 4445 Result.UserDefined.Before.setAllToTypes(QualType()); 4446 4447 Result.UserDefined.After.setAsIdentityConversion(); 4448 Result.UserDefined.After.setFromType(ToType); 4449 Result.UserDefined.After.setAllToTypes(ToType); 4450 Result.UserDefined.ConversionFunction = 0; 4451 } 4452 return Result; 4453 } 4454 4455 // C++11 [over.ics.list]p5: 4456 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4457 if (ToType->isReferenceType()) { 4458 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4459 // mention initializer lists in any way. So we go by what list- 4460 // initialization would do and try to extrapolate from that. 4461 4462 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4463 4464 // If the initializer list has a single element that is reference-related 4465 // to the parameter type, we initialize the reference from that. 4466 if (From->getNumInits() == 1) { 4467 Expr *Init = From->getInit(0); 4468 4469 QualType T2 = Init->getType(); 4470 4471 // If the initializer is the address of an overloaded function, try 4472 // to resolve the overloaded function. If all goes well, T2 is the 4473 // type of the resulting function. 4474 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4475 DeclAccessPair Found; 4476 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4477 Init, ToType, false, Found)) 4478 T2 = Fn->getType(); 4479 } 4480 4481 // Compute some basic properties of the types and the initializer. 4482 bool dummy1 = false; 4483 bool dummy2 = false; 4484 bool dummy3 = false; 4485 Sema::ReferenceCompareResult RefRelationship 4486 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4487 dummy2, dummy3); 4488 4489 if (RefRelationship >= Sema::Ref_Related) 4490 return TryReferenceInit(S, Init, ToType, 4491 /*FIXME:*/From->getLocStart(), 4492 SuppressUserConversions, 4493 /*AllowExplicit=*/false); 4494 } 4495 4496 // Otherwise, we bind the reference to a temporary created from the 4497 // initializer list. 4498 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4499 InOverloadResolution, 4500 AllowObjCWritebackConversion); 4501 if (Result.isFailure()) 4502 return Result; 4503 assert(!Result.isEllipsis() && 4504 "Sub-initialization cannot result in ellipsis conversion."); 4505 4506 // Can we even bind to a temporary? 4507 if (ToType->isRValueReferenceType() || 4508 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4509 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4510 Result.UserDefined.After; 4511 SCS.ReferenceBinding = true; 4512 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4513 SCS.BindsToRvalue = true; 4514 SCS.BindsToFunctionLvalue = false; 4515 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4516 SCS.ObjCLifetimeConversionBinding = false; 4517 } else 4518 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4519 From, ToType); 4520 return Result; 4521 } 4522 4523 // C++11 [over.ics.list]p6: 4524 // Otherwise, if the parameter type is not a class: 4525 if (!ToType->isRecordType()) { 4526 // - if the initializer list has one element, the implicit conversion 4527 // sequence is the one required to convert the element to the 4528 // parameter type. 4529 unsigned NumInits = From->getNumInits(); 4530 if (NumInits == 1) 4531 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4532 SuppressUserConversions, 4533 InOverloadResolution, 4534 AllowObjCWritebackConversion); 4535 // - if the initializer list has no elements, the implicit conversion 4536 // sequence is the identity conversion. 4537 else if (NumInits == 0) { 4538 Result.setStandard(); 4539 Result.Standard.setAsIdentityConversion(); 4540 Result.Standard.setFromType(ToType); 4541 Result.Standard.setAllToTypes(ToType); 4542 } 4543 Result.setListInitializationSequence(); 4544 return Result; 4545 } 4546 4547 // C++11 [over.ics.list]p7: 4548 // In all cases other than those enumerated above, no conversion is possible 4549 return Result; 4550} 4551 4552/// TryCopyInitialization - Try to copy-initialize a value of type 4553/// ToType from the expression From. Return the implicit conversion 4554/// sequence required to pass this argument, which may be a bad 4555/// conversion sequence (meaning that the argument cannot be passed to 4556/// a parameter of this type). If @p SuppressUserConversions, then we 4557/// do not permit any user-defined conversion sequences. 4558static ImplicitConversionSequence 4559TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4560 bool SuppressUserConversions, 4561 bool InOverloadResolution, 4562 bool AllowObjCWritebackConversion, 4563 bool AllowExplicit) { 4564 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4565 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4566 InOverloadResolution,AllowObjCWritebackConversion); 4567 4568 if (ToType->isReferenceType()) 4569 return TryReferenceInit(S, From, ToType, 4570 /*FIXME:*/From->getLocStart(), 4571 SuppressUserConversions, 4572 AllowExplicit); 4573 4574 return TryImplicitConversion(S, From, ToType, 4575 SuppressUserConversions, 4576 /*AllowExplicit=*/false, 4577 InOverloadResolution, 4578 /*CStyle=*/false, 4579 AllowObjCWritebackConversion); 4580} 4581 4582static bool TryCopyInitialization(const CanQualType FromQTy, 4583 const CanQualType ToQTy, 4584 Sema &S, 4585 SourceLocation Loc, 4586 ExprValueKind FromVK) { 4587 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4588 ImplicitConversionSequence ICS = 4589 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4590 4591 return !ICS.isBad(); 4592} 4593 4594/// TryObjectArgumentInitialization - Try to initialize the object 4595/// parameter of the given member function (@c Method) from the 4596/// expression @p From. 4597static ImplicitConversionSequence 4598TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4599 Expr::Classification FromClassification, 4600 CXXMethodDecl *Method, 4601 CXXRecordDecl *ActingContext) { 4602 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4603 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4604 // const volatile object. 4605 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4606 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4607 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4608 4609 // Set up the conversion sequence as a "bad" conversion, to allow us 4610 // to exit early. 4611 ImplicitConversionSequence ICS; 4612 4613 // We need to have an object of class type. 4614 QualType FromType = OrigFromType; 4615 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4616 FromType = PT->getPointeeType(); 4617 4618 // When we had a pointer, it's implicitly dereferenced, so we 4619 // better have an lvalue. 4620 assert(FromClassification.isLValue()); 4621 } 4622 4623 assert(FromType->isRecordType()); 4624 4625 // C++0x [over.match.funcs]p4: 4626 // For non-static member functions, the type of the implicit object 4627 // parameter is 4628 // 4629 // - "lvalue reference to cv X" for functions declared without a 4630 // ref-qualifier or with the & ref-qualifier 4631 // - "rvalue reference to cv X" for functions declared with the && 4632 // ref-qualifier 4633 // 4634 // where X is the class of which the function is a member and cv is the 4635 // cv-qualification on the member function declaration. 4636 // 4637 // However, when finding an implicit conversion sequence for the argument, we 4638 // are not allowed to create temporaries or perform user-defined conversions 4639 // (C++ [over.match.funcs]p5). We perform a simplified version of 4640 // reference binding here, that allows class rvalues to bind to 4641 // non-constant references. 4642 4643 // First check the qualifiers. 4644 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4645 if (ImplicitParamType.getCVRQualifiers() 4646 != FromTypeCanon.getLocalCVRQualifiers() && 4647 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4648 ICS.setBad(BadConversionSequence::bad_qualifiers, 4649 OrigFromType, ImplicitParamType); 4650 return ICS; 4651 } 4652 4653 // Check that we have either the same type or a derived type. It 4654 // affects the conversion rank. 4655 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4656 ImplicitConversionKind SecondKind; 4657 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4658 SecondKind = ICK_Identity; 4659 } else if (S.IsDerivedFrom(FromType, ClassType)) 4660 SecondKind = ICK_Derived_To_Base; 4661 else { 4662 ICS.setBad(BadConversionSequence::unrelated_class, 4663 FromType, ImplicitParamType); 4664 return ICS; 4665 } 4666 4667 // Check the ref-qualifier. 4668 switch (Method->getRefQualifier()) { 4669 case RQ_None: 4670 // Do nothing; we don't care about lvalueness or rvalueness. 4671 break; 4672 4673 case RQ_LValue: 4674 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4675 // non-const lvalue reference cannot bind to an rvalue 4676 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4677 ImplicitParamType); 4678 return ICS; 4679 } 4680 break; 4681 4682 case RQ_RValue: 4683 if (!FromClassification.isRValue()) { 4684 // rvalue reference cannot bind to an lvalue 4685 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4686 ImplicitParamType); 4687 return ICS; 4688 } 4689 break; 4690 } 4691 4692 // Success. Mark this as a reference binding. 4693 ICS.setStandard(); 4694 ICS.Standard.setAsIdentityConversion(); 4695 ICS.Standard.Second = SecondKind; 4696 ICS.Standard.setFromType(FromType); 4697 ICS.Standard.setAllToTypes(ImplicitParamType); 4698 ICS.Standard.ReferenceBinding = true; 4699 ICS.Standard.DirectBinding = true; 4700 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4701 ICS.Standard.BindsToFunctionLvalue = false; 4702 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4703 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4704 = (Method->getRefQualifier() == RQ_None); 4705 return ICS; 4706} 4707 4708/// PerformObjectArgumentInitialization - Perform initialization of 4709/// the implicit object parameter for the given Method with the given 4710/// expression. 4711ExprResult 4712Sema::PerformObjectArgumentInitialization(Expr *From, 4713 NestedNameSpecifier *Qualifier, 4714 NamedDecl *FoundDecl, 4715 CXXMethodDecl *Method) { 4716 QualType FromRecordType, DestType; 4717 QualType ImplicitParamRecordType = 4718 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4719 4720 Expr::Classification FromClassification; 4721 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4722 FromRecordType = PT->getPointeeType(); 4723 DestType = Method->getThisType(Context); 4724 FromClassification = Expr::Classification::makeSimpleLValue(); 4725 } else { 4726 FromRecordType = From->getType(); 4727 DestType = ImplicitParamRecordType; 4728 FromClassification = From->Classify(Context); 4729 } 4730 4731 // Note that we always use the true parent context when performing 4732 // the actual argument initialization. 4733 ImplicitConversionSequence ICS 4734 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4735 Method, Method->getParent()); 4736 if (ICS.isBad()) { 4737 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4738 Qualifiers FromQs = FromRecordType.getQualifiers(); 4739 Qualifiers ToQs = DestType.getQualifiers(); 4740 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4741 if (CVR) { 4742 Diag(From->getLocStart(), 4743 diag::err_member_function_call_bad_cvr) 4744 << Method->getDeclName() << FromRecordType << (CVR - 1) 4745 << From->getSourceRange(); 4746 Diag(Method->getLocation(), diag::note_previous_decl) 4747 << Method->getDeclName(); 4748 return ExprError(); 4749 } 4750 } 4751 4752 return Diag(From->getLocStart(), 4753 diag::err_implicit_object_parameter_init) 4754 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4755 } 4756 4757 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4758 ExprResult FromRes = 4759 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4760 if (FromRes.isInvalid()) 4761 return ExprError(); 4762 From = FromRes.take(); 4763 } 4764 4765 if (!Context.hasSameType(From->getType(), DestType)) 4766 From = ImpCastExprToType(From, DestType, CK_NoOp, 4767 From->getValueKind()).take(); 4768 return Owned(From); 4769} 4770 4771/// TryContextuallyConvertToBool - Attempt to contextually convert the 4772/// expression From to bool (C++0x [conv]p3). 4773static ImplicitConversionSequence 4774TryContextuallyConvertToBool(Sema &S, Expr *From) { 4775 // FIXME: This is pretty broken. 4776 return TryImplicitConversion(S, From, S.Context.BoolTy, 4777 // FIXME: Are these flags correct? 4778 /*SuppressUserConversions=*/false, 4779 /*AllowExplicit=*/true, 4780 /*InOverloadResolution=*/false, 4781 /*CStyle=*/false, 4782 /*AllowObjCWritebackConversion=*/false); 4783} 4784 4785/// PerformContextuallyConvertToBool - Perform a contextual conversion 4786/// of the expression From to bool (C++0x [conv]p3). 4787ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4788 if (checkPlaceholderForOverload(*this, From)) 4789 return ExprError(); 4790 4791 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4792 if (!ICS.isBad()) 4793 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4794 4795 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4796 return Diag(From->getLocStart(), 4797 diag::err_typecheck_bool_condition) 4798 << From->getType() << From->getSourceRange(); 4799 return ExprError(); 4800} 4801 4802/// Check that the specified conversion is permitted in a converted constant 4803/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4804/// is acceptable. 4805static bool CheckConvertedConstantConversions(Sema &S, 4806 StandardConversionSequence &SCS) { 4807 // Since we know that the target type is an integral or unscoped enumeration 4808 // type, most conversion kinds are impossible. All possible First and Third 4809 // conversions are fine. 4810 switch (SCS.Second) { 4811 case ICK_Identity: 4812 case ICK_Integral_Promotion: 4813 case ICK_Integral_Conversion: 4814 return true; 4815 4816 case ICK_Boolean_Conversion: 4817 // Conversion from an integral or unscoped enumeration type to bool is 4818 // classified as ICK_Boolean_Conversion, but it's also an integral 4819 // conversion, so it's permitted in a converted constant expression. 4820 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4821 SCS.getToType(2)->isBooleanType(); 4822 4823 case ICK_Floating_Integral: 4824 case ICK_Complex_Real: 4825 return false; 4826 4827 case ICK_Lvalue_To_Rvalue: 4828 case ICK_Array_To_Pointer: 4829 case ICK_Function_To_Pointer: 4830 case ICK_NoReturn_Adjustment: 4831 case ICK_Qualification: 4832 case ICK_Compatible_Conversion: 4833 case ICK_Vector_Conversion: 4834 case ICK_Vector_Splat: 4835 case ICK_Derived_To_Base: 4836 case ICK_Pointer_Conversion: 4837 case ICK_Pointer_Member: 4838 case ICK_Block_Pointer_Conversion: 4839 case ICK_Writeback_Conversion: 4840 case ICK_Floating_Promotion: 4841 case ICK_Complex_Promotion: 4842 case ICK_Complex_Conversion: 4843 case ICK_Floating_Conversion: 4844 case ICK_TransparentUnionConversion: 4845 llvm_unreachable("unexpected second conversion kind"); 4846 4847 case ICK_Num_Conversion_Kinds: 4848 break; 4849 } 4850 4851 llvm_unreachable("unknown conversion kind"); 4852} 4853 4854/// CheckConvertedConstantExpression - Check that the expression From is a 4855/// converted constant expression of type T, perform the conversion and produce 4856/// the converted expression, per C++11 [expr.const]p3. 4857ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4858 llvm::APSInt &Value, 4859 CCEKind CCE) { 4860 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4861 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4862 4863 if (checkPlaceholderForOverload(*this, From)) 4864 return ExprError(); 4865 4866 // C++11 [expr.const]p3 with proposed wording fixes: 4867 // A converted constant expression of type T is a core constant expression, 4868 // implicitly converted to a prvalue of type T, where the converted 4869 // expression is a literal constant expression and the implicit conversion 4870 // sequence contains only user-defined conversions, lvalue-to-rvalue 4871 // conversions, integral promotions, and integral conversions other than 4872 // narrowing conversions. 4873 ImplicitConversionSequence ICS = 4874 TryImplicitConversion(From, T, 4875 /*SuppressUserConversions=*/false, 4876 /*AllowExplicit=*/false, 4877 /*InOverloadResolution=*/false, 4878 /*CStyle=*/false, 4879 /*AllowObjcWritebackConversion=*/false); 4880 StandardConversionSequence *SCS = 0; 4881 switch (ICS.getKind()) { 4882 case ImplicitConversionSequence::StandardConversion: 4883 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4884 return Diag(From->getLocStart(), 4885 diag::err_typecheck_converted_constant_expression_disallowed) 4886 << From->getType() << From->getSourceRange() << T; 4887 SCS = &ICS.Standard; 4888 break; 4889 case ImplicitConversionSequence::UserDefinedConversion: 4890 // We are converting from class type to an integral or enumeration type, so 4891 // the Before sequence must be trivial. 4892 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4893 return Diag(From->getLocStart(), 4894 diag::err_typecheck_converted_constant_expression_disallowed) 4895 << From->getType() << From->getSourceRange() << T; 4896 SCS = &ICS.UserDefined.After; 4897 break; 4898 case ImplicitConversionSequence::AmbiguousConversion: 4899 case ImplicitConversionSequence::BadConversion: 4900 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4901 return Diag(From->getLocStart(), 4902 diag::err_typecheck_converted_constant_expression) 4903 << From->getType() << From->getSourceRange() << T; 4904 return ExprError(); 4905 4906 case ImplicitConversionSequence::EllipsisConversion: 4907 llvm_unreachable("ellipsis conversion in converted constant expression"); 4908 } 4909 4910 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4911 if (Result.isInvalid()) 4912 return Result; 4913 4914 // Check for a narrowing implicit conversion. 4915 APValue PreNarrowingValue; 4916 QualType PreNarrowingType; 4917 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4918 PreNarrowingType)) { 4919 case NK_Variable_Narrowing: 4920 // Implicit conversion to a narrower type, and the value is not a constant 4921 // expression. We'll diagnose this in a moment. 4922 case NK_Not_Narrowing: 4923 break; 4924 4925 case NK_Constant_Narrowing: 4926 Diag(From->getLocStart(), 4927 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4928 diag::err_cce_narrowing) 4929 << CCE << /*Constant*/1 4930 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4931 break; 4932 4933 case NK_Type_Narrowing: 4934 Diag(From->getLocStart(), 4935 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4936 diag::err_cce_narrowing) 4937 << CCE << /*Constant*/0 << From->getType() << T; 4938 break; 4939 } 4940 4941 // Check the expression is a constant expression. 4942 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4943 Expr::EvalResult Eval; 4944 Eval.Diag = &Notes; 4945 4946 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4947 // The expression can't be folded, so we can't keep it at this position in 4948 // the AST. 4949 Result = ExprError(); 4950 } else { 4951 Value = Eval.Val.getInt(); 4952 4953 if (Notes.empty()) { 4954 // It's a constant expression. 4955 return Result; 4956 } 4957 } 4958 4959 // It's not a constant expression. Produce an appropriate diagnostic. 4960 if (Notes.size() == 1 && 4961 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4962 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4963 else { 4964 Diag(From->getLocStart(), diag::err_expr_not_cce) 4965 << CCE << From->getSourceRange(); 4966 for (unsigned I = 0; I < Notes.size(); ++I) 4967 Diag(Notes[I].first, Notes[I].second); 4968 } 4969 return Result; 4970} 4971 4972/// dropPointerConversions - If the given standard conversion sequence 4973/// involves any pointer conversions, remove them. This may change 4974/// the result type of the conversion sequence. 4975static void dropPointerConversion(StandardConversionSequence &SCS) { 4976 if (SCS.Second == ICK_Pointer_Conversion) { 4977 SCS.Second = ICK_Identity; 4978 SCS.Third = ICK_Identity; 4979 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4980 } 4981} 4982 4983/// TryContextuallyConvertToObjCPointer - Attempt to contextually 4984/// convert the expression From to an Objective-C pointer type. 4985static ImplicitConversionSequence 4986TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4987 // Do an implicit conversion to 'id'. 4988 QualType Ty = S.Context.getObjCIdType(); 4989 ImplicitConversionSequence ICS 4990 = TryImplicitConversion(S, From, Ty, 4991 // FIXME: Are these flags correct? 4992 /*SuppressUserConversions=*/false, 4993 /*AllowExplicit=*/true, 4994 /*InOverloadResolution=*/false, 4995 /*CStyle=*/false, 4996 /*AllowObjCWritebackConversion=*/false); 4997 4998 // Strip off any final conversions to 'id'. 4999 switch (ICS.getKind()) { 5000 case ImplicitConversionSequence::BadConversion: 5001 case ImplicitConversionSequence::AmbiguousConversion: 5002 case ImplicitConversionSequence::EllipsisConversion: 5003 break; 5004 5005 case ImplicitConversionSequence::UserDefinedConversion: 5006 dropPointerConversion(ICS.UserDefined.After); 5007 break; 5008 5009 case ImplicitConversionSequence::StandardConversion: 5010 dropPointerConversion(ICS.Standard); 5011 break; 5012 } 5013 5014 return ICS; 5015} 5016 5017/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5018/// conversion of the expression From to an Objective-C pointer type. 5019ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5020 if (checkPlaceholderForOverload(*this, From)) 5021 return ExprError(); 5022 5023 QualType Ty = Context.getObjCIdType(); 5024 ImplicitConversionSequence ICS = 5025 TryContextuallyConvertToObjCPointer(*this, From); 5026 if (!ICS.isBad()) 5027 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5028 return ExprError(); 5029} 5030 5031/// Determine whether the provided type is an integral type, or an enumeration 5032/// type of a permitted flavor. 5033static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5034 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5035 : T->isIntegralOrUnscopedEnumerationType(); 5036} 5037 5038/// \brief Attempt to convert the given expression to an integral or 5039/// enumeration type. 5040/// 5041/// This routine will attempt to convert an expression of class type to an 5042/// integral or enumeration type, if that class type only has a single 5043/// conversion to an integral or enumeration type. 5044/// 5045/// \param Loc The source location of the construct that requires the 5046/// conversion. 5047/// 5048/// \param From The expression we're converting from. 5049/// 5050/// \param Diagnoser Used to output any diagnostics. 5051/// 5052/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5053/// enumerations should be considered. 5054/// 5055/// \returns The expression, converted to an integral or enumeration type if 5056/// successful. 5057ExprResult 5058Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5059 ICEConvertDiagnoser &Diagnoser, 5060 bool AllowScopedEnumerations) { 5061 // We can't perform any more checking for type-dependent expressions. 5062 if (From->isTypeDependent()) 5063 return Owned(From); 5064 5065 // Process placeholders immediately. 5066 if (From->hasPlaceholderType()) { 5067 ExprResult result = CheckPlaceholderExpr(From); 5068 if (result.isInvalid()) return result; 5069 From = result.take(); 5070 } 5071 5072 // If the expression already has integral or enumeration type, we're golden. 5073 QualType T = From->getType(); 5074 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5075 return DefaultLvalueConversion(From); 5076 5077 // FIXME: Check for missing '()' if T is a function type? 5078 5079 // If we don't have a class type in C++, there's no way we can get an 5080 // expression of integral or enumeration type. 5081 const RecordType *RecordTy = T->getAs<RecordType>(); 5082 if (!RecordTy || !getLangOpts().CPlusPlus) { 5083 if (!Diagnoser.Suppress) 5084 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5085 return Owned(From); 5086 } 5087 5088 // We must have a complete class type. 5089 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5090 ICEConvertDiagnoser &Diagnoser; 5091 Expr *From; 5092 5093 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5094 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5095 5096 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5097 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5098 } 5099 } IncompleteDiagnoser(Diagnoser, From); 5100 5101 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5102 return Owned(From); 5103 5104 // Look for a conversion to an integral or enumeration type. 5105 UnresolvedSet<4> ViableConversions; 5106 UnresolvedSet<4> ExplicitConversions; 5107 const UnresolvedSetImpl *Conversions 5108 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5109 5110 bool HadMultipleCandidates = (Conversions->size() > 1); 5111 5112 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5113 E = Conversions->end(); 5114 I != E; 5115 ++I) { 5116 if (CXXConversionDecl *Conversion 5117 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5118 if (isIntegralOrEnumerationType( 5119 Conversion->getConversionType().getNonReferenceType(), 5120 AllowScopedEnumerations)) { 5121 if (Conversion->isExplicit()) 5122 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5123 else 5124 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5125 } 5126 } 5127 } 5128 5129 switch (ViableConversions.size()) { 5130 case 0: 5131 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5132 DeclAccessPair Found = ExplicitConversions[0]; 5133 CXXConversionDecl *Conversion 5134 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5135 5136 // The user probably meant to invoke the given explicit 5137 // conversion; use it. 5138 QualType ConvTy 5139 = Conversion->getConversionType().getNonReferenceType(); 5140 std::string TypeStr; 5141 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5142 5143 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5144 << FixItHint::CreateInsertion(From->getLocStart(), 5145 "static_cast<" + TypeStr + ">(") 5146 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5147 ")"); 5148 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5149 5150 // If we aren't in a SFINAE context, build a call to the 5151 // explicit conversion function. 5152 if (isSFINAEContext()) 5153 return ExprError(); 5154 5155 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5156 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5157 HadMultipleCandidates); 5158 if (Result.isInvalid()) 5159 return ExprError(); 5160 // Record usage of conversion in an implicit cast. 5161 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5162 CK_UserDefinedConversion, 5163 Result.get(), 0, 5164 Result.get()->getValueKind()); 5165 } 5166 5167 // We'll complain below about a non-integral condition type. 5168 break; 5169 5170 case 1: { 5171 // Apply this conversion. 5172 DeclAccessPair Found = ViableConversions[0]; 5173 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5174 5175 CXXConversionDecl *Conversion 5176 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5177 QualType ConvTy 5178 = Conversion->getConversionType().getNonReferenceType(); 5179 if (!Diagnoser.SuppressConversion) { 5180 if (isSFINAEContext()) 5181 return ExprError(); 5182 5183 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5184 << From->getSourceRange(); 5185 } 5186 5187 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5188 HadMultipleCandidates); 5189 if (Result.isInvalid()) 5190 return ExprError(); 5191 // Record usage of conversion in an implicit cast. 5192 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5193 CK_UserDefinedConversion, 5194 Result.get(), 0, 5195 Result.get()->getValueKind()); 5196 break; 5197 } 5198 5199 default: 5200 if (Diagnoser.Suppress) 5201 return ExprError(); 5202 5203 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5205 CXXConversionDecl *Conv 5206 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5207 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5208 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5209 } 5210 return Owned(From); 5211 } 5212 5213 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5214 !Diagnoser.Suppress) { 5215 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5216 << From->getSourceRange(); 5217 } 5218 5219 return DefaultLvalueConversion(From); 5220} 5221 5222/// AddOverloadCandidate - Adds the given function to the set of 5223/// candidate functions, using the given function call arguments. If 5224/// @p SuppressUserConversions, then don't allow user-defined 5225/// conversions via constructors or conversion operators. 5226/// 5227/// \param PartialOverloading true if we are performing "partial" overloading 5228/// based on an incomplete set of function arguments. This feature is used by 5229/// code completion. 5230void 5231Sema::AddOverloadCandidate(FunctionDecl *Function, 5232 DeclAccessPair FoundDecl, 5233 llvm::ArrayRef<Expr *> Args, 5234 OverloadCandidateSet& CandidateSet, 5235 bool SuppressUserConversions, 5236 bool PartialOverloading, 5237 bool AllowExplicit) { 5238 const FunctionProtoType* Proto 5239 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5240 assert(Proto && "Functions without a prototype cannot be overloaded"); 5241 assert(!Function->getDescribedFunctionTemplate() && 5242 "Use AddTemplateOverloadCandidate for function templates"); 5243 5244 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5245 if (!isa<CXXConstructorDecl>(Method)) { 5246 // If we get here, it's because we're calling a member function 5247 // that is named without a member access expression (e.g., 5248 // "this->f") that was either written explicitly or created 5249 // implicitly. This can happen with a qualified call to a member 5250 // function, e.g., X::f(). We use an empty type for the implied 5251 // object argument (C++ [over.call.func]p3), and the acting context 5252 // is irrelevant. 5253 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5254 QualType(), Expr::Classification::makeSimpleLValue(), 5255 Args, CandidateSet, SuppressUserConversions); 5256 return; 5257 } 5258 // We treat a constructor like a non-member function, since its object 5259 // argument doesn't participate in overload resolution. 5260 } 5261 5262 if (!CandidateSet.isNewCandidate(Function)) 5263 return; 5264 5265 // Overload resolution is always an unevaluated context. 5266 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5267 5268 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5269 // C++ [class.copy]p3: 5270 // A member function template is never instantiated to perform the copy 5271 // of a class object to an object of its class type. 5272 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5273 if (Args.size() == 1 && 5274 Constructor->isSpecializationCopyingObject() && 5275 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5276 IsDerivedFrom(Args[0]->getType(), ClassType))) 5277 return; 5278 } 5279 5280 // Add this candidate 5281 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5282 Candidate.FoundDecl = FoundDecl; 5283 Candidate.Function = Function; 5284 Candidate.Viable = true; 5285 Candidate.IsSurrogate = false; 5286 Candidate.IgnoreObjectArgument = false; 5287 Candidate.ExplicitCallArguments = Args.size(); 5288 5289 unsigned NumArgsInProto = Proto->getNumArgs(); 5290 5291 // (C++ 13.3.2p2): A candidate function having fewer than m 5292 // parameters is viable only if it has an ellipsis in its parameter 5293 // list (8.3.5). 5294 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5295 !Proto->isVariadic()) { 5296 Candidate.Viable = false; 5297 Candidate.FailureKind = ovl_fail_too_many_arguments; 5298 return; 5299 } 5300 5301 // (C++ 13.3.2p2): A candidate function having more than m parameters 5302 // is viable only if the (m+1)st parameter has a default argument 5303 // (8.3.6). For the purposes of overload resolution, the 5304 // parameter list is truncated on the right, so that there are 5305 // exactly m parameters. 5306 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5307 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5308 // Not enough arguments. 5309 Candidate.Viable = false; 5310 Candidate.FailureKind = ovl_fail_too_few_arguments; 5311 return; 5312 } 5313 5314 // (CUDA B.1): Check for invalid calls between targets. 5315 if (getLangOpts().CUDA) 5316 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5317 if (CheckCUDATarget(Caller, Function)) { 5318 Candidate.Viable = false; 5319 Candidate.FailureKind = ovl_fail_bad_target; 5320 return; 5321 } 5322 5323 // Determine the implicit conversion sequences for each of the 5324 // arguments. 5325 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5326 if (ArgIdx < NumArgsInProto) { 5327 // (C++ 13.3.2p3): for F to be a viable function, there shall 5328 // exist for each argument an implicit conversion sequence 5329 // (13.3.3.1) that converts that argument to the corresponding 5330 // parameter of F. 5331 QualType ParamType = Proto->getArgType(ArgIdx); 5332 Candidate.Conversions[ArgIdx] 5333 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5334 SuppressUserConversions, 5335 /*InOverloadResolution=*/true, 5336 /*AllowObjCWritebackConversion=*/ 5337 getLangOpts().ObjCAutoRefCount, 5338 AllowExplicit); 5339 if (Candidate.Conversions[ArgIdx].isBad()) { 5340 Candidate.Viable = false; 5341 Candidate.FailureKind = ovl_fail_bad_conversion; 5342 break; 5343 } 5344 } else { 5345 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5346 // argument for which there is no corresponding parameter is 5347 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5348 Candidate.Conversions[ArgIdx].setEllipsis(); 5349 } 5350 } 5351} 5352 5353/// \brief Add all of the function declarations in the given function set to 5354/// the overload canddiate set. 5355void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5356 llvm::ArrayRef<Expr *> Args, 5357 OverloadCandidateSet& CandidateSet, 5358 bool SuppressUserConversions, 5359 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5360 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5361 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5362 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5363 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5364 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5365 cast<CXXMethodDecl>(FD)->getParent(), 5366 Args[0]->getType(), Args[0]->Classify(Context), 5367 Args.slice(1), CandidateSet, 5368 SuppressUserConversions); 5369 else 5370 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5371 SuppressUserConversions); 5372 } else { 5373 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5374 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5375 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5376 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5377 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5378 ExplicitTemplateArgs, 5379 Args[0]->getType(), 5380 Args[0]->Classify(Context), Args.slice(1), 5381 CandidateSet, SuppressUserConversions); 5382 else 5383 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5384 ExplicitTemplateArgs, Args, 5385 CandidateSet, SuppressUserConversions); 5386 } 5387 } 5388} 5389 5390/// AddMethodCandidate - Adds a named decl (which is some kind of 5391/// method) as a method candidate to the given overload set. 5392void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5393 QualType ObjectType, 5394 Expr::Classification ObjectClassification, 5395 Expr **Args, unsigned NumArgs, 5396 OverloadCandidateSet& CandidateSet, 5397 bool SuppressUserConversions) { 5398 NamedDecl *Decl = FoundDecl.getDecl(); 5399 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5400 5401 if (isa<UsingShadowDecl>(Decl)) 5402 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5403 5404 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5405 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5406 "Expected a member function template"); 5407 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5408 /*ExplicitArgs*/ 0, 5409 ObjectType, ObjectClassification, 5410 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5411 SuppressUserConversions); 5412 } else { 5413 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5414 ObjectType, ObjectClassification, 5415 llvm::makeArrayRef(Args, NumArgs), 5416 CandidateSet, SuppressUserConversions); 5417 } 5418} 5419 5420/// AddMethodCandidate - Adds the given C++ member function to the set 5421/// of candidate functions, using the given function call arguments 5422/// and the object argument (@c Object). For example, in a call 5423/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5424/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5425/// allow user-defined conversions via constructors or conversion 5426/// operators. 5427void 5428Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5429 CXXRecordDecl *ActingContext, QualType ObjectType, 5430 Expr::Classification ObjectClassification, 5431 llvm::ArrayRef<Expr *> Args, 5432 OverloadCandidateSet& CandidateSet, 5433 bool SuppressUserConversions) { 5434 const FunctionProtoType* Proto 5435 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5436 assert(Proto && "Methods without a prototype cannot be overloaded"); 5437 assert(!isa<CXXConstructorDecl>(Method) && 5438 "Use AddOverloadCandidate for constructors"); 5439 5440 if (!CandidateSet.isNewCandidate(Method)) 5441 return; 5442 5443 // Overload resolution is always an unevaluated context. 5444 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5445 5446 // Add this candidate 5447 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5448 Candidate.FoundDecl = FoundDecl; 5449 Candidate.Function = Method; 5450 Candidate.IsSurrogate = false; 5451 Candidate.IgnoreObjectArgument = false; 5452 Candidate.ExplicitCallArguments = Args.size(); 5453 5454 unsigned NumArgsInProto = Proto->getNumArgs(); 5455 5456 // (C++ 13.3.2p2): A candidate function having fewer than m 5457 // parameters is viable only if it has an ellipsis in its parameter 5458 // list (8.3.5). 5459 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5460 Candidate.Viable = false; 5461 Candidate.FailureKind = ovl_fail_too_many_arguments; 5462 return; 5463 } 5464 5465 // (C++ 13.3.2p2): A candidate function having more than m parameters 5466 // is viable only if the (m+1)st parameter has a default argument 5467 // (8.3.6). For the purposes of overload resolution, the 5468 // parameter list is truncated on the right, so that there are 5469 // exactly m parameters. 5470 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5471 if (Args.size() < MinRequiredArgs) { 5472 // Not enough arguments. 5473 Candidate.Viable = false; 5474 Candidate.FailureKind = ovl_fail_too_few_arguments; 5475 return; 5476 } 5477 5478 Candidate.Viable = true; 5479 5480 if (Method->isStatic() || ObjectType.isNull()) 5481 // The implicit object argument is ignored. 5482 Candidate.IgnoreObjectArgument = true; 5483 else { 5484 // Determine the implicit conversion sequence for the object 5485 // parameter. 5486 Candidate.Conversions[0] 5487 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5488 Method, ActingContext); 5489 if (Candidate.Conversions[0].isBad()) { 5490 Candidate.Viable = false; 5491 Candidate.FailureKind = ovl_fail_bad_conversion; 5492 return; 5493 } 5494 } 5495 5496 // Determine the implicit conversion sequences for each of the 5497 // arguments. 5498 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5499 if (ArgIdx < NumArgsInProto) { 5500 // (C++ 13.3.2p3): for F to be a viable function, there shall 5501 // exist for each argument an implicit conversion sequence 5502 // (13.3.3.1) that converts that argument to the corresponding 5503 // parameter of F. 5504 QualType ParamType = Proto->getArgType(ArgIdx); 5505 Candidate.Conversions[ArgIdx + 1] 5506 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5507 SuppressUserConversions, 5508 /*InOverloadResolution=*/true, 5509 /*AllowObjCWritebackConversion=*/ 5510 getLangOpts().ObjCAutoRefCount); 5511 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5512 Candidate.Viable = false; 5513 Candidate.FailureKind = ovl_fail_bad_conversion; 5514 break; 5515 } 5516 } else { 5517 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5518 // argument for which there is no corresponding parameter is 5519 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5520 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5521 } 5522 } 5523} 5524 5525/// \brief Add a C++ member function template as a candidate to the candidate 5526/// set, using template argument deduction to produce an appropriate member 5527/// function template specialization. 5528void 5529Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5530 DeclAccessPair FoundDecl, 5531 CXXRecordDecl *ActingContext, 5532 TemplateArgumentListInfo *ExplicitTemplateArgs, 5533 QualType ObjectType, 5534 Expr::Classification ObjectClassification, 5535 llvm::ArrayRef<Expr *> Args, 5536 OverloadCandidateSet& CandidateSet, 5537 bool SuppressUserConversions) { 5538 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5539 return; 5540 5541 // C++ [over.match.funcs]p7: 5542 // In each case where a candidate is a function template, candidate 5543 // function template specializations are generated using template argument 5544 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5545 // candidate functions in the usual way.113) A given name can refer to one 5546 // or more function templates and also to a set of overloaded non-template 5547 // functions. In such a case, the candidate functions generated from each 5548 // function template are combined with the set of non-template candidate 5549 // functions. 5550 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5551 FunctionDecl *Specialization = 0; 5552 if (TemplateDeductionResult Result 5553 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5554 Specialization, Info)) { 5555 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5556 Candidate.FoundDecl = FoundDecl; 5557 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5558 Candidate.Viable = false; 5559 Candidate.FailureKind = ovl_fail_bad_deduction; 5560 Candidate.IsSurrogate = false; 5561 Candidate.IgnoreObjectArgument = false; 5562 Candidate.ExplicitCallArguments = Args.size(); 5563 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5564 Info); 5565 return; 5566 } 5567 5568 // Add the function template specialization produced by template argument 5569 // deduction as a candidate. 5570 assert(Specialization && "Missing member function template specialization?"); 5571 assert(isa<CXXMethodDecl>(Specialization) && 5572 "Specialization is not a member function?"); 5573 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5574 ActingContext, ObjectType, ObjectClassification, Args, 5575 CandidateSet, SuppressUserConversions); 5576} 5577 5578/// \brief Add a C++ function template specialization as a candidate 5579/// in the candidate set, using template argument deduction to produce 5580/// an appropriate function template specialization. 5581void 5582Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5583 DeclAccessPair FoundDecl, 5584 TemplateArgumentListInfo *ExplicitTemplateArgs, 5585 llvm::ArrayRef<Expr *> Args, 5586 OverloadCandidateSet& CandidateSet, 5587 bool SuppressUserConversions) { 5588 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5589 return; 5590 5591 // C++ [over.match.funcs]p7: 5592 // In each case where a candidate is a function template, candidate 5593 // function template specializations are generated using template argument 5594 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5595 // candidate functions in the usual way.113) A given name can refer to one 5596 // or more function templates and also to a set of overloaded non-template 5597 // functions. In such a case, the candidate functions generated from each 5598 // function template are combined with the set of non-template candidate 5599 // functions. 5600 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5601 FunctionDecl *Specialization = 0; 5602 if (TemplateDeductionResult Result 5603 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5604 Specialization, Info)) { 5605 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5606 Candidate.FoundDecl = FoundDecl; 5607 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5608 Candidate.Viable = false; 5609 Candidate.FailureKind = ovl_fail_bad_deduction; 5610 Candidate.IsSurrogate = false; 5611 Candidate.IgnoreObjectArgument = false; 5612 Candidate.ExplicitCallArguments = Args.size(); 5613 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5614 Info); 5615 return; 5616 } 5617 5618 // Add the function template specialization produced by template argument 5619 // deduction as a candidate. 5620 assert(Specialization && "Missing function template specialization?"); 5621 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5622 SuppressUserConversions); 5623} 5624 5625/// AddConversionCandidate - Add a C++ conversion function as a 5626/// candidate in the candidate set (C++ [over.match.conv], 5627/// C++ [over.match.copy]). From is the expression we're converting from, 5628/// and ToType is the type that we're eventually trying to convert to 5629/// (which may or may not be the same type as the type that the 5630/// conversion function produces). 5631void 5632Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5633 DeclAccessPair FoundDecl, 5634 CXXRecordDecl *ActingContext, 5635 Expr *From, QualType ToType, 5636 OverloadCandidateSet& CandidateSet) { 5637 assert(!Conversion->getDescribedFunctionTemplate() && 5638 "Conversion function templates use AddTemplateConversionCandidate"); 5639 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5640 if (!CandidateSet.isNewCandidate(Conversion)) 5641 return; 5642 5643 // Overload resolution is always an unevaluated context. 5644 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5645 5646 // Add this candidate 5647 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5648 Candidate.FoundDecl = FoundDecl; 5649 Candidate.Function = Conversion; 5650 Candidate.IsSurrogate = false; 5651 Candidate.IgnoreObjectArgument = false; 5652 Candidate.FinalConversion.setAsIdentityConversion(); 5653 Candidate.FinalConversion.setFromType(ConvType); 5654 Candidate.FinalConversion.setAllToTypes(ToType); 5655 Candidate.Viable = true; 5656 Candidate.ExplicitCallArguments = 1; 5657 5658 // C++ [over.match.funcs]p4: 5659 // For conversion functions, the function is considered to be a member of 5660 // the class of the implicit implied object argument for the purpose of 5661 // defining the type of the implicit object parameter. 5662 // 5663 // Determine the implicit conversion sequence for the implicit 5664 // object parameter. 5665 QualType ImplicitParamType = From->getType(); 5666 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5667 ImplicitParamType = FromPtrType->getPointeeType(); 5668 CXXRecordDecl *ConversionContext 5669 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5670 5671 Candidate.Conversions[0] 5672 = TryObjectArgumentInitialization(*this, From->getType(), 5673 From->Classify(Context), 5674 Conversion, ConversionContext); 5675 5676 if (Candidate.Conversions[0].isBad()) { 5677 Candidate.Viable = false; 5678 Candidate.FailureKind = ovl_fail_bad_conversion; 5679 return; 5680 } 5681 5682 // We won't go through a user-define type conversion function to convert a 5683 // derived to base as such conversions are given Conversion Rank. They only 5684 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5685 QualType FromCanon 5686 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5687 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5688 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5689 Candidate.Viable = false; 5690 Candidate.FailureKind = ovl_fail_trivial_conversion; 5691 return; 5692 } 5693 5694 // To determine what the conversion from the result of calling the 5695 // conversion function to the type we're eventually trying to 5696 // convert to (ToType), we need to synthesize a call to the 5697 // conversion function and attempt copy initialization from it. This 5698 // makes sure that we get the right semantics with respect to 5699 // lvalues/rvalues and the type. Fortunately, we can allocate this 5700 // call on the stack and we don't need its arguments to be 5701 // well-formed. 5702 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5703 VK_LValue, From->getLocStart()); 5704 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5705 Context.getPointerType(Conversion->getType()), 5706 CK_FunctionToPointerDecay, 5707 &ConversionRef, VK_RValue); 5708 5709 QualType ConversionType = Conversion->getConversionType(); 5710 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5711 Candidate.Viable = false; 5712 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5713 return; 5714 } 5715 5716 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5717 5718 // Note that it is safe to allocate CallExpr on the stack here because 5719 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5720 // allocator). 5721 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5722 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5723 From->getLocStart()); 5724 ImplicitConversionSequence ICS = 5725 TryCopyInitialization(*this, &Call, ToType, 5726 /*SuppressUserConversions=*/true, 5727 /*InOverloadResolution=*/false, 5728 /*AllowObjCWritebackConversion=*/false); 5729 5730 switch (ICS.getKind()) { 5731 case ImplicitConversionSequence::StandardConversion: 5732 Candidate.FinalConversion = ICS.Standard; 5733 5734 // C++ [over.ics.user]p3: 5735 // If the user-defined conversion is specified by a specialization of a 5736 // conversion function template, the second standard conversion sequence 5737 // shall have exact match rank. 5738 if (Conversion->getPrimaryTemplate() && 5739 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5740 Candidate.Viable = false; 5741 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5742 } 5743 5744 // C++0x [dcl.init.ref]p5: 5745 // In the second case, if the reference is an rvalue reference and 5746 // the second standard conversion sequence of the user-defined 5747 // conversion sequence includes an lvalue-to-rvalue conversion, the 5748 // program is ill-formed. 5749 if (ToType->isRValueReferenceType() && 5750 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5751 Candidate.Viable = false; 5752 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5753 } 5754 break; 5755 5756 case ImplicitConversionSequence::BadConversion: 5757 Candidate.Viable = false; 5758 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5759 break; 5760 5761 default: 5762 llvm_unreachable( 5763 "Can only end up with a standard conversion sequence or failure"); 5764 } 5765} 5766 5767/// \brief Adds a conversion function template specialization 5768/// candidate to the overload set, using template argument deduction 5769/// to deduce the template arguments of the conversion function 5770/// template from the type that we are converting to (C++ 5771/// [temp.deduct.conv]). 5772void 5773Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5774 DeclAccessPair FoundDecl, 5775 CXXRecordDecl *ActingDC, 5776 Expr *From, QualType ToType, 5777 OverloadCandidateSet &CandidateSet) { 5778 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5779 "Only conversion function templates permitted here"); 5780 5781 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5782 return; 5783 5784 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5785 CXXConversionDecl *Specialization = 0; 5786 if (TemplateDeductionResult Result 5787 = DeduceTemplateArguments(FunctionTemplate, ToType, 5788 Specialization, Info)) { 5789 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5790 Candidate.FoundDecl = FoundDecl; 5791 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5792 Candidate.Viable = false; 5793 Candidate.FailureKind = ovl_fail_bad_deduction; 5794 Candidate.IsSurrogate = false; 5795 Candidate.IgnoreObjectArgument = false; 5796 Candidate.ExplicitCallArguments = 1; 5797 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5798 Info); 5799 return; 5800 } 5801 5802 // Add the conversion function template specialization produced by 5803 // template argument deduction as a candidate. 5804 assert(Specialization && "Missing function template specialization?"); 5805 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5806 CandidateSet); 5807} 5808 5809/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5810/// converts the given @c Object to a function pointer via the 5811/// conversion function @c Conversion, and then attempts to call it 5812/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5813/// the type of function that we'll eventually be calling. 5814void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5815 DeclAccessPair FoundDecl, 5816 CXXRecordDecl *ActingContext, 5817 const FunctionProtoType *Proto, 5818 Expr *Object, 5819 llvm::ArrayRef<Expr *> Args, 5820 OverloadCandidateSet& CandidateSet) { 5821 if (!CandidateSet.isNewCandidate(Conversion)) 5822 return; 5823 5824 // Overload resolution is always an unevaluated context. 5825 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5826 5827 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5828 Candidate.FoundDecl = FoundDecl; 5829 Candidate.Function = 0; 5830 Candidate.Surrogate = Conversion; 5831 Candidate.Viable = true; 5832 Candidate.IsSurrogate = true; 5833 Candidate.IgnoreObjectArgument = false; 5834 Candidate.ExplicitCallArguments = Args.size(); 5835 5836 // Determine the implicit conversion sequence for the implicit 5837 // object parameter. 5838 ImplicitConversionSequence ObjectInit 5839 = TryObjectArgumentInitialization(*this, Object->getType(), 5840 Object->Classify(Context), 5841 Conversion, ActingContext); 5842 if (ObjectInit.isBad()) { 5843 Candidate.Viable = false; 5844 Candidate.FailureKind = ovl_fail_bad_conversion; 5845 Candidate.Conversions[0] = ObjectInit; 5846 return; 5847 } 5848 5849 // The first conversion is actually a user-defined conversion whose 5850 // first conversion is ObjectInit's standard conversion (which is 5851 // effectively a reference binding). Record it as such. 5852 Candidate.Conversions[0].setUserDefined(); 5853 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5854 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5855 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5856 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5857 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5858 Candidate.Conversions[0].UserDefined.After 5859 = Candidate.Conversions[0].UserDefined.Before; 5860 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5861 5862 // Find the 5863 unsigned NumArgsInProto = Proto->getNumArgs(); 5864 5865 // (C++ 13.3.2p2): A candidate function having fewer than m 5866 // parameters is viable only if it has an ellipsis in its parameter 5867 // list (8.3.5). 5868 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5869 Candidate.Viable = false; 5870 Candidate.FailureKind = ovl_fail_too_many_arguments; 5871 return; 5872 } 5873 5874 // Function types don't have any default arguments, so just check if 5875 // we have enough arguments. 5876 if (Args.size() < NumArgsInProto) { 5877 // Not enough arguments. 5878 Candidate.Viable = false; 5879 Candidate.FailureKind = ovl_fail_too_few_arguments; 5880 return; 5881 } 5882 5883 // Determine the implicit conversion sequences for each of the 5884 // arguments. 5885 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5886 if (ArgIdx < NumArgsInProto) { 5887 // (C++ 13.3.2p3): for F to be a viable function, there shall 5888 // exist for each argument an implicit conversion sequence 5889 // (13.3.3.1) that converts that argument to the corresponding 5890 // parameter of F. 5891 QualType ParamType = Proto->getArgType(ArgIdx); 5892 Candidate.Conversions[ArgIdx + 1] 5893 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5894 /*SuppressUserConversions=*/false, 5895 /*InOverloadResolution=*/false, 5896 /*AllowObjCWritebackConversion=*/ 5897 getLangOpts().ObjCAutoRefCount); 5898 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5899 Candidate.Viable = false; 5900 Candidate.FailureKind = ovl_fail_bad_conversion; 5901 break; 5902 } 5903 } else { 5904 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5905 // argument for which there is no corresponding parameter is 5906 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5907 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5908 } 5909 } 5910} 5911 5912/// \brief Add overload candidates for overloaded operators that are 5913/// member functions. 5914/// 5915/// Add the overloaded operator candidates that are member functions 5916/// for the operator Op that was used in an operator expression such 5917/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5918/// CandidateSet will store the added overload candidates. (C++ 5919/// [over.match.oper]). 5920void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5921 SourceLocation OpLoc, 5922 Expr **Args, unsigned NumArgs, 5923 OverloadCandidateSet& CandidateSet, 5924 SourceRange OpRange) { 5925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5926 5927 // C++ [over.match.oper]p3: 5928 // For a unary operator @ with an operand of a type whose 5929 // cv-unqualified version is T1, and for a binary operator @ with 5930 // a left operand of a type whose cv-unqualified version is T1 and 5931 // a right operand of a type whose cv-unqualified version is T2, 5932 // three sets of candidate functions, designated member 5933 // candidates, non-member candidates and built-in candidates, are 5934 // constructed as follows: 5935 QualType T1 = Args[0]->getType(); 5936 5937 // -- If T1 is a class type, the set of member candidates is the 5938 // result of the qualified lookup of T1::operator@ 5939 // (13.3.1.1.1); otherwise, the set of member candidates is 5940 // empty. 5941 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5942 // Complete the type if it can be completed. Otherwise, we're done. 5943 if (RequireCompleteType(OpLoc, T1, 0)) 5944 return; 5945 5946 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5947 LookupQualifiedName(Operators, T1Rec->getDecl()); 5948 Operators.suppressDiagnostics(); 5949 5950 for (LookupResult::iterator Oper = Operators.begin(), 5951 OperEnd = Operators.end(); 5952 Oper != OperEnd; 5953 ++Oper) 5954 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5955 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5956 CandidateSet, 5957 /* SuppressUserConversions = */ false); 5958 } 5959} 5960 5961/// AddBuiltinCandidate - Add a candidate for a built-in 5962/// operator. ResultTy and ParamTys are the result and parameter types 5963/// of the built-in candidate, respectively. Args and NumArgs are the 5964/// arguments being passed to the candidate. IsAssignmentOperator 5965/// should be true when this built-in candidate is an assignment 5966/// operator. NumContextualBoolArguments is the number of arguments 5967/// (at the beginning of the argument list) that will be contextually 5968/// converted to bool. 5969void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5970 Expr **Args, unsigned NumArgs, 5971 OverloadCandidateSet& CandidateSet, 5972 bool IsAssignmentOperator, 5973 unsigned NumContextualBoolArguments) { 5974 // Overload resolution is always an unevaluated context. 5975 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5976 5977 // Add this candidate 5978 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5979 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5980 Candidate.Function = 0; 5981 Candidate.IsSurrogate = false; 5982 Candidate.IgnoreObjectArgument = false; 5983 Candidate.BuiltinTypes.ResultTy = ResultTy; 5984 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5985 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5986 5987 // Determine the implicit conversion sequences for each of the 5988 // arguments. 5989 Candidate.Viable = true; 5990 Candidate.ExplicitCallArguments = NumArgs; 5991 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5992 // C++ [over.match.oper]p4: 5993 // For the built-in assignment operators, conversions of the 5994 // left operand are restricted as follows: 5995 // -- no temporaries are introduced to hold the left operand, and 5996 // -- no user-defined conversions are applied to the left 5997 // operand to achieve a type match with the left-most 5998 // parameter of a built-in candidate. 5999 // 6000 // We block these conversions by turning off user-defined 6001 // conversions, since that is the only way that initialization of 6002 // a reference to a non-class type can occur from something that 6003 // is not of the same type. 6004 if (ArgIdx < NumContextualBoolArguments) { 6005 assert(ParamTys[ArgIdx] == Context.BoolTy && 6006 "Contextual conversion to bool requires bool type"); 6007 Candidate.Conversions[ArgIdx] 6008 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6009 } else { 6010 Candidate.Conversions[ArgIdx] 6011 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6012 ArgIdx == 0 && IsAssignmentOperator, 6013 /*InOverloadResolution=*/false, 6014 /*AllowObjCWritebackConversion=*/ 6015 getLangOpts().ObjCAutoRefCount); 6016 } 6017 if (Candidate.Conversions[ArgIdx].isBad()) { 6018 Candidate.Viable = false; 6019 Candidate.FailureKind = ovl_fail_bad_conversion; 6020 break; 6021 } 6022 } 6023} 6024 6025/// BuiltinCandidateTypeSet - A set of types that will be used for the 6026/// candidate operator functions for built-in operators (C++ 6027/// [over.built]). The types are separated into pointer types and 6028/// enumeration types. 6029class BuiltinCandidateTypeSet { 6030 /// TypeSet - A set of types. 6031 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6032 6033 /// PointerTypes - The set of pointer types that will be used in the 6034 /// built-in candidates. 6035 TypeSet PointerTypes; 6036 6037 /// MemberPointerTypes - The set of member pointer types that will be 6038 /// used in the built-in candidates. 6039 TypeSet MemberPointerTypes; 6040 6041 /// EnumerationTypes - The set of enumeration types that will be 6042 /// used in the built-in candidates. 6043 TypeSet EnumerationTypes; 6044 6045 /// \brief The set of vector types that will be used in the built-in 6046 /// candidates. 6047 TypeSet VectorTypes; 6048 6049 /// \brief A flag indicating non-record types are viable candidates 6050 bool HasNonRecordTypes; 6051 6052 /// \brief A flag indicating whether either arithmetic or enumeration types 6053 /// were present in the candidate set. 6054 bool HasArithmeticOrEnumeralTypes; 6055 6056 /// \brief A flag indicating whether the nullptr type was present in the 6057 /// candidate set. 6058 bool HasNullPtrType; 6059 6060 /// Sema - The semantic analysis instance where we are building the 6061 /// candidate type set. 6062 Sema &SemaRef; 6063 6064 /// Context - The AST context in which we will build the type sets. 6065 ASTContext &Context; 6066 6067 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6068 const Qualifiers &VisibleQuals); 6069 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6070 6071public: 6072 /// iterator - Iterates through the types that are part of the set. 6073 typedef TypeSet::iterator iterator; 6074 6075 BuiltinCandidateTypeSet(Sema &SemaRef) 6076 : HasNonRecordTypes(false), 6077 HasArithmeticOrEnumeralTypes(false), 6078 HasNullPtrType(false), 6079 SemaRef(SemaRef), 6080 Context(SemaRef.Context) { } 6081 6082 void AddTypesConvertedFrom(QualType Ty, 6083 SourceLocation Loc, 6084 bool AllowUserConversions, 6085 bool AllowExplicitConversions, 6086 const Qualifiers &VisibleTypeConversionsQuals); 6087 6088 /// pointer_begin - First pointer type found; 6089 iterator pointer_begin() { return PointerTypes.begin(); } 6090 6091 /// pointer_end - Past the last pointer type found; 6092 iterator pointer_end() { return PointerTypes.end(); } 6093 6094 /// member_pointer_begin - First member pointer type found; 6095 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6096 6097 /// member_pointer_end - Past the last member pointer type found; 6098 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6099 6100 /// enumeration_begin - First enumeration type found; 6101 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6102 6103 /// enumeration_end - Past the last enumeration type found; 6104 iterator enumeration_end() { return EnumerationTypes.end(); } 6105 6106 iterator vector_begin() { return VectorTypes.begin(); } 6107 iterator vector_end() { return VectorTypes.end(); } 6108 6109 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6110 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6111 bool hasNullPtrType() const { return HasNullPtrType; } 6112}; 6113 6114/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6115/// the set of pointer types along with any more-qualified variants of 6116/// that type. For example, if @p Ty is "int const *", this routine 6117/// will add "int const *", "int const volatile *", "int const 6118/// restrict *", and "int const volatile restrict *" to the set of 6119/// pointer types. Returns true if the add of @p Ty itself succeeded, 6120/// false otherwise. 6121/// 6122/// FIXME: what to do about extended qualifiers? 6123bool 6124BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6125 const Qualifiers &VisibleQuals) { 6126 6127 // Insert this type. 6128 if (!PointerTypes.insert(Ty)) 6129 return false; 6130 6131 QualType PointeeTy; 6132 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6133 bool buildObjCPtr = false; 6134 if (!PointerTy) { 6135 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6136 PointeeTy = PTy->getPointeeType(); 6137 buildObjCPtr = true; 6138 } else { 6139 PointeeTy = PointerTy->getPointeeType(); 6140 } 6141 6142 // Don't add qualified variants of arrays. For one, they're not allowed 6143 // (the qualifier would sink to the element type), and for another, the 6144 // only overload situation where it matters is subscript or pointer +- int, 6145 // and those shouldn't have qualifier variants anyway. 6146 if (PointeeTy->isArrayType()) 6147 return true; 6148 6149 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6150 bool hasVolatile = VisibleQuals.hasVolatile(); 6151 bool hasRestrict = VisibleQuals.hasRestrict(); 6152 6153 // Iterate through all strict supersets of BaseCVR. 6154 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6155 if ((CVR | BaseCVR) != CVR) continue; 6156 // Skip over volatile if no volatile found anywhere in the types. 6157 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6158 6159 // Skip over restrict if no restrict found anywhere in the types, or if 6160 // the type cannot be restrict-qualified. 6161 if ((CVR & Qualifiers::Restrict) && 6162 (!hasRestrict || 6163 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6164 continue; 6165 6166 // Build qualified pointee type. 6167 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6168 6169 // Build qualified pointer type. 6170 QualType QPointerTy; 6171 if (!buildObjCPtr) 6172 QPointerTy = Context.getPointerType(QPointeeTy); 6173 else 6174 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6175 6176 // Insert qualified pointer type. 6177 PointerTypes.insert(QPointerTy); 6178 } 6179 6180 return true; 6181} 6182 6183/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6184/// to the set of pointer types along with any more-qualified variants of 6185/// that type. For example, if @p Ty is "int const *", this routine 6186/// will add "int const *", "int const volatile *", "int const 6187/// restrict *", and "int const volatile restrict *" to the set of 6188/// pointer types. Returns true if the add of @p Ty itself succeeded, 6189/// false otherwise. 6190/// 6191/// FIXME: what to do about extended qualifiers? 6192bool 6193BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6194 QualType Ty) { 6195 // Insert this type. 6196 if (!MemberPointerTypes.insert(Ty)) 6197 return false; 6198 6199 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6200 assert(PointerTy && "type was not a member pointer type!"); 6201 6202 QualType PointeeTy = PointerTy->getPointeeType(); 6203 // Don't add qualified variants of arrays. For one, they're not allowed 6204 // (the qualifier would sink to the element type), and for another, the 6205 // only overload situation where it matters is subscript or pointer +- int, 6206 // and those shouldn't have qualifier variants anyway. 6207 if (PointeeTy->isArrayType()) 6208 return true; 6209 const Type *ClassTy = PointerTy->getClass(); 6210 6211 // Iterate through all strict supersets of the pointee type's CVR 6212 // qualifiers. 6213 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6214 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6215 if ((CVR | BaseCVR) != CVR) continue; 6216 6217 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6218 MemberPointerTypes.insert( 6219 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6220 } 6221 6222 return true; 6223} 6224 6225/// AddTypesConvertedFrom - Add each of the types to which the type @p 6226/// Ty can be implicit converted to the given set of @p Types. We're 6227/// primarily interested in pointer types and enumeration types. We also 6228/// take member pointer types, for the conditional operator. 6229/// AllowUserConversions is true if we should look at the conversion 6230/// functions of a class type, and AllowExplicitConversions if we 6231/// should also include the explicit conversion functions of a class 6232/// type. 6233void 6234BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6235 SourceLocation Loc, 6236 bool AllowUserConversions, 6237 bool AllowExplicitConversions, 6238 const Qualifiers &VisibleQuals) { 6239 // Only deal with canonical types. 6240 Ty = Context.getCanonicalType(Ty); 6241 6242 // Look through reference types; they aren't part of the type of an 6243 // expression for the purposes of conversions. 6244 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6245 Ty = RefTy->getPointeeType(); 6246 6247 // If we're dealing with an array type, decay to the pointer. 6248 if (Ty->isArrayType()) 6249 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6250 6251 // Otherwise, we don't care about qualifiers on the type. 6252 Ty = Ty.getLocalUnqualifiedType(); 6253 6254 // Flag if we ever add a non-record type. 6255 const RecordType *TyRec = Ty->getAs<RecordType>(); 6256 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6257 6258 // Flag if we encounter an arithmetic type. 6259 HasArithmeticOrEnumeralTypes = 6260 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6261 6262 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6263 PointerTypes.insert(Ty); 6264 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6265 // Insert our type, and its more-qualified variants, into the set 6266 // of types. 6267 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6268 return; 6269 } else if (Ty->isMemberPointerType()) { 6270 // Member pointers are far easier, since the pointee can't be converted. 6271 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6272 return; 6273 } else if (Ty->isEnumeralType()) { 6274 HasArithmeticOrEnumeralTypes = true; 6275 EnumerationTypes.insert(Ty); 6276 } else if (Ty->isVectorType()) { 6277 // We treat vector types as arithmetic types in many contexts as an 6278 // extension. 6279 HasArithmeticOrEnumeralTypes = true; 6280 VectorTypes.insert(Ty); 6281 } else if (Ty->isNullPtrType()) { 6282 HasNullPtrType = true; 6283 } else if (AllowUserConversions && TyRec) { 6284 // No conversion functions in incomplete types. 6285 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6286 return; 6287 6288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6289 const UnresolvedSetImpl *Conversions 6290 = ClassDecl->getVisibleConversionFunctions(); 6291 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6292 E = Conversions->end(); I != E; ++I) { 6293 NamedDecl *D = I.getDecl(); 6294 if (isa<UsingShadowDecl>(D)) 6295 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6296 6297 // Skip conversion function templates; they don't tell us anything 6298 // about which builtin types we can convert to. 6299 if (isa<FunctionTemplateDecl>(D)) 6300 continue; 6301 6302 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6303 if (AllowExplicitConversions || !Conv->isExplicit()) { 6304 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6305 VisibleQuals); 6306 } 6307 } 6308 } 6309} 6310 6311/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6312/// the volatile- and non-volatile-qualified assignment operators for the 6313/// given type to the candidate set. 6314static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6315 QualType T, 6316 Expr **Args, 6317 unsigned NumArgs, 6318 OverloadCandidateSet &CandidateSet) { 6319 QualType ParamTypes[2]; 6320 6321 // T& operator=(T&, T) 6322 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6323 ParamTypes[1] = T; 6324 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6325 /*IsAssignmentOperator=*/true); 6326 6327 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6328 // volatile T& operator=(volatile T&, T) 6329 ParamTypes[0] 6330 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6331 ParamTypes[1] = T; 6332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6333 /*IsAssignmentOperator=*/true); 6334 } 6335} 6336 6337/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6338/// if any, found in visible type conversion functions found in ArgExpr's type. 6339static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6340 Qualifiers VRQuals; 6341 const RecordType *TyRec; 6342 if (const MemberPointerType *RHSMPType = 6343 ArgExpr->getType()->getAs<MemberPointerType>()) 6344 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6345 else 6346 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6347 if (!TyRec) { 6348 // Just to be safe, assume the worst case. 6349 VRQuals.addVolatile(); 6350 VRQuals.addRestrict(); 6351 return VRQuals; 6352 } 6353 6354 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6355 if (!ClassDecl->hasDefinition()) 6356 return VRQuals; 6357 6358 const UnresolvedSetImpl *Conversions = 6359 ClassDecl->getVisibleConversionFunctions(); 6360 6361 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6362 E = Conversions->end(); I != E; ++I) { 6363 NamedDecl *D = I.getDecl(); 6364 if (isa<UsingShadowDecl>(D)) 6365 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6366 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6367 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6368 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6369 CanTy = ResTypeRef->getPointeeType(); 6370 // Need to go down the pointer/mempointer chain and add qualifiers 6371 // as see them. 6372 bool done = false; 6373 while (!done) { 6374 if (CanTy.isRestrictQualified()) 6375 VRQuals.addRestrict(); 6376 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6377 CanTy = ResTypePtr->getPointeeType(); 6378 else if (const MemberPointerType *ResTypeMPtr = 6379 CanTy->getAs<MemberPointerType>()) 6380 CanTy = ResTypeMPtr->getPointeeType(); 6381 else 6382 done = true; 6383 if (CanTy.isVolatileQualified()) 6384 VRQuals.addVolatile(); 6385 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6386 return VRQuals; 6387 } 6388 } 6389 } 6390 return VRQuals; 6391} 6392 6393namespace { 6394 6395/// \brief Helper class to manage the addition of builtin operator overload 6396/// candidates. It provides shared state and utility methods used throughout 6397/// the process, as well as a helper method to add each group of builtin 6398/// operator overloads from the standard to a candidate set. 6399class BuiltinOperatorOverloadBuilder { 6400 // Common instance state available to all overload candidate addition methods. 6401 Sema &S; 6402 Expr **Args; 6403 unsigned NumArgs; 6404 Qualifiers VisibleTypeConversionsQuals; 6405 bool HasArithmeticOrEnumeralCandidateType; 6406 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6407 OverloadCandidateSet &CandidateSet; 6408 6409 // Define some constants used to index and iterate over the arithemetic types 6410 // provided via the getArithmeticType() method below. 6411 // The "promoted arithmetic types" are the arithmetic 6412 // types are that preserved by promotion (C++ [over.built]p2). 6413 static const unsigned FirstIntegralType = 3; 6414 static const unsigned LastIntegralType = 20; 6415 static const unsigned FirstPromotedIntegralType = 3, 6416 LastPromotedIntegralType = 11; 6417 static const unsigned FirstPromotedArithmeticType = 0, 6418 LastPromotedArithmeticType = 11; 6419 static const unsigned NumArithmeticTypes = 20; 6420 6421 /// \brief Get the canonical type for a given arithmetic type index. 6422 CanQualType getArithmeticType(unsigned index) { 6423 assert(index < NumArithmeticTypes); 6424 static CanQualType ASTContext::* const 6425 ArithmeticTypes[NumArithmeticTypes] = { 6426 // Start of promoted types. 6427 &ASTContext::FloatTy, 6428 &ASTContext::DoubleTy, 6429 &ASTContext::LongDoubleTy, 6430 6431 // Start of integral types. 6432 &ASTContext::IntTy, 6433 &ASTContext::LongTy, 6434 &ASTContext::LongLongTy, 6435 &ASTContext::Int128Ty, 6436 &ASTContext::UnsignedIntTy, 6437 &ASTContext::UnsignedLongTy, 6438 &ASTContext::UnsignedLongLongTy, 6439 &ASTContext::UnsignedInt128Ty, 6440 // End of promoted types. 6441 6442 &ASTContext::BoolTy, 6443 &ASTContext::CharTy, 6444 &ASTContext::WCharTy, 6445 &ASTContext::Char16Ty, 6446 &ASTContext::Char32Ty, 6447 &ASTContext::SignedCharTy, 6448 &ASTContext::ShortTy, 6449 &ASTContext::UnsignedCharTy, 6450 &ASTContext::UnsignedShortTy, 6451 // End of integral types. 6452 // FIXME: What about complex? What about half? 6453 }; 6454 return S.Context.*ArithmeticTypes[index]; 6455 } 6456 6457 /// \brief Gets the canonical type resulting from the usual arithemetic 6458 /// converions for the given arithmetic types. 6459 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6460 // Accelerator table for performing the usual arithmetic conversions. 6461 // The rules are basically: 6462 // - if either is floating-point, use the wider floating-point 6463 // - if same signedness, use the higher rank 6464 // - if same size, use unsigned of the higher rank 6465 // - use the larger type 6466 // These rules, together with the axiom that higher ranks are 6467 // never smaller, are sufficient to precompute all of these results 6468 // *except* when dealing with signed types of higher rank. 6469 // (we could precompute SLL x UI for all known platforms, but it's 6470 // better not to make any assumptions). 6471 // We assume that int128 has a higher rank than long long on all platforms. 6472 enum PromotedType { 6473 Dep=-1, 6474 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6475 }; 6476 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6477 [LastPromotedArithmeticType] = { 6478/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6479/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6480/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6481/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6482/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6483/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6484/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6485/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6486/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6487/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6488/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6489 }; 6490 6491 assert(L < LastPromotedArithmeticType); 6492 assert(R < LastPromotedArithmeticType); 6493 int Idx = ConversionsTable[L][R]; 6494 6495 // Fast path: the table gives us a concrete answer. 6496 if (Idx != Dep) return getArithmeticType(Idx); 6497 6498 // Slow path: we need to compare widths. 6499 // An invariant is that the signed type has higher rank. 6500 CanQualType LT = getArithmeticType(L), 6501 RT = getArithmeticType(R); 6502 unsigned LW = S.Context.getIntWidth(LT), 6503 RW = S.Context.getIntWidth(RT); 6504 6505 // If they're different widths, use the signed type. 6506 if (LW > RW) return LT; 6507 else if (LW < RW) return RT; 6508 6509 // Otherwise, use the unsigned type of the signed type's rank. 6510 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6511 assert(L == SLL || R == SLL); 6512 return S.Context.UnsignedLongLongTy; 6513 } 6514 6515 /// \brief Helper method to factor out the common pattern of adding overloads 6516 /// for '++' and '--' builtin operators. 6517 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6518 bool HasVolatile, 6519 bool HasRestrict) { 6520 QualType ParamTypes[2] = { 6521 S.Context.getLValueReferenceType(CandidateTy), 6522 S.Context.IntTy 6523 }; 6524 6525 // Non-volatile version. 6526 if (NumArgs == 1) 6527 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6528 else 6529 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6530 6531 // Use a heuristic to reduce number of builtin candidates in the set: 6532 // add volatile version only if there are conversions to a volatile type. 6533 if (HasVolatile) { 6534 ParamTypes[0] = 6535 S.Context.getLValueReferenceType( 6536 S.Context.getVolatileType(CandidateTy)); 6537 if (NumArgs == 1) 6538 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6539 else 6540 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6541 } 6542 6543 // Add restrict version only if there are conversions to a restrict type 6544 // and our candidate type is a non-restrict-qualified pointer. 6545 if (HasRestrict && CandidateTy->isAnyPointerType() && 6546 !CandidateTy.isRestrictQualified()) { 6547 ParamTypes[0] 6548 = S.Context.getLValueReferenceType( 6549 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6550 if (NumArgs == 1) 6551 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6552 else 6553 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6554 6555 if (HasVolatile) { 6556 ParamTypes[0] 6557 = S.Context.getLValueReferenceType( 6558 S.Context.getCVRQualifiedType(CandidateTy, 6559 (Qualifiers::Volatile | 6560 Qualifiers::Restrict))); 6561 if (NumArgs == 1) 6562 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6563 CandidateSet); 6564 else 6565 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6566 } 6567 } 6568 6569 } 6570 6571public: 6572 BuiltinOperatorOverloadBuilder( 6573 Sema &S, Expr **Args, unsigned NumArgs, 6574 Qualifiers VisibleTypeConversionsQuals, 6575 bool HasArithmeticOrEnumeralCandidateType, 6576 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6577 OverloadCandidateSet &CandidateSet) 6578 : S(S), Args(Args), NumArgs(NumArgs), 6579 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6580 HasArithmeticOrEnumeralCandidateType( 6581 HasArithmeticOrEnumeralCandidateType), 6582 CandidateTypes(CandidateTypes), 6583 CandidateSet(CandidateSet) { 6584 // Validate some of our static helper constants in debug builds. 6585 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6586 "Invalid first promoted integral type"); 6587 assert(getArithmeticType(LastPromotedIntegralType - 1) 6588 == S.Context.UnsignedInt128Ty && 6589 "Invalid last promoted integral type"); 6590 assert(getArithmeticType(FirstPromotedArithmeticType) 6591 == S.Context.FloatTy && 6592 "Invalid first promoted arithmetic type"); 6593 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6594 == S.Context.UnsignedInt128Ty && 6595 "Invalid last promoted arithmetic type"); 6596 } 6597 6598 // C++ [over.built]p3: 6599 // 6600 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6601 // is either volatile or empty, there exist candidate operator 6602 // functions of the form 6603 // 6604 // VQ T& operator++(VQ T&); 6605 // T operator++(VQ T&, int); 6606 // 6607 // C++ [over.built]p4: 6608 // 6609 // For every pair (T, VQ), where T is an arithmetic type other 6610 // than bool, and VQ is either volatile or empty, there exist 6611 // candidate operator functions of the form 6612 // 6613 // VQ T& operator--(VQ T&); 6614 // T operator--(VQ T&, int); 6615 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6616 if (!HasArithmeticOrEnumeralCandidateType) 6617 return; 6618 6619 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6620 Arith < NumArithmeticTypes; ++Arith) { 6621 addPlusPlusMinusMinusStyleOverloads( 6622 getArithmeticType(Arith), 6623 VisibleTypeConversionsQuals.hasVolatile(), 6624 VisibleTypeConversionsQuals.hasRestrict()); 6625 } 6626 } 6627 6628 // C++ [over.built]p5: 6629 // 6630 // For every pair (T, VQ), where T is a cv-qualified or 6631 // cv-unqualified object type, and VQ is either volatile or 6632 // empty, there exist candidate operator functions of the form 6633 // 6634 // T*VQ& operator++(T*VQ&); 6635 // T*VQ& operator--(T*VQ&); 6636 // T* operator++(T*VQ&, int); 6637 // T* operator--(T*VQ&, int); 6638 void addPlusPlusMinusMinusPointerOverloads() { 6639 for (BuiltinCandidateTypeSet::iterator 6640 Ptr = CandidateTypes[0].pointer_begin(), 6641 PtrEnd = CandidateTypes[0].pointer_end(); 6642 Ptr != PtrEnd; ++Ptr) { 6643 // Skip pointer types that aren't pointers to object types. 6644 if (!(*Ptr)->getPointeeType()->isObjectType()) 6645 continue; 6646 6647 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6648 (!(*Ptr).isVolatileQualified() && 6649 VisibleTypeConversionsQuals.hasVolatile()), 6650 (!(*Ptr).isRestrictQualified() && 6651 VisibleTypeConversionsQuals.hasRestrict())); 6652 } 6653 } 6654 6655 // C++ [over.built]p6: 6656 // For every cv-qualified or cv-unqualified object type T, there 6657 // exist candidate operator functions of the form 6658 // 6659 // T& operator*(T*); 6660 // 6661 // C++ [over.built]p7: 6662 // For every function type T that does not have cv-qualifiers or a 6663 // ref-qualifier, there exist candidate operator functions of the form 6664 // T& operator*(T*); 6665 void addUnaryStarPointerOverloads() { 6666 for (BuiltinCandidateTypeSet::iterator 6667 Ptr = CandidateTypes[0].pointer_begin(), 6668 PtrEnd = CandidateTypes[0].pointer_end(); 6669 Ptr != PtrEnd; ++Ptr) { 6670 QualType ParamTy = *Ptr; 6671 QualType PointeeTy = ParamTy->getPointeeType(); 6672 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6673 continue; 6674 6675 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6676 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6677 continue; 6678 6679 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6680 &ParamTy, Args, 1, CandidateSet); 6681 } 6682 } 6683 6684 // C++ [over.built]p9: 6685 // For every promoted arithmetic type T, there exist candidate 6686 // operator functions of the form 6687 // 6688 // T operator+(T); 6689 // T operator-(T); 6690 void addUnaryPlusOrMinusArithmeticOverloads() { 6691 if (!HasArithmeticOrEnumeralCandidateType) 6692 return; 6693 6694 for (unsigned Arith = FirstPromotedArithmeticType; 6695 Arith < LastPromotedArithmeticType; ++Arith) { 6696 QualType ArithTy = getArithmeticType(Arith); 6697 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6698 } 6699 6700 // Extension: We also add these operators for vector types. 6701 for (BuiltinCandidateTypeSet::iterator 6702 Vec = CandidateTypes[0].vector_begin(), 6703 VecEnd = CandidateTypes[0].vector_end(); 6704 Vec != VecEnd; ++Vec) { 6705 QualType VecTy = *Vec; 6706 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6707 } 6708 } 6709 6710 // C++ [over.built]p8: 6711 // For every type T, there exist candidate operator functions of 6712 // the form 6713 // 6714 // T* operator+(T*); 6715 void addUnaryPlusPointerOverloads() { 6716 for (BuiltinCandidateTypeSet::iterator 6717 Ptr = CandidateTypes[0].pointer_begin(), 6718 PtrEnd = CandidateTypes[0].pointer_end(); 6719 Ptr != PtrEnd; ++Ptr) { 6720 QualType ParamTy = *Ptr; 6721 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6722 } 6723 } 6724 6725 // C++ [over.built]p10: 6726 // For every promoted integral type T, there exist candidate 6727 // operator functions of the form 6728 // 6729 // T operator~(T); 6730 void addUnaryTildePromotedIntegralOverloads() { 6731 if (!HasArithmeticOrEnumeralCandidateType) 6732 return; 6733 6734 for (unsigned Int = FirstPromotedIntegralType; 6735 Int < LastPromotedIntegralType; ++Int) { 6736 QualType IntTy = getArithmeticType(Int); 6737 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6738 } 6739 6740 // Extension: We also add this operator for vector types. 6741 for (BuiltinCandidateTypeSet::iterator 6742 Vec = CandidateTypes[0].vector_begin(), 6743 VecEnd = CandidateTypes[0].vector_end(); 6744 Vec != VecEnd; ++Vec) { 6745 QualType VecTy = *Vec; 6746 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6747 } 6748 } 6749 6750 // C++ [over.match.oper]p16: 6751 // For every pointer to member type T, there exist candidate operator 6752 // functions of the form 6753 // 6754 // bool operator==(T,T); 6755 // bool operator!=(T,T); 6756 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6757 /// Set of (canonical) types that we've already handled. 6758 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6759 6760 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6761 for (BuiltinCandidateTypeSet::iterator 6762 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6763 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6764 MemPtr != MemPtrEnd; 6765 ++MemPtr) { 6766 // Don't add the same builtin candidate twice. 6767 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6768 continue; 6769 6770 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6771 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6772 CandidateSet); 6773 } 6774 } 6775 } 6776 6777 // C++ [over.built]p15: 6778 // 6779 // For every T, where T is an enumeration type, a pointer type, or 6780 // std::nullptr_t, there exist candidate operator functions of the form 6781 // 6782 // bool operator<(T, T); 6783 // bool operator>(T, T); 6784 // bool operator<=(T, T); 6785 // bool operator>=(T, T); 6786 // bool operator==(T, T); 6787 // bool operator!=(T, T); 6788 void addRelationalPointerOrEnumeralOverloads() { 6789 // C++ [over.match.oper]p3: 6790 // [...]the built-in candidates include all of the candidate operator 6791 // functions defined in 13.6 that, compared to the given operator, [...] 6792 // do not have the same parameter-type-list as any non-template non-member 6793 // candidate. 6794 // 6795 // Note that in practice, this only affects enumeration types because there 6796 // aren't any built-in candidates of record type, and a user-defined operator 6797 // must have an operand of record or enumeration type. Also, the only other 6798 // overloaded operator with enumeration arguments, operator=, 6799 // cannot be overloaded for enumeration types, so this is the only place 6800 // where we must suppress candidates like this. 6801 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6802 UserDefinedBinaryOperators; 6803 6804 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6805 if (CandidateTypes[ArgIdx].enumeration_begin() != 6806 CandidateTypes[ArgIdx].enumeration_end()) { 6807 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6808 CEnd = CandidateSet.end(); 6809 C != CEnd; ++C) { 6810 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6811 continue; 6812 6813 if (C->Function->isFunctionTemplateSpecialization()) 6814 continue; 6815 6816 QualType FirstParamType = 6817 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6818 QualType SecondParamType = 6819 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6820 6821 // Skip if either parameter isn't of enumeral type. 6822 if (!FirstParamType->isEnumeralType() || 6823 !SecondParamType->isEnumeralType()) 6824 continue; 6825 6826 // Add this operator to the set of known user-defined operators. 6827 UserDefinedBinaryOperators.insert( 6828 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6829 S.Context.getCanonicalType(SecondParamType))); 6830 } 6831 } 6832 } 6833 6834 /// Set of (canonical) types that we've already handled. 6835 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6836 6837 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6838 for (BuiltinCandidateTypeSet::iterator 6839 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6840 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6841 Ptr != PtrEnd; ++Ptr) { 6842 // Don't add the same builtin candidate twice. 6843 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6844 continue; 6845 6846 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6847 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6848 CandidateSet); 6849 } 6850 for (BuiltinCandidateTypeSet::iterator 6851 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6852 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6853 Enum != EnumEnd; ++Enum) { 6854 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6855 6856 // Don't add the same builtin candidate twice, or if a user defined 6857 // candidate exists. 6858 if (!AddedTypes.insert(CanonType) || 6859 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6860 CanonType))) 6861 continue; 6862 6863 QualType ParamTypes[2] = { *Enum, *Enum }; 6864 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6865 CandidateSet); 6866 } 6867 6868 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6869 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6870 if (AddedTypes.insert(NullPtrTy) && 6871 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6872 NullPtrTy))) { 6873 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6874 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6875 CandidateSet); 6876 } 6877 } 6878 } 6879 } 6880 6881 // C++ [over.built]p13: 6882 // 6883 // For every cv-qualified or cv-unqualified object type T 6884 // there exist candidate operator functions of the form 6885 // 6886 // T* operator+(T*, ptrdiff_t); 6887 // T& operator[](T*, ptrdiff_t); [BELOW] 6888 // T* operator-(T*, ptrdiff_t); 6889 // T* operator+(ptrdiff_t, T*); 6890 // T& operator[](ptrdiff_t, T*); [BELOW] 6891 // 6892 // C++ [over.built]p14: 6893 // 6894 // For every T, where T is a pointer to object type, there 6895 // exist candidate operator functions of the form 6896 // 6897 // ptrdiff_t operator-(T, T); 6898 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6899 /// Set of (canonical) types that we've already handled. 6900 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6901 6902 for (int Arg = 0; Arg < 2; ++Arg) { 6903 QualType AsymetricParamTypes[2] = { 6904 S.Context.getPointerDiffType(), 6905 S.Context.getPointerDiffType(), 6906 }; 6907 for (BuiltinCandidateTypeSet::iterator 6908 Ptr = CandidateTypes[Arg].pointer_begin(), 6909 PtrEnd = CandidateTypes[Arg].pointer_end(); 6910 Ptr != PtrEnd; ++Ptr) { 6911 QualType PointeeTy = (*Ptr)->getPointeeType(); 6912 if (!PointeeTy->isObjectType()) 6913 continue; 6914 6915 AsymetricParamTypes[Arg] = *Ptr; 6916 if (Arg == 0 || Op == OO_Plus) { 6917 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6918 // T* operator+(ptrdiff_t, T*); 6919 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6920 CandidateSet); 6921 } 6922 if (Op == OO_Minus) { 6923 // ptrdiff_t operator-(T, T); 6924 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6925 continue; 6926 6927 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6928 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6929 Args, 2, CandidateSet); 6930 } 6931 } 6932 } 6933 } 6934 6935 // C++ [over.built]p12: 6936 // 6937 // For every pair of promoted arithmetic types L and R, there 6938 // exist candidate operator functions of the form 6939 // 6940 // LR operator*(L, R); 6941 // LR operator/(L, R); 6942 // LR operator+(L, R); 6943 // LR operator-(L, R); 6944 // bool operator<(L, R); 6945 // bool operator>(L, R); 6946 // bool operator<=(L, R); 6947 // bool operator>=(L, R); 6948 // bool operator==(L, R); 6949 // bool operator!=(L, R); 6950 // 6951 // where LR is the result of the usual arithmetic conversions 6952 // between types L and R. 6953 // 6954 // C++ [over.built]p24: 6955 // 6956 // For every pair of promoted arithmetic types L and R, there exist 6957 // candidate operator functions of the form 6958 // 6959 // LR operator?(bool, L, R); 6960 // 6961 // where LR is the result of the usual arithmetic conversions 6962 // between types L and R. 6963 // Our candidates ignore the first parameter. 6964 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6965 if (!HasArithmeticOrEnumeralCandidateType) 6966 return; 6967 6968 for (unsigned Left = FirstPromotedArithmeticType; 6969 Left < LastPromotedArithmeticType; ++Left) { 6970 for (unsigned Right = FirstPromotedArithmeticType; 6971 Right < LastPromotedArithmeticType; ++Right) { 6972 QualType LandR[2] = { getArithmeticType(Left), 6973 getArithmeticType(Right) }; 6974 QualType Result = 6975 isComparison ? S.Context.BoolTy 6976 : getUsualArithmeticConversions(Left, Right); 6977 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6978 } 6979 } 6980 6981 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6982 // conditional operator for vector types. 6983 for (BuiltinCandidateTypeSet::iterator 6984 Vec1 = CandidateTypes[0].vector_begin(), 6985 Vec1End = CandidateTypes[0].vector_end(); 6986 Vec1 != Vec1End; ++Vec1) { 6987 for (BuiltinCandidateTypeSet::iterator 6988 Vec2 = CandidateTypes[1].vector_begin(), 6989 Vec2End = CandidateTypes[1].vector_end(); 6990 Vec2 != Vec2End; ++Vec2) { 6991 QualType LandR[2] = { *Vec1, *Vec2 }; 6992 QualType Result = S.Context.BoolTy; 6993 if (!isComparison) { 6994 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6995 Result = *Vec1; 6996 else 6997 Result = *Vec2; 6998 } 6999 7000 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7001 } 7002 } 7003 } 7004 7005 // C++ [over.built]p17: 7006 // 7007 // For every pair of promoted integral types L and R, there 7008 // exist candidate operator functions of the form 7009 // 7010 // LR operator%(L, R); 7011 // LR operator&(L, R); 7012 // LR operator^(L, R); 7013 // LR operator|(L, R); 7014 // L operator<<(L, R); 7015 // L operator>>(L, R); 7016 // 7017 // where LR is the result of the usual arithmetic conversions 7018 // between types L and R. 7019 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7020 if (!HasArithmeticOrEnumeralCandidateType) 7021 return; 7022 7023 for (unsigned Left = FirstPromotedIntegralType; 7024 Left < LastPromotedIntegralType; ++Left) { 7025 for (unsigned Right = FirstPromotedIntegralType; 7026 Right < LastPromotedIntegralType; ++Right) { 7027 QualType LandR[2] = { getArithmeticType(Left), 7028 getArithmeticType(Right) }; 7029 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7030 ? LandR[0] 7031 : getUsualArithmeticConversions(Left, Right); 7032 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7033 } 7034 } 7035 } 7036 7037 // C++ [over.built]p20: 7038 // 7039 // For every pair (T, VQ), where T is an enumeration or 7040 // pointer to member type and VQ is either volatile or 7041 // empty, there exist candidate operator functions of the form 7042 // 7043 // VQ T& operator=(VQ T&, T); 7044 void addAssignmentMemberPointerOrEnumeralOverloads() { 7045 /// Set of (canonical) types that we've already handled. 7046 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7047 7048 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7049 for (BuiltinCandidateTypeSet::iterator 7050 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7051 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7052 Enum != EnumEnd; ++Enum) { 7053 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7054 continue; 7055 7056 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7057 CandidateSet); 7058 } 7059 7060 for (BuiltinCandidateTypeSet::iterator 7061 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7062 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7063 MemPtr != MemPtrEnd; ++MemPtr) { 7064 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7065 continue; 7066 7067 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7068 CandidateSet); 7069 } 7070 } 7071 } 7072 7073 // C++ [over.built]p19: 7074 // 7075 // For every pair (T, VQ), where T is any type and VQ is either 7076 // volatile or empty, there exist candidate operator functions 7077 // of the form 7078 // 7079 // T*VQ& operator=(T*VQ&, T*); 7080 // 7081 // C++ [over.built]p21: 7082 // 7083 // For every pair (T, VQ), where T is a cv-qualified or 7084 // cv-unqualified object type and VQ is either volatile or 7085 // empty, there exist candidate operator functions of the form 7086 // 7087 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7088 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7089 void addAssignmentPointerOverloads(bool isEqualOp) { 7090 /// Set of (canonical) types that we've already handled. 7091 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7092 7093 for (BuiltinCandidateTypeSet::iterator 7094 Ptr = CandidateTypes[0].pointer_begin(), 7095 PtrEnd = CandidateTypes[0].pointer_end(); 7096 Ptr != PtrEnd; ++Ptr) { 7097 // If this is operator=, keep track of the builtin candidates we added. 7098 if (isEqualOp) 7099 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7100 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7101 continue; 7102 7103 // non-volatile version 7104 QualType ParamTypes[2] = { 7105 S.Context.getLValueReferenceType(*Ptr), 7106 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7107 }; 7108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7109 /*IsAssigmentOperator=*/ isEqualOp); 7110 7111 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7112 VisibleTypeConversionsQuals.hasVolatile(); 7113 if (NeedVolatile) { 7114 // volatile version 7115 ParamTypes[0] = 7116 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7117 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7118 /*IsAssigmentOperator=*/isEqualOp); 7119 } 7120 7121 if (!(*Ptr).isRestrictQualified() && 7122 VisibleTypeConversionsQuals.hasRestrict()) { 7123 // restrict version 7124 ParamTypes[0] 7125 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7126 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7127 /*IsAssigmentOperator=*/isEqualOp); 7128 7129 if (NeedVolatile) { 7130 // volatile restrict version 7131 ParamTypes[0] 7132 = S.Context.getLValueReferenceType( 7133 S.Context.getCVRQualifiedType(*Ptr, 7134 (Qualifiers::Volatile | 7135 Qualifiers::Restrict))); 7136 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7137 CandidateSet, 7138 /*IsAssigmentOperator=*/isEqualOp); 7139 } 7140 } 7141 } 7142 7143 if (isEqualOp) { 7144 for (BuiltinCandidateTypeSet::iterator 7145 Ptr = CandidateTypes[1].pointer_begin(), 7146 PtrEnd = CandidateTypes[1].pointer_end(); 7147 Ptr != PtrEnd; ++Ptr) { 7148 // Make sure we don't add the same candidate twice. 7149 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7150 continue; 7151 7152 QualType ParamTypes[2] = { 7153 S.Context.getLValueReferenceType(*Ptr), 7154 *Ptr, 7155 }; 7156 7157 // non-volatile version 7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7159 /*IsAssigmentOperator=*/true); 7160 7161 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7162 VisibleTypeConversionsQuals.hasVolatile(); 7163 if (NeedVolatile) { 7164 // volatile version 7165 ParamTypes[0] = 7166 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7167 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7168 CandidateSet, /*IsAssigmentOperator=*/true); 7169 } 7170 7171 if (!(*Ptr).isRestrictQualified() && 7172 VisibleTypeConversionsQuals.hasRestrict()) { 7173 // restrict version 7174 ParamTypes[0] 7175 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7176 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7177 CandidateSet, /*IsAssigmentOperator=*/true); 7178 7179 if (NeedVolatile) { 7180 // volatile restrict version 7181 ParamTypes[0] 7182 = S.Context.getLValueReferenceType( 7183 S.Context.getCVRQualifiedType(*Ptr, 7184 (Qualifiers::Volatile | 7185 Qualifiers::Restrict))); 7186 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7187 CandidateSet, /*IsAssigmentOperator=*/true); 7188 7189 } 7190 } 7191 } 7192 } 7193 } 7194 7195 // C++ [over.built]p18: 7196 // 7197 // For every triple (L, VQ, R), where L is an arithmetic type, 7198 // VQ is either volatile or empty, and R is a promoted 7199 // arithmetic type, there exist candidate operator functions of 7200 // the form 7201 // 7202 // VQ L& operator=(VQ L&, R); 7203 // VQ L& operator*=(VQ L&, R); 7204 // VQ L& operator/=(VQ L&, R); 7205 // VQ L& operator+=(VQ L&, R); 7206 // VQ L& operator-=(VQ L&, R); 7207 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7208 if (!HasArithmeticOrEnumeralCandidateType) 7209 return; 7210 7211 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7212 for (unsigned Right = FirstPromotedArithmeticType; 7213 Right < LastPromotedArithmeticType; ++Right) { 7214 QualType ParamTypes[2]; 7215 ParamTypes[1] = getArithmeticType(Right); 7216 7217 // Add this built-in operator as a candidate (VQ is empty). 7218 ParamTypes[0] = 7219 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7220 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7221 /*IsAssigmentOperator=*/isEqualOp); 7222 7223 // Add this built-in operator as a candidate (VQ is 'volatile'). 7224 if (VisibleTypeConversionsQuals.hasVolatile()) { 7225 ParamTypes[0] = 7226 S.Context.getVolatileType(getArithmeticType(Left)); 7227 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7228 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7229 CandidateSet, 7230 /*IsAssigmentOperator=*/isEqualOp); 7231 } 7232 } 7233 } 7234 7235 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7236 for (BuiltinCandidateTypeSet::iterator 7237 Vec1 = CandidateTypes[0].vector_begin(), 7238 Vec1End = CandidateTypes[0].vector_end(); 7239 Vec1 != Vec1End; ++Vec1) { 7240 for (BuiltinCandidateTypeSet::iterator 7241 Vec2 = CandidateTypes[1].vector_begin(), 7242 Vec2End = CandidateTypes[1].vector_end(); 7243 Vec2 != Vec2End; ++Vec2) { 7244 QualType ParamTypes[2]; 7245 ParamTypes[1] = *Vec2; 7246 // Add this built-in operator as a candidate (VQ is empty). 7247 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7248 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7249 /*IsAssigmentOperator=*/isEqualOp); 7250 7251 // Add this built-in operator as a candidate (VQ is 'volatile'). 7252 if (VisibleTypeConversionsQuals.hasVolatile()) { 7253 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7254 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7255 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7256 CandidateSet, 7257 /*IsAssigmentOperator=*/isEqualOp); 7258 } 7259 } 7260 } 7261 } 7262 7263 // C++ [over.built]p22: 7264 // 7265 // For every triple (L, VQ, R), where L is an integral type, VQ 7266 // is either volatile or empty, and R is a promoted integral 7267 // type, there exist candidate operator functions of the form 7268 // 7269 // VQ L& operator%=(VQ L&, R); 7270 // VQ L& operator<<=(VQ L&, R); 7271 // VQ L& operator>>=(VQ L&, R); 7272 // VQ L& operator&=(VQ L&, R); 7273 // VQ L& operator^=(VQ L&, R); 7274 // VQ L& operator|=(VQ L&, R); 7275 void addAssignmentIntegralOverloads() { 7276 if (!HasArithmeticOrEnumeralCandidateType) 7277 return; 7278 7279 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7280 for (unsigned Right = FirstPromotedIntegralType; 7281 Right < LastPromotedIntegralType; ++Right) { 7282 QualType ParamTypes[2]; 7283 ParamTypes[1] = getArithmeticType(Right); 7284 7285 // Add this built-in operator as a candidate (VQ is empty). 7286 ParamTypes[0] = 7287 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7288 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7289 if (VisibleTypeConversionsQuals.hasVolatile()) { 7290 // Add this built-in operator as a candidate (VQ is 'volatile'). 7291 ParamTypes[0] = getArithmeticType(Left); 7292 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7293 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7294 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7295 CandidateSet); 7296 } 7297 } 7298 } 7299 } 7300 7301 // C++ [over.operator]p23: 7302 // 7303 // There also exist candidate operator functions of the form 7304 // 7305 // bool operator!(bool); 7306 // bool operator&&(bool, bool); 7307 // bool operator||(bool, bool); 7308 void addExclaimOverload() { 7309 QualType ParamTy = S.Context.BoolTy; 7310 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7311 /*IsAssignmentOperator=*/false, 7312 /*NumContextualBoolArguments=*/1); 7313 } 7314 void addAmpAmpOrPipePipeOverload() { 7315 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7316 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7317 /*IsAssignmentOperator=*/false, 7318 /*NumContextualBoolArguments=*/2); 7319 } 7320 7321 // C++ [over.built]p13: 7322 // 7323 // For every cv-qualified or cv-unqualified object type T there 7324 // exist candidate operator functions of the form 7325 // 7326 // T* operator+(T*, ptrdiff_t); [ABOVE] 7327 // T& operator[](T*, ptrdiff_t); 7328 // T* operator-(T*, ptrdiff_t); [ABOVE] 7329 // T* operator+(ptrdiff_t, T*); [ABOVE] 7330 // T& operator[](ptrdiff_t, T*); 7331 void addSubscriptOverloads() { 7332 for (BuiltinCandidateTypeSet::iterator 7333 Ptr = CandidateTypes[0].pointer_begin(), 7334 PtrEnd = CandidateTypes[0].pointer_end(); 7335 Ptr != PtrEnd; ++Ptr) { 7336 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7337 QualType PointeeType = (*Ptr)->getPointeeType(); 7338 if (!PointeeType->isObjectType()) 7339 continue; 7340 7341 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7342 7343 // T& operator[](T*, ptrdiff_t) 7344 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7345 } 7346 7347 for (BuiltinCandidateTypeSet::iterator 7348 Ptr = CandidateTypes[1].pointer_begin(), 7349 PtrEnd = CandidateTypes[1].pointer_end(); 7350 Ptr != PtrEnd; ++Ptr) { 7351 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7352 QualType PointeeType = (*Ptr)->getPointeeType(); 7353 if (!PointeeType->isObjectType()) 7354 continue; 7355 7356 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7357 7358 // T& operator[](ptrdiff_t, T*) 7359 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7360 } 7361 } 7362 7363 // C++ [over.built]p11: 7364 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7365 // C1 is the same type as C2 or is a derived class of C2, T is an object 7366 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7367 // there exist candidate operator functions of the form 7368 // 7369 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7370 // 7371 // where CV12 is the union of CV1 and CV2. 7372 void addArrowStarOverloads() { 7373 for (BuiltinCandidateTypeSet::iterator 7374 Ptr = CandidateTypes[0].pointer_begin(), 7375 PtrEnd = CandidateTypes[0].pointer_end(); 7376 Ptr != PtrEnd; ++Ptr) { 7377 QualType C1Ty = (*Ptr); 7378 QualType C1; 7379 QualifierCollector Q1; 7380 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7381 if (!isa<RecordType>(C1)) 7382 continue; 7383 // heuristic to reduce number of builtin candidates in the set. 7384 // Add volatile/restrict version only if there are conversions to a 7385 // volatile/restrict type. 7386 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7387 continue; 7388 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7389 continue; 7390 for (BuiltinCandidateTypeSet::iterator 7391 MemPtr = CandidateTypes[1].member_pointer_begin(), 7392 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7393 MemPtr != MemPtrEnd; ++MemPtr) { 7394 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7395 QualType C2 = QualType(mptr->getClass(), 0); 7396 C2 = C2.getUnqualifiedType(); 7397 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7398 break; 7399 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7400 // build CV12 T& 7401 QualType T = mptr->getPointeeType(); 7402 if (!VisibleTypeConversionsQuals.hasVolatile() && 7403 T.isVolatileQualified()) 7404 continue; 7405 if (!VisibleTypeConversionsQuals.hasRestrict() && 7406 T.isRestrictQualified()) 7407 continue; 7408 T = Q1.apply(S.Context, T); 7409 QualType ResultTy = S.Context.getLValueReferenceType(T); 7410 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7411 } 7412 } 7413 } 7414 7415 // Note that we don't consider the first argument, since it has been 7416 // contextually converted to bool long ago. The candidates below are 7417 // therefore added as binary. 7418 // 7419 // C++ [over.built]p25: 7420 // For every type T, where T is a pointer, pointer-to-member, or scoped 7421 // enumeration type, there exist candidate operator functions of the form 7422 // 7423 // T operator?(bool, T, T); 7424 // 7425 void addConditionalOperatorOverloads() { 7426 /// Set of (canonical) types that we've already handled. 7427 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7428 7429 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7430 for (BuiltinCandidateTypeSet::iterator 7431 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7432 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7433 Ptr != PtrEnd; ++Ptr) { 7434 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7435 continue; 7436 7437 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7438 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7439 } 7440 7441 for (BuiltinCandidateTypeSet::iterator 7442 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7443 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7444 MemPtr != MemPtrEnd; ++MemPtr) { 7445 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7446 continue; 7447 7448 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7449 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7450 } 7451 7452 if (S.getLangOpts().CPlusPlus0x) { 7453 for (BuiltinCandidateTypeSet::iterator 7454 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7455 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7456 Enum != EnumEnd; ++Enum) { 7457 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7458 continue; 7459 7460 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7461 continue; 7462 7463 QualType ParamTypes[2] = { *Enum, *Enum }; 7464 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7465 } 7466 } 7467 } 7468 } 7469}; 7470 7471} // end anonymous namespace 7472 7473/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7474/// operator overloads to the candidate set (C++ [over.built]), based 7475/// on the operator @p Op and the arguments given. For example, if the 7476/// operator is a binary '+', this routine might add "int 7477/// operator+(int, int)" to cover integer addition. 7478void 7479Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7480 SourceLocation OpLoc, 7481 Expr **Args, unsigned NumArgs, 7482 OverloadCandidateSet& CandidateSet) { 7483 // Find all of the types that the arguments can convert to, but only 7484 // if the operator we're looking at has built-in operator candidates 7485 // that make use of these types. Also record whether we encounter non-record 7486 // candidate types or either arithmetic or enumeral candidate types. 7487 Qualifiers VisibleTypeConversionsQuals; 7488 VisibleTypeConversionsQuals.addConst(); 7489 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7490 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7491 7492 bool HasNonRecordCandidateType = false; 7493 bool HasArithmeticOrEnumeralCandidateType = false; 7494 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7495 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7496 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7497 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7498 OpLoc, 7499 true, 7500 (Op == OO_Exclaim || 7501 Op == OO_AmpAmp || 7502 Op == OO_PipePipe), 7503 VisibleTypeConversionsQuals); 7504 HasNonRecordCandidateType = HasNonRecordCandidateType || 7505 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7506 HasArithmeticOrEnumeralCandidateType = 7507 HasArithmeticOrEnumeralCandidateType || 7508 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7509 } 7510 7511 // Exit early when no non-record types have been added to the candidate set 7512 // for any of the arguments to the operator. 7513 // 7514 // We can't exit early for !, ||, or &&, since there we have always have 7515 // 'bool' overloads. 7516 if (!HasNonRecordCandidateType && 7517 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7518 return; 7519 7520 // Setup an object to manage the common state for building overloads. 7521 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7522 VisibleTypeConversionsQuals, 7523 HasArithmeticOrEnumeralCandidateType, 7524 CandidateTypes, CandidateSet); 7525 7526 // Dispatch over the operation to add in only those overloads which apply. 7527 switch (Op) { 7528 case OO_None: 7529 case NUM_OVERLOADED_OPERATORS: 7530 llvm_unreachable("Expected an overloaded operator"); 7531 7532 case OO_New: 7533 case OO_Delete: 7534 case OO_Array_New: 7535 case OO_Array_Delete: 7536 case OO_Call: 7537 llvm_unreachable( 7538 "Special operators don't use AddBuiltinOperatorCandidates"); 7539 7540 case OO_Comma: 7541 case OO_Arrow: 7542 // C++ [over.match.oper]p3: 7543 // -- For the operator ',', the unary operator '&', or the 7544 // operator '->', the built-in candidates set is empty. 7545 break; 7546 7547 case OO_Plus: // '+' is either unary or binary 7548 if (NumArgs == 1) 7549 OpBuilder.addUnaryPlusPointerOverloads(); 7550 // Fall through. 7551 7552 case OO_Minus: // '-' is either unary or binary 7553 if (NumArgs == 1) { 7554 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7555 } else { 7556 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7557 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7558 } 7559 break; 7560 7561 case OO_Star: // '*' is either unary or binary 7562 if (NumArgs == 1) 7563 OpBuilder.addUnaryStarPointerOverloads(); 7564 else 7565 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7566 break; 7567 7568 case OO_Slash: 7569 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7570 break; 7571 7572 case OO_PlusPlus: 7573 case OO_MinusMinus: 7574 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7575 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7576 break; 7577 7578 case OO_EqualEqual: 7579 case OO_ExclaimEqual: 7580 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7581 // Fall through. 7582 7583 case OO_Less: 7584 case OO_Greater: 7585 case OO_LessEqual: 7586 case OO_GreaterEqual: 7587 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7588 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7589 break; 7590 7591 case OO_Percent: 7592 case OO_Caret: 7593 case OO_Pipe: 7594 case OO_LessLess: 7595 case OO_GreaterGreater: 7596 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7597 break; 7598 7599 case OO_Amp: // '&' is either unary or binary 7600 if (NumArgs == 1) 7601 // C++ [over.match.oper]p3: 7602 // -- For the operator ',', the unary operator '&', or the 7603 // operator '->', the built-in candidates set is empty. 7604 break; 7605 7606 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7607 break; 7608 7609 case OO_Tilde: 7610 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7611 break; 7612 7613 case OO_Equal: 7614 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7615 // Fall through. 7616 7617 case OO_PlusEqual: 7618 case OO_MinusEqual: 7619 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7620 // Fall through. 7621 7622 case OO_StarEqual: 7623 case OO_SlashEqual: 7624 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7625 break; 7626 7627 case OO_PercentEqual: 7628 case OO_LessLessEqual: 7629 case OO_GreaterGreaterEqual: 7630 case OO_AmpEqual: 7631 case OO_CaretEqual: 7632 case OO_PipeEqual: 7633 OpBuilder.addAssignmentIntegralOverloads(); 7634 break; 7635 7636 case OO_Exclaim: 7637 OpBuilder.addExclaimOverload(); 7638 break; 7639 7640 case OO_AmpAmp: 7641 case OO_PipePipe: 7642 OpBuilder.addAmpAmpOrPipePipeOverload(); 7643 break; 7644 7645 case OO_Subscript: 7646 OpBuilder.addSubscriptOverloads(); 7647 break; 7648 7649 case OO_ArrowStar: 7650 OpBuilder.addArrowStarOverloads(); 7651 break; 7652 7653 case OO_Conditional: 7654 OpBuilder.addConditionalOperatorOverloads(); 7655 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7656 break; 7657 } 7658} 7659 7660/// \brief Add function candidates found via argument-dependent lookup 7661/// to the set of overloading candidates. 7662/// 7663/// This routine performs argument-dependent name lookup based on the 7664/// given function name (which may also be an operator name) and adds 7665/// all of the overload candidates found by ADL to the overload 7666/// candidate set (C++ [basic.lookup.argdep]). 7667void 7668Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7669 bool Operator, SourceLocation Loc, 7670 llvm::ArrayRef<Expr *> Args, 7671 TemplateArgumentListInfo *ExplicitTemplateArgs, 7672 OverloadCandidateSet& CandidateSet, 7673 bool PartialOverloading) { 7674 ADLResult Fns; 7675 7676 // FIXME: This approach for uniquing ADL results (and removing 7677 // redundant candidates from the set) relies on pointer-equality, 7678 // which means we need to key off the canonical decl. However, 7679 // always going back to the canonical decl might not get us the 7680 // right set of default arguments. What default arguments are 7681 // we supposed to consider on ADL candidates, anyway? 7682 7683 // FIXME: Pass in the explicit template arguments? 7684 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7685 7686 // Erase all of the candidates we already knew about. 7687 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7688 CandEnd = CandidateSet.end(); 7689 Cand != CandEnd; ++Cand) 7690 if (Cand->Function) { 7691 Fns.erase(Cand->Function); 7692 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7693 Fns.erase(FunTmpl); 7694 } 7695 7696 // For each of the ADL candidates we found, add it to the overload 7697 // set. 7698 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7699 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7700 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7701 if (ExplicitTemplateArgs) 7702 continue; 7703 7704 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7705 PartialOverloading); 7706 } else 7707 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7708 FoundDecl, ExplicitTemplateArgs, 7709 Args, CandidateSet); 7710 } 7711} 7712 7713/// isBetterOverloadCandidate - Determines whether the first overload 7714/// candidate is a better candidate than the second (C++ 13.3.3p1). 7715bool 7716isBetterOverloadCandidate(Sema &S, 7717 const OverloadCandidate &Cand1, 7718 const OverloadCandidate &Cand2, 7719 SourceLocation Loc, 7720 bool UserDefinedConversion) { 7721 // Define viable functions to be better candidates than non-viable 7722 // functions. 7723 if (!Cand2.Viable) 7724 return Cand1.Viable; 7725 else if (!Cand1.Viable) 7726 return false; 7727 7728 // C++ [over.match.best]p1: 7729 // 7730 // -- if F is a static member function, ICS1(F) is defined such 7731 // that ICS1(F) is neither better nor worse than ICS1(G) for 7732 // any function G, and, symmetrically, ICS1(G) is neither 7733 // better nor worse than ICS1(F). 7734 unsigned StartArg = 0; 7735 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7736 StartArg = 1; 7737 7738 // C++ [over.match.best]p1: 7739 // A viable function F1 is defined to be a better function than another 7740 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7741 // conversion sequence than ICSi(F2), and then... 7742 unsigned NumArgs = Cand1.NumConversions; 7743 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7744 bool HasBetterConversion = false; 7745 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7746 switch (CompareImplicitConversionSequences(S, 7747 Cand1.Conversions[ArgIdx], 7748 Cand2.Conversions[ArgIdx])) { 7749 case ImplicitConversionSequence::Better: 7750 // Cand1 has a better conversion sequence. 7751 HasBetterConversion = true; 7752 break; 7753 7754 case ImplicitConversionSequence::Worse: 7755 // Cand1 can't be better than Cand2. 7756 return false; 7757 7758 case ImplicitConversionSequence::Indistinguishable: 7759 // Do nothing. 7760 break; 7761 } 7762 } 7763 7764 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7765 // ICSj(F2), or, if not that, 7766 if (HasBetterConversion) 7767 return true; 7768 7769 // - F1 is a non-template function and F2 is a function template 7770 // specialization, or, if not that, 7771 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7772 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7773 return true; 7774 7775 // -- F1 and F2 are function template specializations, and the function 7776 // template for F1 is more specialized than the template for F2 7777 // according to the partial ordering rules described in 14.5.5.2, or, 7778 // if not that, 7779 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7780 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7781 if (FunctionTemplateDecl *BetterTemplate 7782 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7783 Cand2.Function->getPrimaryTemplate(), 7784 Loc, 7785 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7786 : TPOC_Call, 7787 Cand1.ExplicitCallArguments)) 7788 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7789 } 7790 7791 // -- the context is an initialization by user-defined conversion 7792 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7793 // from the return type of F1 to the destination type (i.e., 7794 // the type of the entity being initialized) is a better 7795 // conversion sequence than the standard conversion sequence 7796 // from the return type of F2 to the destination type. 7797 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7798 isa<CXXConversionDecl>(Cand1.Function) && 7799 isa<CXXConversionDecl>(Cand2.Function)) { 7800 // First check whether we prefer one of the conversion functions over the 7801 // other. This only distinguishes the results in non-standard, extension 7802 // cases such as the conversion from a lambda closure type to a function 7803 // pointer or block. 7804 ImplicitConversionSequence::CompareKind FuncResult 7805 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7806 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7807 return FuncResult; 7808 7809 switch (CompareStandardConversionSequences(S, 7810 Cand1.FinalConversion, 7811 Cand2.FinalConversion)) { 7812 case ImplicitConversionSequence::Better: 7813 // Cand1 has a better conversion sequence. 7814 return true; 7815 7816 case ImplicitConversionSequence::Worse: 7817 // Cand1 can't be better than Cand2. 7818 return false; 7819 7820 case ImplicitConversionSequence::Indistinguishable: 7821 // Do nothing 7822 break; 7823 } 7824 } 7825 7826 return false; 7827} 7828 7829/// \brief Computes the best viable function (C++ 13.3.3) 7830/// within an overload candidate set. 7831/// 7832/// \param Loc The location of the function name (or operator symbol) for 7833/// which overload resolution occurs. 7834/// 7835/// \param Best If overload resolution was successful or found a deleted 7836/// function, \p Best points to the candidate function found. 7837/// 7838/// \returns The result of overload resolution. 7839OverloadingResult 7840OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7841 iterator &Best, 7842 bool UserDefinedConversion) { 7843 // Find the best viable function. 7844 Best = end(); 7845 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7846 if (Cand->Viable) 7847 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7848 UserDefinedConversion)) 7849 Best = Cand; 7850 } 7851 7852 // If we didn't find any viable functions, abort. 7853 if (Best == end()) 7854 return OR_No_Viable_Function; 7855 7856 // Make sure that this function is better than every other viable 7857 // function. If not, we have an ambiguity. 7858 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7859 if (Cand->Viable && 7860 Cand != Best && 7861 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7862 UserDefinedConversion)) { 7863 Best = end(); 7864 return OR_Ambiguous; 7865 } 7866 } 7867 7868 // Best is the best viable function. 7869 if (Best->Function && 7870 (Best->Function->isDeleted() || 7871 S.isFunctionConsideredUnavailable(Best->Function))) 7872 return OR_Deleted; 7873 7874 return OR_Success; 7875} 7876 7877namespace { 7878 7879enum OverloadCandidateKind { 7880 oc_function, 7881 oc_method, 7882 oc_constructor, 7883 oc_function_template, 7884 oc_method_template, 7885 oc_constructor_template, 7886 oc_implicit_default_constructor, 7887 oc_implicit_copy_constructor, 7888 oc_implicit_move_constructor, 7889 oc_implicit_copy_assignment, 7890 oc_implicit_move_assignment, 7891 oc_implicit_inherited_constructor 7892}; 7893 7894OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7895 FunctionDecl *Fn, 7896 std::string &Description) { 7897 bool isTemplate = false; 7898 7899 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7900 isTemplate = true; 7901 Description = S.getTemplateArgumentBindingsText( 7902 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7903 } 7904 7905 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7906 if (!Ctor->isImplicit()) 7907 return isTemplate ? oc_constructor_template : oc_constructor; 7908 7909 if (Ctor->getInheritedConstructor()) 7910 return oc_implicit_inherited_constructor; 7911 7912 if (Ctor->isDefaultConstructor()) 7913 return oc_implicit_default_constructor; 7914 7915 if (Ctor->isMoveConstructor()) 7916 return oc_implicit_move_constructor; 7917 7918 assert(Ctor->isCopyConstructor() && 7919 "unexpected sort of implicit constructor"); 7920 return oc_implicit_copy_constructor; 7921 } 7922 7923 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7924 // This actually gets spelled 'candidate function' for now, but 7925 // it doesn't hurt to split it out. 7926 if (!Meth->isImplicit()) 7927 return isTemplate ? oc_method_template : oc_method; 7928 7929 if (Meth->isMoveAssignmentOperator()) 7930 return oc_implicit_move_assignment; 7931 7932 if (Meth->isCopyAssignmentOperator()) 7933 return oc_implicit_copy_assignment; 7934 7935 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7936 return oc_method; 7937 } 7938 7939 return isTemplate ? oc_function_template : oc_function; 7940} 7941 7942void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7943 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7944 if (!Ctor) return; 7945 7946 Ctor = Ctor->getInheritedConstructor(); 7947 if (!Ctor) return; 7948 7949 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7950} 7951 7952} // end anonymous namespace 7953 7954// Notes the location of an overload candidate. 7955void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7956 std::string FnDesc; 7957 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7958 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7959 << (unsigned) K << FnDesc; 7960 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7961 Diag(Fn->getLocation(), PD); 7962 MaybeEmitInheritedConstructorNote(*this, Fn); 7963} 7964 7965//Notes the location of all overload candidates designated through 7966// OverloadedExpr 7967void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7968 assert(OverloadedExpr->getType() == Context.OverloadTy); 7969 7970 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7971 OverloadExpr *OvlExpr = Ovl.Expression; 7972 7973 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7974 IEnd = OvlExpr->decls_end(); 7975 I != IEnd; ++I) { 7976 if (FunctionTemplateDecl *FunTmpl = 7977 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7978 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7979 } else if (FunctionDecl *Fun 7980 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7981 NoteOverloadCandidate(Fun, DestType); 7982 } 7983 } 7984} 7985 7986/// Diagnoses an ambiguous conversion. The partial diagnostic is the 7987/// "lead" diagnostic; it will be given two arguments, the source and 7988/// target types of the conversion. 7989void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7990 Sema &S, 7991 SourceLocation CaretLoc, 7992 const PartialDiagnostic &PDiag) const { 7993 S.Diag(CaretLoc, PDiag) 7994 << Ambiguous.getFromType() << Ambiguous.getToType(); 7995 // FIXME: The note limiting machinery is borrowed from 7996 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 7997 // refactoring here. 7998 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 7999 unsigned CandsShown = 0; 8000 AmbiguousConversionSequence::const_iterator I, E; 8001 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8002 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8003 break; 8004 ++CandsShown; 8005 S.NoteOverloadCandidate(*I); 8006 } 8007 if (I != E) 8008 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8009} 8010 8011namespace { 8012 8013void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8014 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8015 assert(Conv.isBad()); 8016 assert(Cand->Function && "for now, candidate must be a function"); 8017 FunctionDecl *Fn = Cand->Function; 8018 8019 // There's a conversion slot for the object argument if this is a 8020 // non-constructor method. Note that 'I' corresponds the 8021 // conversion-slot index. 8022 bool isObjectArgument = false; 8023 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8024 if (I == 0) 8025 isObjectArgument = true; 8026 else 8027 I--; 8028 } 8029 8030 std::string FnDesc; 8031 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8032 8033 Expr *FromExpr = Conv.Bad.FromExpr; 8034 QualType FromTy = Conv.Bad.getFromType(); 8035 QualType ToTy = Conv.Bad.getToType(); 8036 8037 if (FromTy == S.Context.OverloadTy) { 8038 assert(FromExpr && "overload set argument came from implicit argument?"); 8039 Expr *E = FromExpr->IgnoreParens(); 8040 if (isa<UnaryOperator>(E)) 8041 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8042 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8043 8044 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8045 << (unsigned) FnKind << FnDesc 8046 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8047 << ToTy << Name << I+1; 8048 MaybeEmitInheritedConstructorNote(S, Fn); 8049 return; 8050 } 8051 8052 // Do some hand-waving analysis to see if the non-viability is due 8053 // to a qualifier mismatch. 8054 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8055 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8056 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8057 CToTy = RT->getPointeeType(); 8058 else { 8059 // TODO: detect and diagnose the full richness of const mismatches. 8060 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8061 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8062 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8063 } 8064 8065 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8066 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8067 Qualifiers FromQs = CFromTy.getQualifiers(); 8068 Qualifiers ToQs = CToTy.getQualifiers(); 8069 8070 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8071 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8072 << (unsigned) FnKind << FnDesc 8073 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8074 << FromTy 8075 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8076 << (unsigned) isObjectArgument << I+1; 8077 MaybeEmitInheritedConstructorNote(S, Fn); 8078 return; 8079 } 8080 8081 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8083 << (unsigned) FnKind << FnDesc 8084 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8085 << FromTy 8086 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8087 << (unsigned) isObjectArgument << I+1; 8088 MaybeEmitInheritedConstructorNote(S, Fn); 8089 return; 8090 } 8091 8092 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8094 << (unsigned) FnKind << FnDesc 8095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8096 << FromTy 8097 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8098 << (unsigned) isObjectArgument << I+1; 8099 MaybeEmitInheritedConstructorNote(S, Fn); 8100 return; 8101 } 8102 8103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8104 assert(CVR && "unexpected qualifiers mismatch"); 8105 8106 if (isObjectArgument) { 8107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8108 << (unsigned) FnKind << FnDesc 8109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8110 << FromTy << (CVR - 1); 8111 } else { 8112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8113 << (unsigned) FnKind << FnDesc 8114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8115 << FromTy << (CVR - 1) << I+1; 8116 } 8117 MaybeEmitInheritedConstructorNote(S, Fn); 8118 return; 8119 } 8120 8121 // Special diagnostic for failure to convert an initializer list, since 8122 // telling the user that it has type void is not useful. 8123 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8125 << (unsigned) FnKind << FnDesc 8126 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8127 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8128 MaybeEmitInheritedConstructorNote(S, Fn); 8129 return; 8130 } 8131 8132 // Diagnose references or pointers to incomplete types differently, 8133 // since it's far from impossible that the incompleteness triggered 8134 // the failure. 8135 QualType TempFromTy = FromTy.getNonReferenceType(); 8136 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8137 TempFromTy = PTy->getPointeeType(); 8138 if (TempFromTy->isIncompleteType()) { 8139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8140 << (unsigned) FnKind << FnDesc 8141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8142 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8143 MaybeEmitInheritedConstructorNote(S, Fn); 8144 return; 8145 } 8146 8147 // Diagnose base -> derived pointer conversions. 8148 unsigned BaseToDerivedConversion = 0; 8149 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8150 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8151 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8152 FromPtrTy->getPointeeType()) && 8153 !FromPtrTy->getPointeeType()->isIncompleteType() && 8154 !ToPtrTy->getPointeeType()->isIncompleteType() && 8155 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8156 FromPtrTy->getPointeeType())) 8157 BaseToDerivedConversion = 1; 8158 } 8159 } else if (const ObjCObjectPointerType *FromPtrTy 8160 = FromTy->getAs<ObjCObjectPointerType>()) { 8161 if (const ObjCObjectPointerType *ToPtrTy 8162 = ToTy->getAs<ObjCObjectPointerType>()) 8163 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8164 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8165 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8166 FromPtrTy->getPointeeType()) && 8167 FromIface->isSuperClassOf(ToIface)) 8168 BaseToDerivedConversion = 2; 8169 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8170 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8171 !FromTy->isIncompleteType() && 8172 !ToRefTy->getPointeeType()->isIncompleteType() && 8173 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8174 BaseToDerivedConversion = 3; 8175 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8176 ToTy.getNonReferenceType().getCanonicalType() == 8177 FromTy.getNonReferenceType().getCanonicalType()) { 8178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8179 << (unsigned) FnKind << FnDesc 8180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8181 << (unsigned) isObjectArgument << I + 1; 8182 MaybeEmitInheritedConstructorNote(S, Fn); 8183 return; 8184 } 8185 } 8186 8187 if (BaseToDerivedConversion) { 8188 S.Diag(Fn->getLocation(), 8189 diag::note_ovl_candidate_bad_base_to_derived_conv) 8190 << (unsigned) FnKind << FnDesc 8191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8192 << (BaseToDerivedConversion - 1) 8193 << FromTy << ToTy << I+1; 8194 MaybeEmitInheritedConstructorNote(S, Fn); 8195 return; 8196 } 8197 8198 if (isa<ObjCObjectPointerType>(CFromTy) && 8199 isa<PointerType>(CToTy)) { 8200 Qualifiers FromQs = CFromTy.getQualifiers(); 8201 Qualifiers ToQs = CToTy.getQualifiers(); 8202 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8204 << (unsigned) FnKind << FnDesc 8205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8206 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8207 MaybeEmitInheritedConstructorNote(S, Fn); 8208 return; 8209 } 8210 } 8211 8212 // Emit the generic diagnostic and, optionally, add the hints to it. 8213 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8214 FDiag << (unsigned) FnKind << FnDesc 8215 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8216 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8217 << (unsigned) (Cand->Fix.Kind); 8218 8219 // If we can fix the conversion, suggest the FixIts. 8220 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8221 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8222 FDiag << *HI; 8223 S.Diag(Fn->getLocation(), FDiag); 8224 8225 MaybeEmitInheritedConstructorNote(S, Fn); 8226} 8227 8228void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8229 unsigned NumFormalArgs) { 8230 // TODO: treat calls to a missing default constructor as a special case 8231 8232 FunctionDecl *Fn = Cand->Function; 8233 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8234 8235 unsigned MinParams = Fn->getMinRequiredArguments(); 8236 8237 // With invalid overloaded operators, it's possible that we think we 8238 // have an arity mismatch when it fact it looks like we have the 8239 // right number of arguments, because only overloaded operators have 8240 // the weird behavior of overloading member and non-member functions. 8241 // Just don't report anything. 8242 if (Fn->isInvalidDecl() && 8243 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8244 return; 8245 8246 // at least / at most / exactly 8247 unsigned mode, modeCount; 8248 if (NumFormalArgs < MinParams) { 8249 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8250 (Cand->FailureKind == ovl_fail_bad_deduction && 8251 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8252 if (MinParams != FnTy->getNumArgs() || 8253 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8254 mode = 0; // "at least" 8255 else 8256 mode = 2; // "exactly" 8257 modeCount = MinParams; 8258 } else { 8259 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8260 (Cand->FailureKind == ovl_fail_bad_deduction && 8261 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8262 if (MinParams != FnTy->getNumArgs()) 8263 mode = 1; // "at most" 8264 else 8265 mode = 2; // "exactly" 8266 modeCount = FnTy->getNumArgs(); 8267 } 8268 8269 std::string Description; 8270 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8271 8272 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8274 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8275 << Fn->getParamDecl(0) << NumFormalArgs; 8276 else 8277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8278 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8279 << modeCount << NumFormalArgs; 8280 MaybeEmitInheritedConstructorNote(S, Fn); 8281} 8282 8283/// Diagnose a failed template-argument deduction. 8284void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8285 unsigned NumArgs) { 8286 FunctionDecl *Fn = Cand->Function; // pattern 8287 8288 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8289 NamedDecl *ParamD; 8290 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8291 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8292 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8293 switch (Cand->DeductionFailure.Result) { 8294 case Sema::TDK_Success: 8295 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8296 8297 case Sema::TDK_Incomplete: { 8298 assert(ParamD && "no parameter found for incomplete deduction result"); 8299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8300 << ParamD->getDeclName(); 8301 MaybeEmitInheritedConstructorNote(S, Fn); 8302 return; 8303 } 8304 8305 case Sema::TDK_Underqualified: { 8306 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8307 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8308 8309 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8310 8311 // Param will have been canonicalized, but it should just be a 8312 // qualified version of ParamD, so move the qualifiers to that. 8313 QualifierCollector Qs; 8314 Qs.strip(Param); 8315 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8316 assert(S.Context.hasSameType(Param, NonCanonParam)); 8317 8318 // Arg has also been canonicalized, but there's nothing we can do 8319 // about that. It also doesn't matter as much, because it won't 8320 // have any template parameters in it (because deduction isn't 8321 // done on dependent types). 8322 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8323 8324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8325 << ParamD->getDeclName() << Arg << NonCanonParam; 8326 MaybeEmitInheritedConstructorNote(S, Fn); 8327 return; 8328 } 8329 8330 case Sema::TDK_Inconsistent: { 8331 assert(ParamD && "no parameter found for inconsistent deduction result"); 8332 int which = 0; 8333 if (isa<TemplateTypeParmDecl>(ParamD)) 8334 which = 0; 8335 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8336 which = 1; 8337 else { 8338 which = 2; 8339 } 8340 8341 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8342 << which << ParamD->getDeclName() 8343 << *Cand->DeductionFailure.getFirstArg() 8344 << *Cand->DeductionFailure.getSecondArg(); 8345 MaybeEmitInheritedConstructorNote(S, Fn); 8346 return; 8347 } 8348 8349 case Sema::TDK_InvalidExplicitArguments: 8350 assert(ParamD && "no parameter found for invalid explicit arguments"); 8351 if (ParamD->getDeclName()) 8352 S.Diag(Fn->getLocation(), 8353 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8354 << ParamD->getDeclName(); 8355 else { 8356 int index = 0; 8357 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8358 index = TTP->getIndex(); 8359 else if (NonTypeTemplateParmDecl *NTTP 8360 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8361 index = NTTP->getIndex(); 8362 else 8363 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8364 S.Diag(Fn->getLocation(), 8365 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8366 << (index + 1); 8367 } 8368 MaybeEmitInheritedConstructorNote(S, Fn); 8369 return; 8370 8371 case Sema::TDK_TooManyArguments: 8372 case Sema::TDK_TooFewArguments: 8373 DiagnoseArityMismatch(S, Cand, NumArgs); 8374 return; 8375 8376 case Sema::TDK_InstantiationDepth: 8377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8378 MaybeEmitInheritedConstructorNote(S, Fn); 8379 return; 8380 8381 case Sema::TDK_SubstitutionFailure: { 8382 // Format the template argument list into the argument string. 8383 llvm::SmallString<128> TemplateArgString; 8384 if (TemplateArgumentList *Args = 8385 Cand->DeductionFailure.getTemplateArgumentList()) { 8386 TemplateArgString = " "; 8387 TemplateArgString += S.getTemplateArgumentBindingsText( 8388 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8389 } 8390 8391 // If this candidate was disabled by enable_if, say so. 8392 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8393 if (PDiag && PDiag->second.getDiagID() == 8394 diag::err_typename_nested_not_found_enable_if) { 8395 // FIXME: Use the source range of the condition, and the fully-qualified 8396 // name of the enable_if template. These are both present in PDiag. 8397 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8398 << "'enable_if'" << TemplateArgString; 8399 return; 8400 } 8401 8402 // Format the SFINAE diagnostic into the argument string. 8403 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8404 // formatted message in another diagnostic. 8405 llvm::SmallString<128> SFINAEArgString; 8406 SourceRange R; 8407 if (PDiag) { 8408 SFINAEArgString = ": "; 8409 R = SourceRange(PDiag->first, PDiag->first); 8410 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8411 } 8412 8413 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8414 << TemplateArgString << SFINAEArgString << R; 8415 MaybeEmitInheritedConstructorNote(S, Fn); 8416 return; 8417 } 8418 8419 // TODO: diagnose these individually, then kill off 8420 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8421 case Sema::TDK_NonDeducedMismatch: 8422 case Sema::TDK_FailedOverloadResolution: 8423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8424 MaybeEmitInheritedConstructorNote(S, Fn); 8425 return; 8426 } 8427} 8428 8429/// CUDA: diagnose an invalid call across targets. 8430void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8431 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8432 FunctionDecl *Callee = Cand->Function; 8433 8434 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8435 CalleeTarget = S.IdentifyCUDATarget(Callee); 8436 8437 std::string FnDesc; 8438 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8439 8440 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8441 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8442} 8443 8444/// Generates a 'note' diagnostic for an overload candidate. We've 8445/// already generated a primary error at the call site. 8446/// 8447/// It really does need to be a single diagnostic with its caret 8448/// pointed at the candidate declaration. Yes, this creates some 8449/// major challenges of technical writing. Yes, this makes pointing 8450/// out problems with specific arguments quite awkward. It's still 8451/// better than generating twenty screens of text for every failed 8452/// overload. 8453/// 8454/// It would be great to be able to express per-candidate problems 8455/// more richly for those diagnostic clients that cared, but we'd 8456/// still have to be just as careful with the default diagnostics. 8457void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8458 unsigned NumArgs) { 8459 FunctionDecl *Fn = Cand->Function; 8460 8461 // Note deleted candidates, but only if they're viable. 8462 if (Cand->Viable && (Fn->isDeleted() || 8463 S.isFunctionConsideredUnavailable(Fn))) { 8464 std::string FnDesc; 8465 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8466 8467 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8468 << FnKind << FnDesc 8469 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8470 MaybeEmitInheritedConstructorNote(S, Fn); 8471 return; 8472 } 8473 8474 // We don't really have anything else to say about viable candidates. 8475 if (Cand->Viable) { 8476 S.NoteOverloadCandidate(Fn); 8477 return; 8478 } 8479 8480 switch (Cand->FailureKind) { 8481 case ovl_fail_too_many_arguments: 8482 case ovl_fail_too_few_arguments: 8483 return DiagnoseArityMismatch(S, Cand, NumArgs); 8484 8485 case ovl_fail_bad_deduction: 8486 return DiagnoseBadDeduction(S, Cand, NumArgs); 8487 8488 case ovl_fail_trivial_conversion: 8489 case ovl_fail_bad_final_conversion: 8490 case ovl_fail_final_conversion_not_exact: 8491 return S.NoteOverloadCandidate(Fn); 8492 8493 case ovl_fail_bad_conversion: { 8494 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8495 for (unsigned N = Cand->NumConversions; I != N; ++I) 8496 if (Cand->Conversions[I].isBad()) 8497 return DiagnoseBadConversion(S, Cand, I); 8498 8499 // FIXME: this currently happens when we're called from SemaInit 8500 // when user-conversion overload fails. Figure out how to handle 8501 // those conditions and diagnose them well. 8502 return S.NoteOverloadCandidate(Fn); 8503 } 8504 8505 case ovl_fail_bad_target: 8506 return DiagnoseBadTarget(S, Cand); 8507 } 8508} 8509 8510void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8511 // Desugar the type of the surrogate down to a function type, 8512 // retaining as many typedefs as possible while still showing 8513 // the function type (and, therefore, its parameter types). 8514 QualType FnType = Cand->Surrogate->getConversionType(); 8515 bool isLValueReference = false; 8516 bool isRValueReference = false; 8517 bool isPointer = false; 8518 if (const LValueReferenceType *FnTypeRef = 8519 FnType->getAs<LValueReferenceType>()) { 8520 FnType = FnTypeRef->getPointeeType(); 8521 isLValueReference = true; 8522 } else if (const RValueReferenceType *FnTypeRef = 8523 FnType->getAs<RValueReferenceType>()) { 8524 FnType = FnTypeRef->getPointeeType(); 8525 isRValueReference = true; 8526 } 8527 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8528 FnType = FnTypePtr->getPointeeType(); 8529 isPointer = true; 8530 } 8531 // Desugar down to a function type. 8532 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8533 // Reconstruct the pointer/reference as appropriate. 8534 if (isPointer) FnType = S.Context.getPointerType(FnType); 8535 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8536 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8537 8538 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8539 << FnType; 8540 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8541} 8542 8543void NoteBuiltinOperatorCandidate(Sema &S, 8544 StringRef Opc, 8545 SourceLocation OpLoc, 8546 OverloadCandidate *Cand) { 8547 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8548 std::string TypeStr("operator"); 8549 TypeStr += Opc; 8550 TypeStr += "("; 8551 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8552 if (Cand->NumConversions == 1) { 8553 TypeStr += ")"; 8554 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8555 } else { 8556 TypeStr += ", "; 8557 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8558 TypeStr += ")"; 8559 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8560 } 8561} 8562 8563void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8564 OverloadCandidate *Cand) { 8565 unsigned NoOperands = Cand->NumConversions; 8566 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8567 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8568 if (ICS.isBad()) break; // all meaningless after first invalid 8569 if (!ICS.isAmbiguous()) continue; 8570 8571 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8572 S.PDiag(diag::note_ambiguous_type_conversion)); 8573 } 8574} 8575 8576SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8577 if (Cand->Function) 8578 return Cand->Function->getLocation(); 8579 if (Cand->IsSurrogate) 8580 return Cand->Surrogate->getLocation(); 8581 return SourceLocation(); 8582} 8583 8584static unsigned 8585RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8586 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8587 case Sema::TDK_Success: 8588 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8589 8590 case Sema::TDK_Invalid: 8591 case Sema::TDK_Incomplete: 8592 return 1; 8593 8594 case Sema::TDK_Underqualified: 8595 case Sema::TDK_Inconsistent: 8596 return 2; 8597 8598 case Sema::TDK_SubstitutionFailure: 8599 case Sema::TDK_NonDeducedMismatch: 8600 return 3; 8601 8602 case Sema::TDK_InstantiationDepth: 8603 case Sema::TDK_FailedOverloadResolution: 8604 return 4; 8605 8606 case Sema::TDK_InvalidExplicitArguments: 8607 return 5; 8608 8609 case Sema::TDK_TooManyArguments: 8610 case Sema::TDK_TooFewArguments: 8611 return 6; 8612 } 8613 llvm_unreachable("Unhandled deduction result"); 8614} 8615 8616struct CompareOverloadCandidatesForDisplay { 8617 Sema &S; 8618 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8619 8620 bool operator()(const OverloadCandidate *L, 8621 const OverloadCandidate *R) { 8622 // Fast-path this check. 8623 if (L == R) return false; 8624 8625 // Order first by viability. 8626 if (L->Viable) { 8627 if (!R->Viable) return true; 8628 8629 // TODO: introduce a tri-valued comparison for overload 8630 // candidates. Would be more worthwhile if we had a sort 8631 // that could exploit it. 8632 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8633 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8634 } else if (R->Viable) 8635 return false; 8636 8637 assert(L->Viable == R->Viable); 8638 8639 // Criteria by which we can sort non-viable candidates: 8640 if (!L->Viable) { 8641 // 1. Arity mismatches come after other candidates. 8642 if (L->FailureKind == ovl_fail_too_many_arguments || 8643 L->FailureKind == ovl_fail_too_few_arguments) 8644 return false; 8645 if (R->FailureKind == ovl_fail_too_many_arguments || 8646 R->FailureKind == ovl_fail_too_few_arguments) 8647 return true; 8648 8649 // 2. Bad conversions come first and are ordered by the number 8650 // of bad conversions and quality of good conversions. 8651 if (L->FailureKind == ovl_fail_bad_conversion) { 8652 if (R->FailureKind != ovl_fail_bad_conversion) 8653 return true; 8654 8655 // The conversion that can be fixed with a smaller number of changes, 8656 // comes first. 8657 unsigned numLFixes = L->Fix.NumConversionsFixed; 8658 unsigned numRFixes = R->Fix.NumConversionsFixed; 8659 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8660 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8661 if (numLFixes != numRFixes) { 8662 if (numLFixes < numRFixes) 8663 return true; 8664 else 8665 return false; 8666 } 8667 8668 // If there's any ordering between the defined conversions... 8669 // FIXME: this might not be transitive. 8670 assert(L->NumConversions == R->NumConversions); 8671 8672 int leftBetter = 0; 8673 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8674 for (unsigned E = L->NumConversions; I != E; ++I) { 8675 switch (CompareImplicitConversionSequences(S, 8676 L->Conversions[I], 8677 R->Conversions[I])) { 8678 case ImplicitConversionSequence::Better: 8679 leftBetter++; 8680 break; 8681 8682 case ImplicitConversionSequence::Worse: 8683 leftBetter--; 8684 break; 8685 8686 case ImplicitConversionSequence::Indistinguishable: 8687 break; 8688 } 8689 } 8690 if (leftBetter > 0) return true; 8691 if (leftBetter < 0) return false; 8692 8693 } else if (R->FailureKind == ovl_fail_bad_conversion) 8694 return false; 8695 8696 if (L->FailureKind == ovl_fail_bad_deduction) { 8697 if (R->FailureKind != ovl_fail_bad_deduction) 8698 return true; 8699 8700 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8701 return RankDeductionFailure(L->DeductionFailure) 8702 < RankDeductionFailure(R->DeductionFailure); 8703 } else if (R->FailureKind == ovl_fail_bad_deduction) 8704 return false; 8705 8706 // TODO: others? 8707 } 8708 8709 // Sort everything else by location. 8710 SourceLocation LLoc = GetLocationForCandidate(L); 8711 SourceLocation RLoc = GetLocationForCandidate(R); 8712 8713 // Put candidates without locations (e.g. builtins) at the end. 8714 if (LLoc.isInvalid()) return false; 8715 if (RLoc.isInvalid()) return true; 8716 8717 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8718 } 8719}; 8720 8721/// CompleteNonViableCandidate - Normally, overload resolution only 8722/// computes up to the first. Produces the FixIt set if possible. 8723void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8724 llvm::ArrayRef<Expr *> Args) { 8725 assert(!Cand->Viable); 8726 8727 // Don't do anything on failures other than bad conversion. 8728 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8729 8730 // We only want the FixIts if all the arguments can be corrected. 8731 bool Unfixable = false; 8732 // Use a implicit copy initialization to check conversion fixes. 8733 Cand->Fix.setConversionChecker(TryCopyInitialization); 8734 8735 // Skip forward to the first bad conversion. 8736 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8737 unsigned ConvCount = Cand->NumConversions; 8738 while (true) { 8739 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8740 ConvIdx++; 8741 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8742 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8743 break; 8744 } 8745 } 8746 8747 if (ConvIdx == ConvCount) 8748 return; 8749 8750 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8751 "remaining conversion is initialized?"); 8752 8753 // FIXME: this should probably be preserved from the overload 8754 // operation somehow. 8755 bool SuppressUserConversions = false; 8756 8757 const FunctionProtoType* Proto; 8758 unsigned ArgIdx = ConvIdx; 8759 8760 if (Cand->IsSurrogate) { 8761 QualType ConvType 8762 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8763 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8764 ConvType = ConvPtrType->getPointeeType(); 8765 Proto = ConvType->getAs<FunctionProtoType>(); 8766 ArgIdx--; 8767 } else if (Cand->Function) { 8768 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8769 if (isa<CXXMethodDecl>(Cand->Function) && 8770 !isa<CXXConstructorDecl>(Cand->Function)) 8771 ArgIdx--; 8772 } else { 8773 // Builtin binary operator with a bad first conversion. 8774 assert(ConvCount <= 3); 8775 for (; ConvIdx != ConvCount; ++ConvIdx) 8776 Cand->Conversions[ConvIdx] 8777 = TryCopyInitialization(S, Args[ConvIdx], 8778 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8779 SuppressUserConversions, 8780 /*InOverloadResolution*/ true, 8781 /*AllowObjCWritebackConversion=*/ 8782 S.getLangOpts().ObjCAutoRefCount); 8783 return; 8784 } 8785 8786 // Fill in the rest of the conversions. 8787 unsigned NumArgsInProto = Proto->getNumArgs(); 8788 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8789 if (ArgIdx < NumArgsInProto) { 8790 Cand->Conversions[ConvIdx] 8791 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8792 SuppressUserConversions, 8793 /*InOverloadResolution=*/true, 8794 /*AllowObjCWritebackConversion=*/ 8795 S.getLangOpts().ObjCAutoRefCount); 8796 // Store the FixIt in the candidate if it exists. 8797 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8798 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8799 } 8800 else 8801 Cand->Conversions[ConvIdx].setEllipsis(); 8802 } 8803} 8804 8805} // end anonymous namespace 8806 8807/// PrintOverloadCandidates - When overload resolution fails, prints 8808/// diagnostic messages containing the candidates in the candidate 8809/// set. 8810void OverloadCandidateSet::NoteCandidates(Sema &S, 8811 OverloadCandidateDisplayKind OCD, 8812 llvm::ArrayRef<Expr *> Args, 8813 StringRef Opc, 8814 SourceLocation OpLoc) { 8815 // Sort the candidates by viability and position. Sorting directly would 8816 // be prohibitive, so we make a set of pointers and sort those. 8817 SmallVector<OverloadCandidate*, 32> Cands; 8818 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8819 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8820 if (Cand->Viable) 8821 Cands.push_back(Cand); 8822 else if (OCD == OCD_AllCandidates) { 8823 CompleteNonViableCandidate(S, Cand, Args); 8824 if (Cand->Function || Cand->IsSurrogate) 8825 Cands.push_back(Cand); 8826 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8827 // want to list every possible builtin candidate. 8828 } 8829 } 8830 8831 std::sort(Cands.begin(), Cands.end(), 8832 CompareOverloadCandidatesForDisplay(S)); 8833 8834 bool ReportedAmbiguousConversions = false; 8835 8836 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8837 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8838 unsigned CandsShown = 0; 8839 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8840 OverloadCandidate *Cand = *I; 8841 8842 // Set an arbitrary limit on the number of candidate functions we'll spam 8843 // the user with. FIXME: This limit should depend on details of the 8844 // candidate list. 8845 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8846 break; 8847 } 8848 ++CandsShown; 8849 8850 if (Cand->Function) 8851 NoteFunctionCandidate(S, Cand, Args.size()); 8852 else if (Cand->IsSurrogate) 8853 NoteSurrogateCandidate(S, Cand); 8854 else { 8855 assert(Cand->Viable && 8856 "Non-viable built-in candidates are not added to Cands."); 8857 // Generally we only see ambiguities including viable builtin 8858 // operators if overload resolution got screwed up by an 8859 // ambiguous user-defined conversion. 8860 // 8861 // FIXME: It's quite possible for different conversions to see 8862 // different ambiguities, though. 8863 if (!ReportedAmbiguousConversions) { 8864 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8865 ReportedAmbiguousConversions = true; 8866 } 8867 8868 // If this is a viable builtin, print it. 8869 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8870 } 8871 } 8872 8873 if (I != E) 8874 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8875} 8876 8877// [PossiblyAFunctionType] --> [Return] 8878// NonFunctionType --> NonFunctionType 8879// R (A) --> R(A) 8880// R (*)(A) --> R (A) 8881// R (&)(A) --> R (A) 8882// R (S::*)(A) --> R (A) 8883QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8884 QualType Ret = PossiblyAFunctionType; 8885 if (const PointerType *ToTypePtr = 8886 PossiblyAFunctionType->getAs<PointerType>()) 8887 Ret = ToTypePtr->getPointeeType(); 8888 else if (const ReferenceType *ToTypeRef = 8889 PossiblyAFunctionType->getAs<ReferenceType>()) 8890 Ret = ToTypeRef->getPointeeType(); 8891 else if (const MemberPointerType *MemTypePtr = 8892 PossiblyAFunctionType->getAs<MemberPointerType>()) 8893 Ret = MemTypePtr->getPointeeType(); 8894 Ret = 8895 Context.getCanonicalType(Ret).getUnqualifiedType(); 8896 return Ret; 8897} 8898 8899// A helper class to help with address of function resolution 8900// - allows us to avoid passing around all those ugly parameters 8901class AddressOfFunctionResolver 8902{ 8903 Sema& S; 8904 Expr* SourceExpr; 8905 const QualType& TargetType; 8906 QualType TargetFunctionType; // Extracted function type from target type 8907 8908 bool Complain; 8909 //DeclAccessPair& ResultFunctionAccessPair; 8910 ASTContext& Context; 8911 8912 bool TargetTypeIsNonStaticMemberFunction; 8913 bool FoundNonTemplateFunction; 8914 8915 OverloadExpr::FindResult OvlExprInfo; 8916 OverloadExpr *OvlExpr; 8917 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8918 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8919 8920public: 8921 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8922 const QualType& TargetType, bool Complain) 8923 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8924 Complain(Complain), Context(S.getASTContext()), 8925 TargetTypeIsNonStaticMemberFunction( 8926 !!TargetType->getAs<MemberPointerType>()), 8927 FoundNonTemplateFunction(false), 8928 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8929 OvlExpr(OvlExprInfo.Expression) 8930 { 8931 ExtractUnqualifiedFunctionTypeFromTargetType(); 8932 8933 if (!TargetFunctionType->isFunctionType()) { 8934 if (OvlExpr->hasExplicitTemplateArgs()) { 8935 DeclAccessPair dap; 8936 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8937 OvlExpr, false, &dap) ) { 8938 8939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8940 if (!Method->isStatic()) { 8941 // If the target type is a non-function type and the function 8942 // found is a non-static member function, pretend as if that was 8943 // the target, it's the only possible type to end up with. 8944 TargetTypeIsNonStaticMemberFunction = true; 8945 8946 // And skip adding the function if its not in the proper form. 8947 // We'll diagnose this due to an empty set of functions. 8948 if (!OvlExprInfo.HasFormOfMemberPointer) 8949 return; 8950 } 8951 } 8952 8953 Matches.push_back(std::make_pair(dap,Fn)); 8954 } 8955 } 8956 return; 8957 } 8958 8959 if (OvlExpr->hasExplicitTemplateArgs()) 8960 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8961 8962 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8963 // C++ [over.over]p4: 8964 // If more than one function is selected, [...] 8965 if (Matches.size() > 1) { 8966 if (FoundNonTemplateFunction) 8967 EliminateAllTemplateMatches(); 8968 else 8969 EliminateAllExceptMostSpecializedTemplate(); 8970 } 8971 } 8972 } 8973 8974private: 8975 bool isTargetTypeAFunction() const { 8976 return TargetFunctionType->isFunctionType(); 8977 } 8978 8979 // [ToType] [Return] 8980 8981 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8982 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8983 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8984 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8985 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8986 } 8987 8988 // return true if any matching specializations were found 8989 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8990 const DeclAccessPair& CurAccessFunPair) { 8991 if (CXXMethodDecl *Method 8992 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8993 // Skip non-static function templates when converting to pointer, and 8994 // static when converting to member pointer. 8995 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8996 return false; 8997 } 8998 else if (TargetTypeIsNonStaticMemberFunction) 8999 return false; 9000 9001 // C++ [over.over]p2: 9002 // If the name is a function template, template argument deduction is 9003 // done (14.8.2.2), and if the argument deduction succeeds, the 9004 // resulting template argument list is used to generate a single 9005 // function template specialization, which is added to the set of 9006 // overloaded functions considered. 9007 FunctionDecl *Specialization = 0; 9008 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9009 if (Sema::TemplateDeductionResult Result 9010 = S.DeduceTemplateArguments(FunctionTemplate, 9011 &OvlExplicitTemplateArgs, 9012 TargetFunctionType, Specialization, 9013 Info)) { 9014 // FIXME: make a note of the failed deduction for diagnostics. 9015 (void)Result; 9016 return false; 9017 } 9018 9019 // Template argument deduction ensures that we have an exact match. 9020 // This function template specicalization works. 9021 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9022 assert(TargetFunctionType 9023 == Context.getCanonicalType(Specialization->getType())); 9024 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9025 return true; 9026 } 9027 9028 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9029 const DeclAccessPair& CurAccessFunPair) { 9030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9031 // Skip non-static functions when converting to pointer, and static 9032 // when converting to member pointer. 9033 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9034 return false; 9035 } 9036 else if (TargetTypeIsNonStaticMemberFunction) 9037 return false; 9038 9039 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9040 if (S.getLangOpts().CUDA) 9041 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9042 if (S.CheckCUDATarget(Caller, FunDecl)) 9043 return false; 9044 9045 QualType ResultTy; 9046 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9047 FunDecl->getType()) || 9048 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9049 ResultTy)) { 9050 Matches.push_back(std::make_pair(CurAccessFunPair, 9051 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9052 FoundNonTemplateFunction = true; 9053 return true; 9054 } 9055 } 9056 9057 return false; 9058 } 9059 9060 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9061 bool Ret = false; 9062 9063 // If the overload expression doesn't have the form of a pointer to 9064 // member, don't try to convert it to a pointer-to-member type. 9065 if (IsInvalidFormOfPointerToMemberFunction()) 9066 return false; 9067 9068 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9069 E = OvlExpr->decls_end(); 9070 I != E; ++I) { 9071 // Look through any using declarations to find the underlying function. 9072 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9073 9074 // C++ [over.over]p3: 9075 // Non-member functions and static member functions match 9076 // targets of type "pointer-to-function" or "reference-to-function." 9077 // Nonstatic member functions match targets of 9078 // type "pointer-to-member-function." 9079 // Note that according to DR 247, the containing class does not matter. 9080 if (FunctionTemplateDecl *FunctionTemplate 9081 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9082 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9083 Ret = true; 9084 } 9085 // If we have explicit template arguments supplied, skip non-templates. 9086 else if (!OvlExpr->hasExplicitTemplateArgs() && 9087 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9088 Ret = true; 9089 } 9090 assert(Ret || Matches.empty()); 9091 return Ret; 9092 } 9093 9094 void EliminateAllExceptMostSpecializedTemplate() { 9095 // [...] and any given function template specialization F1 is 9096 // eliminated if the set contains a second function template 9097 // specialization whose function template is more specialized 9098 // than the function template of F1 according to the partial 9099 // ordering rules of 14.5.5.2. 9100 9101 // The algorithm specified above is quadratic. We instead use a 9102 // two-pass algorithm (similar to the one used to identify the 9103 // best viable function in an overload set) that identifies the 9104 // best function template (if it exists). 9105 9106 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9107 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9108 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9109 9110 UnresolvedSetIterator Result = 9111 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9112 TPOC_Other, 0, SourceExpr->getLocStart(), 9113 S.PDiag(), 9114 S.PDiag(diag::err_addr_ovl_ambiguous) 9115 << Matches[0].second->getDeclName(), 9116 S.PDiag(diag::note_ovl_candidate) 9117 << (unsigned) oc_function_template, 9118 Complain, TargetFunctionType); 9119 9120 if (Result != MatchesCopy.end()) { 9121 // Make it the first and only element 9122 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9123 Matches[0].second = cast<FunctionDecl>(*Result); 9124 Matches.resize(1); 9125 } 9126 } 9127 9128 void EliminateAllTemplateMatches() { 9129 // [...] any function template specializations in the set are 9130 // eliminated if the set also contains a non-template function, [...] 9131 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9132 if (Matches[I].second->getPrimaryTemplate() == 0) 9133 ++I; 9134 else { 9135 Matches[I] = Matches[--N]; 9136 Matches.set_size(N); 9137 } 9138 } 9139 } 9140 9141public: 9142 void ComplainNoMatchesFound() const { 9143 assert(Matches.empty()); 9144 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9145 << OvlExpr->getName() << TargetFunctionType 9146 << OvlExpr->getSourceRange(); 9147 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9148 } 9149 9150 bool IsInvalidFormOfPointerToMemberFunction() const { 9151 return TargetTypeIsNonStaticMemberFunction && 9152 !OvlExprInfo.HasFormOfMemberPointer; 9153 } 9154 9155 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9156 // TODO: Should we condition this on whether any functions might 9157 // have matched, or is it more appropriate to do that in callers? 9158 // TODO: a fixit wouldn't hurt. 9159 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9160 << TargetType << OvlExpr->getSourceRange(); 9161 } 9162 9163 void ComplainOfInvalidConversion() const { 9164 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9165 << OvlExpr->getName() << TargetType; 9166 } 9167 9168 void ComplainMultipleMatchesFound() const { 9169 assert(Matches.size() > 1); 9170 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9171 << OvlExpr->getName() 9172 << OvlExpr->getSourceRange(); 9173 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9174 } 9175 9176 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9177 9178 int getNumMatches() const { return Matches.size(); } 9179 9180 FunctionDecl* getMatchingFunctionDecl() const { 9181 if (Matches.size() != 1) return 0; 9182 return Matches[0].second; 9183 } 9184 9185 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9186 if (Matches.size() != 1) return 0; 9187 return &Matches[0].first; 9188 } 9189}; 9190 9191/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9192/// an overloaded function (C++ [over.over]), where @p From is an 9193/// expression with overloaded function type and @p ToType is the type 9194/// we're trying to resolve to. For example: 9195/// 9196/// @code 9197/// int f(double); 9198/// int f(int); 9199/// 9200/// int (*pfd)(double) = f; // selects f(double) 9201/// @endcode 9202/// 9203/// This routine returns the resulting FunctionDecl if it could be 9204/// resolved, and NULL otherwise. When @p Complain is true, this 9205/// routine will emit diagnostics if there is an error. 9206FunctionDecl * 9207Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9208 QualType TargetType, 9209 bool Complain, 9210 DeclAccessPair &FoundResult, 9211 bool *pHadMultipleCandidates) { 9212 assert(AddressOfExpr->getType() == Context.OverloadTy); 9213 9214 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9215 Complain); 9216 int NumMatches = Resolver.getNumMatches(); 9217 FunctionDecl* Fn = 0; 9218 if (NumMatches == 0 && Complain) { 9219 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9220 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9221 else 9222 Resolver.ComplainNoMatchesFound(); 9223 } 9224 else if (NumMatches > 1 && Complain) 9225 Resolver.ComplainMultipleMatchesFound(); 9226 else if (NumMatches == 1) { 9227 Fn = Resolver.getMatchingFunctionDecl(); 9228 assert(Fn); 9229 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9230 if (Complain) 9231 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9232 } 9233 9234 if (pHadMultipleCandidates) 9235 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9236 return Fn; 9237} 9238 9239/// \brief Given an expression that refers to an overloaded function, try to 9240/// resolve that overloaded function expression down to a single function. 9241/// 9242/// This routine can only resolve template-ids that refer to a single function 9243/// template, where that template-id refers to a single template whose template 9244/// arguments are either provided by the template-id or have defaults, 9245/// as described in C++0x [temp.arg.explicit]p3. 9246FunctionDecl * 9247Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9248 bool Complain, 9249 DeclAccessPair *FoundResult) { 9250 // C++ [over.over]p1: 9251 // [...] [Note: any redundant set of parentheses surrounding the 9252 // overloaded function name is ignored (5.1). ] 9253 // C++ [over.over]p1: 9254 // [...] The overloaded function name can be preceded by the & 9255 // operator. 9256 9257 // If we didn't actually find any template-ids, we're done. 9258 if (!ovl->hasExplicitTemplateArgs()) 9259 return 0; 9260 9261 TemplateArgumentListInfo ExplicitTemplateArgs; 9262 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9263 9264 // Look through all of the overloaded functions, searching for one 9265 // whose type matches exactly. 9266 FunctionDecl *Matched = 0; 9267 for (UnresolvedSetIterator I = ovl->decls_begin(), 9268 E = ovl->decls_end(); I != E; ++I) { 9269 // C++0x [temp.arg.explicit]p3: 9270 // [...] In contexts where deduction is done and fails, or in contexts 9271 // where deduction is not done, if a template argument list is 9272 // specified and it, along with any default template arguments, 9273 // identifies a single function template specialization, then the 9274 // template-id is an lvalue for the function template specialization. 9275 FunctionTemplateDecl *FunctionTemplate 9276 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9277 9278 // C++ [over.over]p2: 9279 // If the name is a function template, template argument deduction is 9280 // done (14.8.2.2), and if the argument deduction succeeds, the 9281 // resulting template argument list is used to generate a single 9282 // function template specialization, which is added to the set of 9283 // overloaded functions considered. 9284 FunctionDecl *Specialization = 0; 9285 TemplateDeductionInfo Info(ovl->getNameLoc()); 9286 if (TemplateDeductionResult Result 9287 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9288 Specialization, Info)) { 9289 // FIXME: make a note of the failed deduction for diagnostics. 9290 (void)Result; 9291 continue; 9292 } 9293 9294 assert(Specialization && "no specialization and no error?"); 9295 9296 // Multiple matches; we can't resolve to a single declaration. 9297 if (Matched) { 9298 if (Complain) { 9299 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9300 << ovl->getName(); 9301 NoteAllOverloadCandidates(ovl); 9302 } 9303 return 0; 9304 } 9305 9306 Matched = Specialization; 9307 if (FoundResult) *FoundResult = I.getPair(); 9308 } 9309 9310 return Matched; 9311} 9312 9313 9314 9315 9316// Resolve and fix an overloaded expression that can be resolved 9317// because it identifies a single function template specialization. 9318// 9319// Last three arguments should only be supplied if Complain = true 9320// 9321// Return true if it was logically possible to so resolve the 9322// expression, regardless of whether or not it succeeded. Always 9323// returns true if 'complain' is set. 9324bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9325 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9326 bool complain, const SourceRange& OpRangeForComplaining, 9327 QualType DestTypeForComplaining, 9328 unsigned DiagIDForComplaining) { 9329 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9330 9331 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9332 9333 DeclAccessPair found; 9334 ExprResult SingleFunctionExpression; 9335 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9336 ovl.Expression, /*complain*/ false, &found)) { 9337 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9338 SrcExpr = ExprError(); 9339 return true; 9340 } 9341 9342 // It is only correct to resolve to an instance method if we're 9343 // resolving a form that's permitted to be a pointer to member. 9344 // Otherwise we'll end up making a bound member expression, which 9345 // is illegal in all the contexts we resolve like this. 9346 if (!ovl.HasFormOfMemberPointer && 9347 isa<CXXMethodDecl>(fn) && 9348 cast<CXXMethodDecl>(fn)->isInstance()) { 9349 if (!complain) return false; 9350 9351 Diag(ovl.Expression->getExprLoc(), 9352 diag::err_bound_member_function) 9353 << 0 << ovl.Expression->getSourceRange(); 9354 9355 // TODO: I believe we only end up here if there's a mix of 9356 // static and non-static candidates (otherwise the expression 9357 // would have 'bound member' type, not 'overload' type). 9358 // Ideally we would note which candidate was chosen and why 9359 // the static candidates were rejected. 9360 SrcExpr = ExprError(); 9361 return true; 9362 } 9363 9364 // Fix the expression to refer to 'fn'. 9365 SingleFunctionExpression = 9366 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9367 9368 // If desired, do function-to-pointer decay. 9369 if (doFunctionPointerConverion) { 9370 SingleFunctionExpression = 9371 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9372 if (SingleFunctionExpression.isInvalid()) { 9373 SrcExpr = ExprError(); 9374 return true; 9375 } 9376 } 9377 } 9378 9379 if (!SingleFunctionExpression.isUsable()) { 9380 if (complain) { 9381 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9382 << ovl.Expression->getName() 9383 << DestTypeForComplaining 9384 << OpRangeForComplaining 9385 << ovl.Expression->getQualifierLoc().getSourceRange(); 9386 NoteAllOverloadCandidates(SrcExpr.get()); 9387 9388 SrcExpr = ExprError(); 9389 return true; 9390 } 9391 9392 return false; 9393 } 9394 9395 SrcExpr = SingleFunctionExpression; 9396 return true; 9397} 9398 9399/// \brief Add a single candidate to the overload set. 9400static void AddOverloadedCallCandidate(Sema &S, 9401 DeclAccessPair FoundDecl, 9402 TemplateArgumentListInfo *ExplicitTemplateArgs, 9403 llvm::ArrayRef<Expr *> Args, 9404 OverloadCandidateSet &CandidateSet, 9405 bool PartialOverloading, 9406 bool KnownValid) { 9407 NamedDecl *Callee = FoundDecl.getDecl(); 9408 if (isa<UsingShadowDecl>(Callee)) 9409 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9410 9411 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9412 if (ExplicitTemplateArgs) { 9413 assert(!KnownValid && "Explicit template arguments?"); 9414 return; 9415 } 9416 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9417 PartialOverloading); 9418 return; 9419 } 9420 9421 if (FunctionTemplateDecl *FuncTemplate 9422 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9423 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9424 ExplicitTemplateArgs, Args, CandidateSet); 9425 return; 9426 } 9427 9428 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9429} 9430 9431/// \brief Add the overload candidates named by callee and/or found by argument 9432/// dependent lookup to the given overload set. 9433void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9434 llvm::ArrayRef<Expr *> Args, 9435 OverloadCandidateSet &CandidateSet, 9436 bool PartialOverloading) { 9437 9438#ifndef NDEBUG 9439 // Verify that ArgumentDependentLookup is consistent with the rules 9440 // in C++0x [basic.lookup.argdep]p3: 9441 // 9442 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9443 // and let Y be the lookup set produced by argument dependent 9444 // lookup (defined as follows). If X contains 9445 // 9446 // -- a declaration of a class member, or 9447 // 9448 // -- a block-scope function declaration that is not a 9449 // using-declaration, or 9450 // 9451 // -- a declaration that is neither a function or a function 9452 // template 9453 // 9454 // then Y is empty. 9455 9456 if (ULE->requiresADL()) { 9457 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9458 E = ULE->decls_end(); I != E; ++I) { 9459 assert(!(*I)->getDeclContext()->isRecord()); 9460 assert(isa<UsingShadowDecl>(*I) || 9461 !(*I)->getDeclContext()->isFunctionOrMethod()); 9462 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9463 } 9464 } 9465#endif 9466 9467 // It would be nice to avoid this copy. 9468 TemplateArgumentListInfo TABuffer; 9469 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9470 if (ULE->hasExplicitTemplateArgs()) { 9471 ULE->copyTemplateArgumentsInto(TABuffer); 9472 ExplicitTemplateArgs = &TABuffer; 9473 } 9474 9475 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9476 E = ULE->decls_end(); I != E; ++I) 9477 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9478 CandidateSet, PartialOverloading, 9479 /*KnownValid*/ true); 9480 9481 if (ULE->requiresADL()) 9482 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9483 ULE->getExprLoc(), 9484 Args, ExplicitTemplateArgs, 9485 CandidateSet, PartialOverloading); 9486} 9487 9488/// Attempt to recover from an ill-formed use of a non-dependent name in a 9489/// template, where the non-dependent name was declared after the template 9490/// was defined. This is common in code written for a compilers which do not 9491/// correctly implement two-stage name lookup. 9492/// 9493/// Returns true if a viable candidate was found and a diagnostic was issued. 9494static bool 9495DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9496 const CXXScopeSpec &SS, LookupResult &R, 9497 TemplateArgumentListInfo *ExplicitTemplateArgs, 9498 llvm::ArrayRef<Expr *> Args) { 9499 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9500 return false; 9501 9502 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9503 if (DC->isTransparentContext()) 9504 continue; 9505 9506 SemaRef.LookupQualifiedName(R, DC); 9507 9508 if (!R.empty()) { 9509 R.suppressDiagnostics(); 9510 9511 if (isa<CXXRecordDecl>(DC)) { 9512 // Don't diagnose names we find in classes; we get much better 9513 // diagnostics for these from DiagnoseEmptyLookup. 9514 R.clear(); 9515 return false; 9516 } 9517 9518 OverloadCandidateSet Candidates(FnLoc); 9519 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9520 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9521 ExplicitTemplateArgs, Args, 9522 Candidates, false, /*KnownValid*/ false); 9523 9524 OverloadCandidateSet::iterator Best; 9525 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9526 // No viable functions. Don't bother the user with notes for functions 9527 // which don't work and shouldn't be found anyway. 9528 R.clear(); 9529 return false; 9530 } 9531 9532 // Find the namespaces where ADL would have looked, and suggest 9533 // declaring the function there instead. 9534 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9535 Sema::AssociatedClassSet AssociatedClasses; 9536 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9537 AssociatedNamespaces, 9538 AssociatedClasses); 9539 // Never suggest declaring a function within namespace 'std'. 9540 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9541 DeclContext *Std = SemaRef.getStdNamespace(); 9542 for (Sema::AssociatedNamespaceSet::iterator 9543 it = AssociatedNamespaces.begin(), 9544 end = AssociatedNamespaces.end(); it != end; ++it) { 9545 NamespaceDecl *Assoc = cast<NamespaceDecl>(*it); 9546 if ((!Std || !Std->Encloses(Assoc)) && 9547 Assoc->getQualifiedNameAsString().find("__") == std::string::npos) 9548 SuggestedNamespaces.insert(Assoc); 9549 } 9550 9551 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9552 << R.getLookupName(); 9553 if (SuggestedNamespaces.empty()) { 9554 SemaRef.Diag(Best->Function->getLocation(), 9555 diag::note_not_found_by_two_phase_lookup) 9556 << R.getLookupName() << 0; 9557 } else if (SuggestedNamespaces.size() == 1) { 9558 SemaRef.Diag(Best->Function->getLocation(), 9559 diag::note_not_found_by_two_phase_lookup) 9560 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9561 } else { 9562 // FIXME: It would be useful to list the associated namespaces here, 9563 // but the diagnostics infrastructure doesn't provide a way to produce 9564 // a localized representation of a list of items. 9565 SemaRef.Diag(Best->Function->getLocation(), 9566 diag::note_not_found_by_two_phase_lookup) 9567 << R.getLookupName() << 2; 9568 } 9569 9570 // Try to recover by calling this function. 9571 return true; 9572 } 9573 9574 R.clear(); 9575 } 9576 9577 return false; 9578} 9579 9580/// Attempt to recover from ill-formed use of a non-dependent operator in a 9581/// template, where the non-dependent operator was declared after the template 9582/// was defined. 9583/// 9584/// Returns true if a viable candidate was found and a diagnostic was issued. 9585static bool 9586DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9587 SourceLocation OpLoc, 9588 llvm::ArrayRef<Expr *> Args) { 9589 DeclarationName OpName = 9590 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9591 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9592 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9593 /*ExplicitTemplateArgs=*/0, Args); 9594} 9595 9596namespace { 9597// Callback to limit the allowed keywords and to only accept typo corrections 9598// that are keywords or whose decls refer to functions (or template functions) 9599// that accept the given number of arguments. 9600class RecoveryCallCCC : public CorrectionCandidateCallback { 9601 public: 9602 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9603 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9604 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9605 WantRemainingKeywords = false; 9606 } 9607 9608 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9609 if (!candidate.getCorrectionDecl()) 9610 return candidate.isKeyword(); 9611 9612 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9613 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9614 FunctionDecl *FD = 0; 9615 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9616 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9617 FD = FTD->getTemplatedDecl(); 9618 if (!HasExplicitTemplateArgs && !FD) { 9619 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9620 // If the Decl is neither a function nor a template function, 9621 // determine if it is a pointer or reference to a function. If so, 9622 // check against the number of arguments expected for the pointee. 9623 QualType ValType = cast<ValueDecl>(ND)->getType(); 9624 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9625 ValType = ValType->getPointeeType(); 9626 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9627 if (FPT->getNumArgs() == NumArgs) 9628 return true; 9629 } 9630 } 9631 if (FD && FD->getNumParams() >= NumArgs && 9632 FD->getMinRequiredArguments() <= NumArgs) 9633 return true; 9634 } 9635 return false; 9636 } 9637 9638 private: 9639 unsigned NumArgs; 9640 bool HasExplicitTemplateArgs; 9641}; 9642 9643// Callback that effectively disabled typo correction 9644class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9645 public: 9646 NoTypoCorrectionCCC() { 9647 WantTypeSpecifiers = false; 9648 WantExpressionKeywords = false; 9649 WantCXXNamedCasts = false; 9650 WantRemainingKeywords = false; 9651 } 9652 9653 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9654 return false; 9655 } 9656}; 9657 9658class BuildRecoveryCallExprRAII { 9659 Sema &SemaRef; 9660public: 9661 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9662 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9663 SemaRef.IsBuildingRecoveryCallExpr = true; 9664 } 9665 9666 ~BuildRecoveryCallExprRAII() { 9667 SemaRef.IsBuildingRecoveryCallExpr = false; 9668 } 9669}; 9670 9671} 9672 9673/// Attempts to recover from a call where no functions were found. 9674/// 9675/// Returns true if new candidates were found. 9676static ExprResult 9677BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9678 UnresolvedLookupExpr *ULE, 9679 SourceLocation LParenLoc, 9680 llvm::MutableArrayRef<Expr *> Args, 9681 SourceLocation RParenLoc, 9682 bool EmptyLookup, bool AllowTypoCorrection) { 9683 // Do not try to recover if it is already building a recovery call. 9684 // This stops infinite loops for template instantiations like 9685 // 9686 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9687 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9688 // 9689 if (SemaRef.IsBuildingRecoveryCallExpr) 9690 return ExprError(); 9691 BuildRecoveryCallExprRAII RCE(SemaRef); 9692 9693 CXXScopeSpec SS; 9694 SS.Adopt(ULE->getQualifierLoc()); 9695 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9696 9697 TemplateArgumentListInfo TABuffer; 9698 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9699 if (ULE->hasExplicitTemplateArgs()) { 9700 ULE->copyTemplateArgumentsInto(TABuffer); 9701 ExplicitTemplateArgs = &TABuffer; 9702 } 9703 9704 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9705 Sema::LookupOrdinaryName); 9706 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9707 NoTypoCorrectionCCC RejectAll; 9708 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9709 (CorrectionCandidateCallback*)&Validator : 9710 (CorrectionCandidateCallback*)&RejectAll; 9711 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9712 ExplicitTemplateArgs, Args) && 9713 (!EmptyLookup || 9714 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9715 ExplicitTemplateArgs, Args))) 9716 return ExprError(); 9717 9718 assert(!R.empty() && "lookup results empty despite recovery"); 9719 9720 // Build an implicit member call if appropriate. Just drop the 9721 // casts and such from the call, we don't really care. 9722 ExprResult NewFn = ExprError(); 9723 if ((*R.begin())->isCXXClassMember()) 9724 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9725 R, ExplicitTemplateArgs); 9726 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9727 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9728 ExplicitTemplateArgs); 9729 else 9730 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9731 9732 if (NewFn.isInvalid()) 9733 return ExprError(); 9734 9735 // This shouldn't cause an infinite loop because we're giving it 9736 // an expression with viable lookup results, which should never 9737 // end up here. 9738 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9739 MultiExprArg(Args.data(), Args.size()), 9740 RParenLoc); 9741} 9742 9743/// \brief Constructs and populates an OverloadedCandidateSet from 9744/// the given function. 9745/// \returns true when an the ExprResult output parameter has been set. 9746bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9747 UnresolvedLookupExpr *ULE, 9748 Expr **Args, unsigned NumArgs, 9749 SourceLocation RParenLoc, 9750 OverloadCandidateSet *CandidateSet, 9751 ExprResult *Result) { 9752#ifndef NDEBUG 9753 if (ULE->requiresADL()) { 9754 // To do ADL, we must have found an unqualified name. 9755 assert(!ULE->getQualifier() && "qualified name with ADL"); 9756 9757 // We don't perform ADL for implicit declarations of builtins. 9758 // Verify that this was correctly set up. 9759 FunctionDecl *F; 9760 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9761 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9762 F->getBuiltinID() && F->isImplicit()) 9763 llvm_unreachable("performing ADL for builtin"); 9764 9765 // We don't perform ADL in C. 9766 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9767 } 9768#endif 9769 9770 UnbridgedCastsSet UnbridgedCasts; 9771 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9772 *Result = ExprError(); 9773 return true; 9774 } 9775 9776 // Add the functions denoted by the callee to the set of candidate 9777 // functions, including those from argument-dependent lookup. 9778 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9779 *CandidateSet); 9780 9781 // If we found nothing, try to recover. 9782 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9783 // out if it fails. 9784 if (CandidateSet->empty()) { 9785 // In Microsoft mode, if we are inside a template class member function then 9786 // create a type dependent CallExpr. The goal is to postpone name lookup 9787 // to instantiation time to be able to search into type dependent base 9788 // classes. 9789 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9790 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9791 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9792 llvm::makeArrayRef(Args, NumArgs), 9793 Context.DependentTy, VK_RValue, 9794 RParenLoc); 9795 CE->setTypeDependent(true); 9796 *Result = Owned(CE); 9797 return true; 9798 } 9799 return false; 9800 } 9801 9802 UnbridgedCasts.restore(); 9803 return false; 9804} 9805 9806/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9807/// the completed call expression. If overload resolution fails, emits 9808/// diagnostics and returns ExprError() 9809static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9810 UnresolvedLookupExpr *ULE, 9811 SourceLocation LParenLoc, 9812 Expr **Args, unsigned NumArgs, 9813 SourceLocation RParenLoc, 9814 Expr *ExecConfig, 9815 OverloadCandidateSet *CandidateSet, 9816 OverloadCandidateSet::iterator *Best, 9817 OverloadingResult OverloadResult, 9818 bool AllowTypoCorrection) { 9819 if (CandidateSet->empty()) 9820 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9821 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9822 RParenLoc, /*EmptyLookup=*/true, 9823 AllowTypoCorrection); 9824 9825 switch (OverloadResult) { 9826 case OR_Success: { 9827 FunctionDecl *FDecl = (*Best)->Function; 9828 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9829 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9830 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9831 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9832 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9833 RParenLoc, ExecConfig); 9834 } 9835 9836 case OR_No_Viable_Function: { 9837 // Try to recover by looking for viable functions which the user might 9838 // have meant to call. 9839 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9840 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9841 RParenLoc, 9842 /*EmptyLookup=*/false, 9843 AllowTypoCorrection); 9844 if (!Recovery.isInvalid()) 9845 return Recovery; 9846 9847 SemaRef.Diag(Fn->getLocStart(), 9848 diag::err_ovl_no_viable_function_in_call) 9849 << ULE->getName() << Fn->getSourceRange(); 9850 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9851 llvm::makeArrayRef(Args, NumArgs)); 9852 break; 9853 } 9854 9855 case OR_Ambiguous: 9856 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9857 << ULE->getName() << Fn->getSourceRange(); 9858 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9859 llvm::makeArrayRef(Args, NumArgs)); 9860 break; 9861 9862 case OR_Deleted: { 9863 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9864 << (*Best)->Function->isDeleted() 9865 << ULE->getName() 9866 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9867 << Fn->getSourceRange(); 9868 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9869 llvm::makeArrayRef(Args, NumArgs)); 9870 9871 // We emitted an error for the unvailable/deleted function call but keep 9872 // the call in the AST. 9873 FunctionDecl *FDecl = (*Best)->Function; 9874 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9875 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9876 RParenLoc, ExecConfig); 9877 } 9878 } 9879 9880 // Overload resolution failed. 9881 return ExprError(); 9882} 9883 9884/// BuildOverloadedCallExpr - Given the call expression that calls Fn 9885/// (which eventually refers to the declaration Func) and the call 9886/// arguments Args/NumArgs, attempt to resolve the function call down 9887/// to a specific function. If overload resolution succeeds, returns 9888/// the call expression produced by overload resolution. 9889/// Otherwise, emits diagnostics and returns ExprError. 9890ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9891 UnresolvedLookupExpr *ULE, 9892 SourceLocation LParenLoc, 9893 Expr **Args, unsigned NumArgs, 9894 SourceLocation RParenLoc, 9895 Expr *ExecConfig, 9896 bool AllowTypoCorrection) { 9897 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9898 ExprResult result; 9899 9900 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9901 &CandidateSet, &result)) 9902 return result; 9903 9904 OverloadCandidateSet::iterator Best; 9905 OverloadingResult OverloadResult = 9906 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9907 9908 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9909 RParenLoc, ExecConfig, &CandidateSet, 9910 &Best, OverloadResult, 9911 AllowTypoCorrection); 9912} 9913 9914static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9915 return Functions.size() > 1 || 9916 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9917} 9918 9919/// \brief Create a unary operation that may resolve to an overloaded 9920/// operator. 9921/// 9922/// \param OpLoc The location of the operator itself (e.g., '*'). 9923/// 9924/// \param OpcIn The UnaryOperator::Opcode that describes this 9925/// operator. 9926/// 9927/// \param Fns The set of non-member functions that will be 9928/// considered by overload resolution. The caller needs to build this 9929/// set based on the context using, e.g., 9930/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9931/// set should not contain any member functions; those will be added 9932/// by CreateOverloadedUnaryOp(). 9933/// 9934/// \param Input The input argument. 9935ExprResult 9936Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9937 const UnresolvedSetImpl &Fns, 9938 Expr *Input) { 9939 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9940 9941 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9942 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9943 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9944 // TODO: provide better source location info. 9945 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9946 9947 if (checkPlaceholderForOverload(*this, Input)) 9948 return ExprError(); 9949 9950 Expr *Args[2] = { Input, 0 }; 9951 unsigned NumArgs = 1; 9952 9953 // For post-increment and post-decrement, add the implicit '0' as 9954 // the second argument, so that we know this is a post-increment or 9955 // post-decrement. 9956 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9957 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9958 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9959 SourceLocation()); 9960 NumArgs = 2; 9961 } 9962 9963 if (Input->isTypeDependent()) { 9964 if (Fns.empty()) 9965 return Owned(new (Context) UnaryOperator(Input, 9966 Opc, 9967 Context.DependentTy, 9968 VK_RValue, OK_Ordinary, 9969 OpLoc)); 9970 9971 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9972 UnresolvedLookupExpr *Fn 9973 = UnresolvedLookupExpr::Create(Context, NamingClass, 9974 NestedNameSpecifierLoc(), OpNameInfo, 9975 /*ADL*/ true, IsOverloaded(Fns), 9976 Fns.begin(), Fns.end()); 9977 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9978 llvm::makeArrayRef(Args, NumArgs), 9979 Context.DependentTy, 9980 VK_RValue, 9981 OpLoc, false)); 9982 } 9983 9984 // Build an empty overload set. 9985 OverloadCandidateSet CandidateSet(OpLoc); 9986 9987 // Add the candidates from the given function set. 9988 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9989 false); 9990 9991 // Add operator candidates that are member functions. 9992 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9993 9994 // Add candidates from ADL. 9995 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9996 OpLoc, llvm::makeArrayRef(Args, NumArgs), 9997 /*ExplicitTemplateArgs*/ 0, 9998 CandidateSet); 9999 10000 // Add builtin operator candidates. 10001 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10002 10003 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10004 10005 // Perform overload resolution. 10006 OverloadCandidateSet::iterator Best; 10007 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10008 case OR_Success: { 10009 // We found a built-in operator or an overloaded operator. 10010 FunctionDecl *FnDecl = Best->Function; 10011 10012 if (FnDecl) { 10013 // We matched an overloaded operator. Build a call to that 10014 // operator. 10015 10016 MarkFunctionReferenced(OpLoc, FnDecl); 10017 10018 // Convert the arguments. 10019 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10020 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10021 10022 ExprResult InputRes = 10023 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10024 Best->FoundDecl, Method); 10025 if (InputRes.isInvalid()) 10026 return ExprError(); 10027 Input = InputRes.take(); 10028 } else { 10029 // Convert the arguments. 10030 ExprResult InputInit 10031 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10032 Context, 10033 FnDecl->getParamDecl(0)), 10034 SourceLocation(), 10035 Input); 10036 if (InputInit.isInvalid()) 10037 return ExprError(); 10038 Input = InputInit.take(); 10039 } 10040 10041 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10042 10043 // Determine the result type. 10044 QualType ResultTy = FnDecl->getResultType(); 10045 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10046 ResultTy = ResultTy.getNonLValueExprType(Context); 10047 10048 // Build the actual expression node. 10049 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10050 HadMultipleCandidates, OpLoc); 10051 if (FnExpr.isInvalid()) 10052 return ExprError(); 10053 10054 Args[0] = Input; 10055 CallExpr *TheCall = 10056 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10057 llvm::makeArrayRef(Args, NumArgs), 10058 ResultTy, VK, OpLoc, false); 10059 10060 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10061 FnDecl)) 10062 return ExprError(); 10063 10064 return MaybeBindToTemporary(TheCall); 10065 } else { 10066 // We matched a built-in operator. Convert the arguments, then 10067 // break out so that we will build the appropriate built-in 10068 // operator node. 10069 ExprResult InputRes = 10070 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10071 Best->Conversions[0], AA_Passing); 10072 if (InputRes.isInvalid()) 10073 return ExprError(); 10074 Input = InputRes.take(); 10075 break; 10076 } 10077 } 10078 10079 case OR_No_Viable_Function: 10080 // This is an erroneous use of an operator which can be overloaded by 10081 // a non-member function. Check for non-member operators which were 10082 // defined too late to be candidates. 10083 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10084 llvm::makeArrayRef(Args, NumArgs))) 10085 // FIXME: Recover by calling the found function. 10086 return ExprError(); 10087 10088 // No viable function; fall through to handling this as a 10089 // built-in operator, which will produce an error message for us. 10090 break; 10091 10092 case OR_Ambiguous: 10093 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10094 << UnaryOperator::getOpcodeStr(Opc) 10095 << Input->getType() 10096 << Input->getSourceRange(); 10097 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10098 llvm::makeArrayRef(Args, NumArgs), 10099 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10100 return ExprError(); 10101 10102 case OR_Deleted: 10103 Diag(OpLoc, diag::err_ovl_deleted_oper) 10104 << Best->Function->isDeleted() 10105 << UnaryOperator::getOpcodeStr(Opc) 10106 << getDeletedOrUnavailableSuffix(Best->Function) 10107 << Input->getSourceRange(); 10108 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10109 llvm::makeArrayRef(Args, NumArgs), 10110 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10111 return ExprError(); 10112 } 10113 10114 // Either we found no viable overloaded operator or we matched a 10115 // built-in operator. In either case, fall through to trying to 10116 // build a built-in operation. 10117 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10118} 10119 10120/// \brief Create a binary operation that may resolve to an overloaded 10121/// operator. 10122/// 10123/// \param OpLoc The location of the operator itself (e.g., '+'). 10124/// 10125/// \param OpcIn The BinaryOperator::Opcode that describes this 10126/// operator. 10127/// 10128/// \param Fns The set of non-member functions that will be 10129/// considered by overload resolution. The caller needs to build this 10130/// set based on the context using, e.g., 10131/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10132/// set should not contain any member functions; those will be added 10133/// by CreateOverloadedBinOp(). 10134/// 10135/// \param LHS Left-hand argument. 10136/// \param RHS Right-hand argument. 10137ExprResult 10138Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10139 unsigned OpcIn, 10140 const UnresolvedSetImpl &Fns, 10141 Expr *LHS, Expr *RHS) { 10142 Expr *Args[2] = { LHS, RHS }; 10143 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10144 10145 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10146 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10147 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10148 10149 // If either side is type-dependent, create an appropriate dependent 10150 // expression. 10151 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10152 if (Fns.empty()) { 10153 // If there are no functions to store, just build a dependent 10154 // BinaryOperator or CompoundAssignment. 10155 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10156 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10157 Context.DependentTy, 10158 VK_RValue, OK_Ordinary, 10159 OpLoc, 10160 FPFeatures.fp_contract)); 10161 10162 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10163 Context.DependentTy, 10164 VK_LValue, 10165 OK_Ordinary, 10166 Context.DependentTy, 10167 Context.DependentTy, 10168 OpLoc, 10169 FPFeatures.fp_contract)); 10170 } 10171 10172 // FIXME: save results of ADL from here? 10173 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10174 // TODO: provide better source location info in DNLoc component. 10175 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10176 UnresolvedLookupExpr *Fn 10177 = UnresolvedLookupExpr::Create(Context, NamingClass, 10178 NestedNameSpecifierLoc(), OpNameInfo, 10179 /*ADL*/ true, IsOverloaded(Fns), 10180 Fns.begin(), Fns.end()); 10181 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10182 Context.DependentTy, VK_RValue, 10183 OpLoc, FPFeatures.fp_contract)); 10184 } 10185 10186 // Always do placeholder-like conversions on the RHS. 10187 if (checkPlaceholderForOverload(*this, Args[1])) 10188 return ExprError(); 10189 10190 // Do placeholder-like conversion on the LHS; note that we should 10191 // not get here with a PseudoObject LHS. 10192 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10193 if (checkPlaceholderForOverload(*this, Args[0])) 10194 return ExprError(); 10195 10196 // If this is the assignment operator, we only perform overload resolution 10197 // if the left-hand side is a class or enumeration type. This is actually 10198 // a hack. The standard requires that we do overload resolution between the 10199 // various built-in candidates, but as DR507 points out, this can lead to 10200 // problems. So we do it this way, which pretty much follows what GCC does. 10201 // Note that we go the traditional code path for compound assignment forms. 10202 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10203 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10204 10205 // If this is the .* operator, which is not overloadable, just 10206 // create a built-in binary operator. 10207 if (Opc == BO_PtrMemD) 10208 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10209 10210 // Build an empty overload set. 10211 OverloadCandidateSet CandidateSet(OpLoc); 10212 10213 // Add the candidates from the given function set. 10214 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10215 10216 // Add operator candidates that are member functions. 10217 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10218 10219 // Add candidates from ADL. 10220 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10221 OpLoc, Args, 10222 /*ExplicitTemplateArgs*/ 0, 10223 CandidateSet); 10224 10225 // Add builtin operator candidates. 10226 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10227 10228 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10229 10230 // Perform overload resolution. 10231 OverloadCandidateSet::iterator Best; 10232 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10233 case OR_Success: { 10234 // We found a built-in operator or an overloaded operator. 10235 FunctionDecl *FnDecl = Best->Function; 10236 10237 if (FnDecl) { 10238 // We matched an overloaded operator. Build a call to that 10239 // operator. 10240 10241 MarkFunctionReferenced(OpLoc, FnDecl); 10242 10243 // Convert the arguments. 10244 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10245 // Best->Access is only meaningful for class members. 10246 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10247 10248 ExprResult Arg1 = 10249 PerformCopyInitialization( 10250 InitializedEntity::InitializeParameter(Context, 10251 FnDecl->getParamDecl(0)), 10252 SourceLocation(), Owned(Args[1])); 10253 if (Arg1.isInvalid()) 10254 return ExprError(); 10255 10256 ExprResult Arg0 = 10257 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10258 Best->FoundDecl, Method); 10259 if (Arg0.isInvalid()) 10260 return ExprError(); 10261 Args[0] = Arg0.takeAs<Expr>(); 10262 Args[1] = RHS = Arg1.takeAs<Expr>(); 10263 } else { 10264 // Convert the arguments. 10265 ExprResult Arg0 = PerformCopyInitialization( 10266 InitializedEntity::InitializeParameter(Context, 10267 FnDecl->getParamDecl(0)), 10268 SourceLocation(), Owned(Args[0])); 10269 if (Arg0.isInvalid()) 10270 return ExprError(); 10271 10272 ExprResult Arg1 = 10273 PerformCopyInitialization( 10274 InitializedEntity::InitializeParameter(Context, 10275 FnDecl->getParamDecl(1)), 10276 SourceLocation(), Owned(Args[1])); 10277 if (Arg1.isInvalid()) 10278 return ExprError(); 10279 Args[0] = LHS = Arg0.takeAs<Expr>(); 10280 Args[1] = RHS = Arg1.takeAs<Expr>(); 10281 } 10282 10283 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10284 10285 // Determine the result type. 10286 QualType ResultTy = FnDecl->getResultType(); 10287 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10288 ResultTy = ResultTy.getNonLValueExprType(Context); 10289 10290 // Build the actual expression node. 10291 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10292 HadMultipleCandidates, OpLoc); 10293 if (FnExpr.isInvalid()) 10294 return ExprError(); 10295 10296 CXXOperatorCallExpr *TheCall = 10297 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10298 Args, ResultTy, VK, OpLoc, 10299 FPFeatures.fp_contract); 10300 10301 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10302 FnDecl)) 10303 return ExprError(); 10304 10305 return MaybeBindToTemporary(TheCall); 10306 } else { 10307 // We matched a built-in operator. Convert the arguments, then 10308 // break out so that we will build the appropriate built-in 10309 // operator node. 10310 ExprResult ArgsRes0 = 10311 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10312 Best->Conversions[0], AA_Passing); 10313 if (ArgsRes0.isInvalid()) 10314 return ExprError(); 10315 Args[0] = ArgsRes0.take(); 10316 10317 ExprResult ArgsRes1 = 10318 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10319 Best->Conversions[1], AA_Passing); 10320 if (ArgsRes1.isInvalid()) 10321 return ExprError(); 10322 Args[1] = ArgsRes1.take(); 10323 break; 10324 } 10325 } 10326 10327 case OR_No_Viable_Function: { 10328 // C++ [over.match.oper]p9: 10329 // If the operator is the operator , [...] and there are no 10330 // viable functions, then the operator is assumed to be the 10331 // built-in operator and interpreted according to clause 5. 10332 if (Opc == BO_Comma) 10333 break; 10334 10335 // For class as left operand for assignment or compound assigment 10336 // operator do not fall through to handling in built-in, but report that 10337 // no overloaded assignment operator found 10338 ExprResult Result = ExprError(); 10339 if (Args[0]->getType()->isRecordType() && 10340 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10341 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10342 << BinaryOperator::getOpcodeStr(Opc) 10343 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10344 } else { 10345 // This is an erroneous use of an operator which can be overloaded by 10346 // a non-member function. Check for non-member operators which were 10347 // defined too late to be candidates. 10348 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10349 // FIXME: Recover by calling the found function. 10350 return ExprError(); 10351 10352 // No viable function; try to create a built-in operation, which will 10353 // produce an error. Then, show the non-viable candidates. 10354 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10355 } 10356 assert(Result.isInvalid() && 10357 "C++ binary operator overloading is missing candidates!"); 10358 if (Result.isInvalid()) 10359 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10360 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10361 return Result; 10362 } 10363 10364 case OR_Ambiguous: 10365 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10366 << BinaryOperator::getOpcodeStr(Opc) 10367 << Args[0]->getType() << Args[1]->getType() 10368 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10369 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10370 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10371 return ExprError(); 10372 10373 case OR_Deleted: 10374 if (isImplicitlyDeleted(Best->Function)) { 10375 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10376 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10377 << getSpecialMember(Method) 10378 << BinaryOperator::getOpcodeStr(Opc) 10379 << getDeletedOrUnavailableSuffix(Best->Function); 10380 10381 if (getSpecialMember(Method) != CXXInvalid) { 10382 // The user probably meant to call this special member. Just 10383 // explain why it's deleted. 10384 NoteDeletedFunction(Method); 10385 return ExprError(); 10386 } 10387 } else { 10388 Diag(OpLoc, diag::err_ovl_deleted_oper) 10389 << Best->Function->isDeleted() 10390 << BinaryOperator::getOpcodeStr(Opc) 10391 << getDeletedOrUnavailableSuffix(Best->Function) 10392 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10393 } 10394 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10395 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10396 return ExprError(); 10397 } 10398 10399 // We matched a built-in operator; build it. 10400 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10401} 10402 10403ExprResult 10404Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10405 SourceLocation RLoc, 10406 Expr *Base, Expr *Idx) { 10407 Expr *Args[2] = { Base, Idx }; 10408 DeclarationName OpName = 10409 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10410 10411 // If either side is type-dependent, create an appropriate dependent 10412 // expression. 10413 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10414 10415 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10416 // CHECKME: no 'operator' keyword? 10417 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10418 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10419 UnresolvedLookupExpr *Fn 10420 = UnresolvedLookupExpr::Create(Context, NamingClass, 10421 NestedNameSpecifierLoc(), OpNameInfo, 10422 /*ADL*/ true, /*Overloaded*/ false, 10423 UnresolvedSetIterator(), 10424 UnresolvedSetIterator()); 10425 // Can't add any actual overloads yet 10426 10427 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10428 Args, 10429 Context.DependentTy, 10430 VK_RValue, 10431 RLoc, false)); 10432 } 10433 10434 // Handle placeholders on both operands. 10435 if (checkPlaceholderForOverload(*this, Args[0])) 10436 return ExprError(); 10437 if (checkPlaceholderForOverload(*this, Args[1])) 10438 return ExprError(); 10439 10440 // Build an empty overload set. 10441 OverloadCandidateSet CandidateSet(LLoc); 10442 10443 // Subscript can only be overloaded as a member function. 10444 10445 // Add operator candidates that are member functions. 10446 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10447 10448 // Add builtin operator candidates. 10449 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10450 10451 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10452 10453 // Perform overload resolution. 10454 OverloadCandidateSet::iterator Best; 10455 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10456 case OR_Success: { 10457 // We found a built-in operator or an overloaded operator. 10458 FunctionDecl *FnDecl = Best->Function; 10459 10460 if (FnDecl) { 10461 // We matched an overloaded operator. Build a call to that 10462 // operator. 10463 10464 MarkFunctionReferenced(LLoc, FnDecl); 10465 10466 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10467 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10468 10469 // Convert the arguments. 10470 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10471 ExprResult Arg0 = 10472 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10473 Best->FoundDecl, Method); 10474 if (Arg0.isInvalid()) 10475 return ExprError(); 10476 Args[0] = Arg0.take(); 10477 10478 // Convert the arguments. 10479 ExprResult InputInit 10480 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10481 Context, 10482 FnDecl->getParamDecl(0)), 10483 SourceLocation(), 10484 Owned(Args[1])); 10485 if (InputInit.isInvalid()) 10486 return ExprError(); 10487 10488 Args[1] = InputInit.takeAs<Expr>(); 10489 10490 // Determine the result type 10491 QualType ResultTy = FnDecl->getResultType(); 10492 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10493 ResultTy = ResultTy.getNonLValueExprType(Context); 10494 10495 // Build the actual expression node. 10496 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10497 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10498 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10499 HadMultipleCandidates, 10500 OpLocInfo.getLoc(), 10501 OpLocInfo.getInfo()); 10502 if (FnExpr.isInvalid()) 10503 return ExprError(); 10504 10505 CXXOperatorCallExpr *TheCall = 10506 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10507 FnExpr.take(), Args, 10508 ResultTy, VK, RLoc, 10509 false); 10510 10511 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10512 FnDecl)) 10513 return ExprError(); 10514 10515 return MaybeBindToTemporary(TheCall); 10516 } else { 10517 // We matched a built-in operator. Convert the arguments, then 10518 // break out so that we will build the appropriate built-in 10519 // operator node. 10520 ExprResult ArgsRes0 = 10521 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10522 Best->Conversions[0], AA_Passing); 10523 if (ArgsRes0.isInvalid()) 10524 return ExprError(); 10525 Args[0] = ArgsRes0.take(); 10526 10527 ExprResult ArgsRes1 = 10528 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10529 Best->Conversions[1], AA_Passing); 10530 if (ArgsRes1.isInvalid()) 10531 return ExprError(); 10532 Args[1] = ArgsRes1.take(); 10533 10534 break; 10535 } 10536 } 10537 10538 case OR_No_Viable_Function: { 10539 if (CandidateSet.empty()) 10540 Diag(LLoc, diag::err_ovl_no_oper) 10541 << Args[0]->getType() << /*subscript*/ 0 10542 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10543 else 10544 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10545 << Args[0]->getType() 10546 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10547 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10548 "[]", LLoc); 10549 return ExprError(); 10550 } 10551 10552 case OR_Ambiguous: 10553 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10554 << "[]" 10555 << Args[0]->getType() << Args[1]->getType() 10556 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10557 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10558 "[]", LLoc); 10559 return ExprError(); 10560 10561 case OR_Deleted: 10562 Diag(LLoc, diag::err_ovl_deleted_oper) 10563 << Best->Function->isDeleted() << "[]" 10564 << getDeletedOrUnavailableSuffix(Best->Function) 10565 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10566 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10567 "[]", LLoc); 10568 return ExprError(); 10569 } 10570 10571 // We matched a built-in operator; build it. 10572 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10573} 10574 10575/// BuildCallToMemberFunction - Build a call to a member 10576/// function. MemExpr is the expression that refers to the member 10577/// function (and includes the object parameter), Args/NumArgs are the 10578/// arguments to the function call (not including the object 10579/// parameter). The caller needs to validate that the member 10580/// expression refers to a non-static member function or an overloaded 10581/// member function. 10582ExprResult 10583Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10584 SourceLocation LParenLoc, Expr **Args, 10585 unsigned NumArgs, SourceLocation RParenLoc) { 10586 assert(MemExprE->getType() == Context.BoundMemberTy || 10587 MemExprE->getType() == Context.OverloadTy); 10588 10589 // Dig out the member expression. This holds both the object 10590 // argument and the member function we're referring to. 10591 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10592 10593 // Determine whether this is a call to a pointer-to-member function. 10594 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10595 assert(op->getType() == Context.BoundMemberTy); 10596 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10597 10598 QualType fnType = 10599 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10600 10601 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10602 QualType resultType = proto->getCallResultType(Context); 10603 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10604 10605 // Check that the object type isn't more qualified than the 10606 // member function we're calling. 10607 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10608 10609 QualType objectType = op->getLHS()->getType(); 10610 if (op->getOpcode() == BO_PtrMemI) 10611 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10612 Qualifiers objectQuals = objectType.getQualifiers(); 10613 10614 Qualifiers difference = objectQuals - funcQuals; 10615 difference.removeObjCGCAttr(); 10616 difference.removeAddressSpace(); 10617 if (difference) { 10618 std::string qualsString = difference.getAsString(); 10619 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10620 << fnType.getUnqualifiedType() 10621 << qualsString 10622 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10623 } 10624 10625 CXXMemberCallExpr *call 10626 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10627 llvm::makeArrayRef(Args, NumArgs), 10628 resultType, valueKind, RParenLoc); 10629 10630 if (CheckCallReturnType(proto->getResultType(), 10631 op->getRHS()->getLocStart(), 10632 call, 0)) 10633 return ExprError(); 10634 10635 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10636 return ExprError(); 10637 10638 return MaybeBindToTemporary(call); 10639 } 10640 10641 UnbridgedCastsSet UnbridgedCasts; 10642 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10643 return ExprError(); 10644 10645 MemberExpr *MemExpr; 10646 CXXMethodDecl *Method = 0; 10647 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10648 NestedNameSpecifier *Qualifier = 0; 10649 if (isa<MemberExpr>(NakedMemExpr)) { 10650 MemExpr = cast<MemberExpr>(NakedMemExpr); 10651 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10652 FoundDecl = MemExpr->getFoundDecl(); 10653 Qualifier = MemExpr->getQualifier(); 10654 UnbridgedCasts.restore(); 10655 } else { 10656 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10657 Qualifier = UnresExpr->getQualifier(); 10658 10659 QualType ObjectType = UnresExpr->getBaseType(); 10660 Expr::Classification ObjectClassification 10661 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10662 : UnresExpr->getBase()->Classify(Context); 10663 10664 // Add overload candidates 10665 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10666 10667 // FIXME: avoid copy. 10668 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10669 if (UnresExpr->hasExplicitTemplateArgs()) { 10670 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10671 TemplateArgs = &TemplateArgsBuffer; 10672 } 10673 10674 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10675 E = UnresExpr->decls_end(); I != E; ++I) { 10676 10677 NamedDecl *Func = *I; 10678 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10679 if (isa<UsingShadowDecl>(Func)) 10680 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10681 10682 10683 // Microsoft supports direct constructor calls. 10684 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10685 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10686 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10687 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10688 // If explicit template arguments were provided, we can't call a 10689 // non-template member function. 10690 if (TemplateArgs) 10691 continue; 10692 10693 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10694 ObjectClassification, 10695 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10696 /*SuppressUserConversions=*/false); 10697 } else { 10698 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10699 I.getPair(), ActingDC, TemplateArgs, 10700 ObjectType, ObjectClassification, 10701 llvm::makeArrayRef(Args, NumArgs), 10702 CandidateSet, 10703 /*SuppressUsedConversions=*/false); 10704 } 10705 } 10706 10707 DeclarationName DeclName = UnresExpr->getMemberName(); 10708 10709 UnbridgedCasts.restore(); 10710 10711 OverloadCandidateSet::iterator Best; 10712 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10713 Best)) { 10714 case OR_Success: 10715 Method = cast<CXXMethodDecl>(Best->Function); 10716 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10717 FoundDecl = Best->FoundDecl; 10718 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10719 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10720 break; 10721 10722 case OR_No_Viable_Function: 10723 Diag(UnresExpr->getMemberLoc(), 10724 diag::err_ovl_no_viable_member_function_in_call) 10725 << DeclName << MemExprE->getSourceRange(); 10726 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10727 llvm::makeArrayRef(Args, NumArgs)); 10728 // FIXME: Leaking incoming expressions! 10729 return ExprError(); 10730 10731 case OR_Ambiguous: 10732 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10733 << DeclName << MemExprE->getSourceRange(); 10734 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10735 llvm::makeArrayRef(Args, NumArgs)); 10736 // FIXME: Leaking incoming expressions! 10737 return ExprError(); 10738 10739 case OR_Deleted: 10740 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10741 << Best->Function->isDeleted() 10742 << DeclName 10743 << getDeletedOrUnavailableSuffix(Best->Function) 10744 << MemExprE->getSourceRange(); 10745 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10746 llvm::makeArrayRef(Args, NumArgs)); 10747 // FIXME: Leaking incoming expressions! 10748 return ExprError(); 10749 } 10750 10751 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10752 10753 // If overload resolution picked a static member, build a 10754 // non-member call based on that function. 10755 if (Method->isStatic()) { 10756 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10757 Args, NumArgs, RParenLoc); 10758 } 10759 10760 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10761 } 10762 10763 QualType ResultType = Method->getResultType(); 10764 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10765 ResultType = ResultType.getNonLValueExprType(Context); 10766 10767 assert(Method && "Member call to something that isn't a method?"); 10768 CXXMemberCallExpr *TheCall = 10769 new (Context) CXXMemberCallExpr(Context, MemExprE, 10770 llvm::makeArrayRef(Args, NumArgs), 10771 ResultType, VK, RParenLoc); 10772 10773 // Check for a valid return type. 10774 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10775 TheCall, Method)) 10776 return ExprError(); 10777 10778 // Convert the object argument (for a non-static member function call). 10779 // We only need to do this if there was actually an overload; otherwise 10780 // it was done at lookup. 10781 if (!Method->isStatic()) { 10782 ExprResult ObjectArg = 10783 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10784 FoundDecl, Method); 10785 if (ObjectArg.isInvalid()) 10786 return ExprError(); 10787 MemExpr->setBase(ObjectArg.take()); 10788 } 10789 10790 // Convert the rest of the arguments 10791 const FunctionProtoType *Proto = 10792 Method->getType()->getAs<FunctionProtoType>(); 10793 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10794 RParenLoc)) 10795 return ExprError(); 10796 10797 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10798 10799 if (CheckFunctionCall(Method, TheCall, Proto)) 10800 return ExprError(); 10801 10802 if ((isa<CXXConstructorDecl>(CurContext) || 10803 isa<CXXDestructorDecl>(CurContext)) && 10804 TheCall->getMethodDecl()->isPure()) { 10805 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10806 10807 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10808 Diag(MemExpr->getLocStart(), 10809 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10810 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10811 << MD->getParent()->getDeclName(); 10812 10813 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10814 } 10815 } 10816 return MaybeBindToTemporary(TheCall); 10817} 10818 10819/// BuildCallToObjectOfClassType - Build a call to an object of class 10820/// type (C++ [over.call.object]), which can end up invoking an 10821/// overloaded function call operator (@c operator()) or performing a 10822/// user-defined conversion on the object argument. 10823ExprResult 10824Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10825 SourceLocation LParenLoc, 10826 Expr **Args, unsigned NumArgs, 10827 SourceLocation RParenLoc) { 10828 if (checkPlaceholderForOverload(*this, Obj)) 10829 return ExprError(); 10830 ExprResult Object = Owned(Obj); 10831 10832 UnbridgedCastsSet UnbridgedCasts; 10833 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10834 return ExprError(); 10835 10836 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10837 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10838 10839 // C++ [over.call.object]p1: 10840 // If the primary-expression E in the function call syntax 10841 // evaluates to a class object of type "cv T", then the set of 10842 // candidate functions includes at least the function call 10843 // operators of T. The function call operators of T are obtained by 10844 // ordinary lookup of the name operator() in the context of 10845 // (E).operator(). 10846 OverloadCandidateSet CandidateSet(LParenLoc); 10847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10848 10849 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10850 diag::err_incomplete_object_call, Object.get())) 10851 return true; 10852 10853 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10854 LookupQualifiedName(R, Record->getDecl()); 10855 R.suppressDiagnostics(); 10856 10857 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10858 Oper != OperEnd; ++Oper) { 10859 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10860 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10861 /*SuppressUserConversions=*/ false); 10862 } 10863 10864 // C++ [over.call.object]p2: 10865 // In addition, for each (non-explicit in C++0x) conversion function 10866 // declared in T of the form 10867 // 10868 // operator conversion-type-id () cv-qualifier; 10869 // 10870 // where cv-qualifier is the same cv-qualification as, or a 10871 // greater cv-qualification than, cv, and where conversion-type-id 10872 // denotes the type "pointer to function of (P1,...,Pn) returning 10873 // R", or the type "reference to pointer to function of 10874 // (P1,...,Pn) returning R", or the type "reference to function 10875 // of (P1,...,Pn) returning R", a surrogate call function [...] 10876 // is also considered as a candidate function. Similarly, 10877 // surrogate call functions are added to the set of candidate 10878 // functions for each conversion function declared in an 10879 // accessible base class provided the function is not hidden 10880 // within T by another intervening declaration. 10881 const UnresolvedSetImpl *Conversions 10882 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10883 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10884 E = Conversions->end(); I != E; ++I) { 10885 NamedDecl *D = *I; 10886 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10887 if (isa<UsingShadowDecl>(D)) 10888 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10889 10890 // Skip over templated conversion functions; they aren't 10891 // surrogates. 10892 if (isa<FunctionTemplateDecl>(D)) 10893 continue; 10894 10895 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10896 if (!Conv->isExplicit()) { 10897 // Strip the reference type (if any) and then the pointer type (if 10898 // any) to get down to what might be a function type. 10899 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10900 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10901 ConvType = ConvPtrType->getPointeeType(); 10902 10903 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10904 { 10905 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10906 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10907 CandidateSet); 10908 } 10909 } 10910 } 10911 10912 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10913 10914 // Perform overload resolution. 10915 OverloadCandidateSet::iterator Best; 10916 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10917 Best)) { 10918 case OR_Success: 10919 // Overload resolution succeeded; we'll build the appropriate call 10920 // below. 10921 break; 10922 10923 case OR_No_Viable_Function: 10924 if (CandidateSet.empty()) 10925 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10926 << Object.get()->getType() << /*call*/ 1 10927 << Object.get()->getSourceRange(); 10928 else 10929 Diag(Object.get()->getLocStart(), 10930 diag::err_ovl_no_viable_object_call) 10931 << Object.get()->getType() << Object.get()->getSourceRange(); 10932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10933 llvm::makeArrayRef(Args, NumArgs)); 10934 break; 10935 10936 case OR_Ambiguous: 10937 Diag(Object.get()->getLocStart(), 10938 diag::err_ovl_ambiguous_object_call) 10939 << Object.get()->getType() << Object.get()->getSourceRange(); 10940 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10941 llvm::makeArrayRef(Args, NumArgs)); 10942 break; 10943 10944 case OR_Deleted: 10945 Diag(Object.get()->getLocStart(), 10946 diag::err_ovl_deleted_object_call) 10947 << Best->Function->isDeleted() 10948 << Object.get()->getType() 10949 << getDeletedOrUnavailableSuffix(Best->Function) 10950 << Object.get()->getSourceRange(); 10951 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10952 llvm::makeArrayRef(Args, NumArgs)); 10953 break; 10954 } 10955 10956 if (Best == CandidateSet.end()) 10957 return true; 10958 10959 UnbridgedCasts.restore(); 10960 10961 if (Best->Function == 0) { 10962 // Since there is no function declaration, this is one of the 10963 // surrogate candidates. Dig out the conversion function. 10964 CXXConversionDecl *Conv 10965 = cast<CXXConversionDecl>( 10966 Best->Conversions[0].UserDefined.ConversionFunction); 10967 10968 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10969 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10970 10971 // We selected one of the surrogate functions that converts the 10972 // object parameter to a function pointer. Perform the conversion 10973 // on the object argument, then let ActOnCallExpr finish the job. 10974 10975 // Create an implicit member expr to refer to the conversion operator. 10976 // and then call it. 10977 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10978 Conv, HadMultipleCandidates); 10979 if (Call.isInvalid()) 10980 return ExprError(); 10981 // Record usage of conversion in an implicit cast. 10982 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10983 CK_UserDefinedConversion, 10984 Call.get(), 0, VK_RValue)); 10985 10986 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10987 RParenLoc); 10988 } 10989 10990 MarkFunctionReferenced(LParenLoc, Best->Function); 10991 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10992 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10993 10994 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10995 // that calls this method, using Object for the implicit object 10996 // parameter and passing along the remaining arguments. 10997 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10998 10999 // An error diagnostic has already been printed when parsing the declaration. 11000 if (Method->isInvalidDecl()) 11001 return ExprError(); 11002 11003 const FunctionProtoType *Proto = 11004 Method->getType()->getAs<FunctionProtoType>(); 11005 11006 unsigned NumArgsInProto = Proto->getNumArgs(); 11007 unsigned NumArgsToCheck = NumArgs; 11008 11009 // Build the full argument list for the method call (the 11010 // implicit object parameter is placed at the beginning of the 11011 // list). 11012 Expr **MethodArgs; 11013 if (NumArgs < NumArgsInProto) { 11014 NumArgsToCheck = NumArgsInProto; 11015 MethodArgs = new Expr*[NumArgsInProto + 1]; 11016 } else { 11017 MethodArgs = new Expr*[NumArgs + 1]; 11018 } 11019 MethodArgs[0] = Object.get(); 11020 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11021 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11022 11023 DeclarationNameInfo OpLocInfo( 11024 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11025 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11026 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 11027 HadMultipleCandidates, 11028 OpLocInfo.getLoc(), 11029 OpLocInfo.getInfo()); 11030 if (NewFn.isInvalid()) 11031 return true; 11032 11033 // Once we've built TheCall, all of the expressions are properly 11034 // owned. 11035 QualType ResultTy = Method->getResultType(); 11036 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11037 ResultTy = ResultTy.getNonLValueExprType(Context); 11038 11039 CXXOperatorCallExpr *TheCall = 11040 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11041 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11042 ResultTy, VK, RParenLoc, false); 11043 delete [] MethodArgs; 11044 11045 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11046 Method)) 11047 return true; 11048 11049 // We may have default arguments. If so, we need to allocate more 11050 // slots in the call for them. 11051 if (NumArgs < NumArgsInProto) 11052 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11053 else if (NumArgs > NumArgsInProto) 11054 NumArgsToCheck = NumArgsInProto; 11055 11056 bool IsError = false; 11057 11058 // Initialize the implicit object parameter. 11059 ExprResult ObjRes = 11060 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11061 Best->FoundDecl, Method); 11062 if (ObjRes.isInvalid()) 11063 IsError = true; 11064 else 11065 Object = ObjRes; 11066 TheCall->setArg(0, Object.take()); 11067 11068 // Check the argument types. 11069 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11070 Expr *Arg; 11071 if (i < NumArgs) { 11072 Arg = Args[i]; 11073 11074 // Pass the argument. 11075 11076 ExprResult InputInit 11077 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11078 Context, 11079 Method->getParamDecl(i)), 11080 SourceLocation(), Arg); 11081 11082 IsError |= InputInit.isInvalid(); 11083 Arg = InputInit.takeAs<Expr>(); 11084 } else { 11085 ExprResult DefArg 11086 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11087 if (DefArg.isInvalid()) { 11088 IsError = true; 11089 break; 11090 } 11091 11092 Arg = DefArg.takeAs<Expr>(); 11093 } 11094 11095 TheCall->setArg(i + 1, Arg); 11096 } 11097 11098 // If this is a variadic call, handle args passed through "...". 11099 if (Proto->isVariadic()) { 11100 // Promote the arguments (C99 6.5.2.2p7). 11101 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11102 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11103 IsError |= Arg.isInvalid(); 11104 TheCall->setArg(i + 1, Arg.take()); 11105 } 11106 } 11107 11108 if (IsError) return true; 11109 11110 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11111 11112 if (CheckFunctionCall(Method, TheCall, Proto)) 11113 return true; 11114 11115 return MaybeBindToTemporary(TheCall); 11116} 11117 11118/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11119/// (if one exists), where @c Base is an expression of class type and 11120/// @c Member is the name of the member we're trying to find. 11121ExprResult 11122Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11123 assert(Base->getType()->isRecordType() && 11124 "left-hand side must have class type"); 11125 11126 if (checkPlaceholderForOverload(*this, Base)) 11127 return ExprError(); 11128 11129 SourceLocation Loc = Base->getExprLoc(); 11130 11131 // C++ [over.ref]p1: 11132 // 11133 // [...] An expression x->m is interpreted as (x.operator->())->m 11134 // for a class object x of type T if T::operator->() exists and if 11135 // the operator is selected as the best match function by the 11136 // overload resolution mechanism (13.3). 11137 DeclarationName OpName = 11138 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11139 OverloadCandidateSet CandidateSet(Loc); 11140 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11141 11142 if (RequireCompleteType(Loc, Base->getType(), 11143 diag::err_typecheck_incomplete_tag, Base)) 11144 return ExprError(); 11145 11146 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11147 LookupQualifiedName(R, BaseRecord->getDecl()); 11148 R.suppressDiagnostics(); 11149 11150 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11151 Oper != OperEnd; ++Oper) { 11152 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11153 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11154 } 11155 11156 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11157 11158 // Perform overload resolution. 11159 OverloadCandidateSet::iterator Best; 11160 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11161 case OR_Success: 11162 // Overload resolution succeeded; we'll build the call below. 11163 break; 11164 11165 case OR_No_Viable_Function: 11166 if (CandidateSet.empty()) 11167 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11168 << Base->getType() << Base->getSourceRange(); 11169 else 11170 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11171 << "operator->" << Base->getSourceRange(); 11172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11173 return ExprError(); 11174 11175 case OR_Ambiguous: 11176 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11177 << "->" << Base->getType() << Base->getSourceRange(); 11178 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11179 return ExprError(); 11180 11181 case OR_Deleted: 11182 Diag(OpLoc, diag::err_ovl_deleted_oper) 11183 << Best->Function->isDeleted() 11184 << "->" 11185 << getDeletedOrUnavailableSuffix(Best->Function) 11186 << Base->getSourceRange(); 11187 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11188 return ExprError(); 11189 } 11190 11191 MarkFunctionReferenced(OpLoc, Best->Function); 11192 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11193 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11194 11195 // Convert the object parameter. 11196 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11197 ExprResult BaseResult = 11198 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11199 Best->FoundDecl, Method); 11200 if (BaseResult.isInvalid()) 11201 return ExprError(); 11202 Base = BaseResult.take(); 11203 11204 // Build the operator call. 11205 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11206 HadMultipleCandidates, OpLoc); 11207 if (FnExpr.isInvalid()) 11208 return ExprError(); 11209 11210 QualType ResultTy = Method->getResultType(); 11211 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11212 ResultTy = ResultTy.getNonLValueExprType(Context); 11213 CXXOperatorCallExpr *TheCall = 11214 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11215 Base, ResultTy, VK, OpLoc, false); 11216 11217 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11218 Method)) 11219 return ExprError(); 11220 11221 return MaybeBindToTemporary(TheCall); 11222} 11223 11224/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11225/// a literal operator described by the provided lookup results. 11226ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11227 DeclarationNameInfo &SuffixInfo, 11228 ArrayRef<Expr*> Args, 11229 SourceLocation LitEndLoc, 11230 TemplateArgumentListInfo *TemplateArgs) { 11231 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11232 11233 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11234 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11235 TemplateArgs); 11236 11237 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11238 11239 // Perform overload resolution. This will usually be trivial, but might need 11240 // to perform substitutions for a literal operator template. 11241 OverloadCandidateSet::iterator Best; 11242 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11243 case OR_Success: 11244 case OR_Deleted: 11245 break; 11246 11247 case OR_No_Viable_Function: 11248 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11249 << R.getLookupName(); 11250 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11251 return ExprError(); 11252 11253 case OR_Ambiguous: 11254 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11255 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11256 return ExprError(); 11257 } 11258 11259 FunctionDecl *FD = Best->Function; 11260 MarkFunctionReferenced(UDSuffixLoc, FD); 11261 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11262 11263 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11264 SuffixInfo.getLoc(), 11265 SuffixInfo.getInfo()); 11266 if (Fn.isInvalid()) 11267 return true; 11268 11269 // Check the argument types. This should almost always be a no-op, except 11270 // that array-to-pointer decay is applied to string literals. 11271 Expr *ConvArgs[2]; 11272 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11273 ExprResult InputInit = PerformCopyInitialization( 11274 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11275 SourceLocation(), Args[ArgIdx]); 11276 if (InputInit.isInvalid()) 11277 return true; 11278 ConvArgs[ArgIdx] = InputInit.take(); 11279 } 11280 11281 QualType ResultTy = FD->getResultType(); 11282 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11283 ResultTy = ResultTy.getNonLValueExprType(Context); 11284 11285 UserDefinedLiteral *UDL = 11286 new (Context) UserDefinedLiteral(Context, Fn.take(), 11287 llvm::makeArrayRef(ConvArgs, Args.size()), 11288 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11289 11290 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11291 return ExprError(); 11292 11293 if (CheckFunctionCall(FD, UDL, NULL)) 11294 return ExprError(); 11295 11296 return MaybeBindToTemporary(UDL); 11297} 11298 11299/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11300/// given LookupResult is non-empty, it is assumed to describe a member which 11301/// will be invoked. Otherwise, the function will be found via argument 11302/// dependent lookup. 11303/// CallExpr is set to a valid expression and FRS_Success returned on success, 11304/// otherwise CallExpr is set to ExprError() and some non-success value 11305/// is returned. 11306Sema::ForRangeStatus 11307Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11308 SourceLocation RangeLoc, VarDecl *Decl, 11309 BeginEndFunction BEF, 11310 const DeclarationNameInfo &NameInfo, 11311 LookupResult &MemberLookup, 11312 OverloadCandidateSet *CandidateSet, 11313 Expr *Range, ExprResult *CallExpr) { 11314 CandidateSet->clear(); 11315 if (!MemberLookup.empty()) { 11316 ExprResult MemberRef = 11317 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11318 /*IsPtr=*/false, CXXScopeSpec(), 11319 /*TemplateKWLoc=*/SourceLocation(), 11320 /*FirstQualifierInScope=*/0, 11321 MemberLookup, 11322 /*TemplateArgs=*/0); 11323 if (MemberRef.isInvalid()) { 11324 *CallExpr = ExprError(); 11325 Diag(Range->getLocStart(), diag::note_in_for_range) 11326 << RangeLoc << BEF << Range->getType(); 11327 return FRS_DiagnosticIssued; 11328 } 11329 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11330 if (CallExpr->isInvalid()) { 11331 *CallExpr = ExprError(); 11332 Diag(Range->getLocStart(), diag::note_in_for_range) 11333 << RangeLoc << BEF << Range->getType(); 11334 return FRS_DiagnosticIssued; 11335 } 11336 } else { 11337 UnresolvedSet<0> FoundNames; 11338 UnresolvedLookupExpr *Fn = 11339 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11340 NestedNameSpecifierLoc(), NameInfo, 11341 /*NeedsADL=*/true, /*Overloaded=*/false, 11342 FoundNames.begin(), FoundNames.end()); 11343 11344 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11345 CandidateSet, CallExpr); 11346 if (CandidateSet->empty() || CandidateSetError) { 11347 *CallExpr = ExprError(); 11348 return FRS_NoViableFunction; 11349 } 11350 OverloadCandidateSet::iterator Best; 11351 OverloadingResult OverloadResult = 11352 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11353 11354 if (OverloadResult == OR_No_Viable_Function) { 11355 *CallExpr = ExprError(); 11356 return FRS_NoViableFunction; 11357 } 11358 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11359 Loc, 0, CandidateSet, &Best, 11360 OverloadResult, 11361 /*AllowTypoCorrection=*/false); 11362 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11363 *CallExpr = ExprError(); 11364 Diag(Range->getLocStart(), diag::note_in_for_range) 11365 << RangeLoc << BEF << Range->getType(); 11366 return FRS_DiagnosticIssued; 11367 } 11368 } 11369 return FRS_Success; 11370} 11371 11372 11373/// FixOverloadedFunctionReference - E is an expression that refers to 11374/// a C++ overloaded function (possibly with some parentheses and 11375/// perhaps a '&' around it). We have resolved the overloaded function 11376/// to the function declaration Fn, so patch up the expression E to 11377/// refer (possibly indirectly) to Fn. Returns the new expr. 11378Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11379 FunctionDecl *Fn) { 11380 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11381 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11382 Found, Fn); 11383 if (SubExpr == PE->getSubExpr()) 11384 return PE; 11385 11386 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11387 } 11388 11389 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11390 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11391 Found, Fn); 11392 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11393 SubExpr->getType()) && 11394 "Implicit cast type cannot be determined from overload"); 11395 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11396 if (SubExpr == ICE->getSubExpr()) 11397 return ICE; 11398 11399 return ImplicitCastExpr::Create(Context, ICE->getType(), 11400 ICE->getCastKind(), 11401 SubExpr, 0, 11402 ICE->getValueKind()); 11403 } 11404 11405 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11406 assert(UnOp->getOpcode() == UO_AddrOf && 11407 "Can only take the address of an overloaded function"); 11408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11409 if (Method->isStatic()) { 11410 // Do nothing: static member functions aren't any different 11411 // from non-member functions. 11412 } else { 11413 // Fix the sub expression, which really has to be an 11414 // UnresolvedLookupExpr holding an overloaded member function 11415 // or template. 11416 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11417 Found, Fn); 11418 if (SubExpr == UnOp->getSubExpr()) 11419 return UnOp; 11420 11421 assert(isa<DeclRefExpr>(SubExpr) 11422 && "fixed to something other than a decl ref"); 11423 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11424 && "fixed to a member ref with no nested name qualifier"); 11425 11426 // We have taken the address of a pointer to member 11427 // function. Perform the computation here so that we get the 11428 // appropriate pointer to member type. 11429 QualType ClassType 11430 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11431 QualType MemPtrType 11432 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11433 11434 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11435 VK_RValue, OK_Ordinary, 11436 UnOp->getOperatorLoc()); 11437 } 11438 } 11439 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11440 Found, Fn); 11441 if (SubExpr == UnOp->getSubExpr()) 11442 return UnOp; 11443 11444 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11445 Context.getPointerType(SubExpr->getType()), 11446 VK_RValue, OK_Ordinary, 11447 UnOp->getOperatorLoc()); 11448 } 11449 11450 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11451 // FIXME: avoid copy. 11452 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11453 if (ULE->hasExplicitTemplateArgs()) { 11454 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11455 TemplateArgs = &TemplateArgsBuffer; 11456 } 11457 11458 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11459 ULE->getQualifierLoc(), 11460 ULE->getTemplateKeywordLoc(), 11461 Fn, 11462 /*enclosing*/ false, // FIXME? 11463 ULE->getNameLoc(), 11464 Fn->getType(), 11465 VK_LValue, 11466 Found.getDecl(), 11467 TemplateArgs); 11468 MarkDeclRefReferenced(DRE); 11469 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11470 return DRE; 11471 } 11472 11473 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11474 // FIXME: avoid copy. 11475 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11476 if (MemExpr->hasExplicitTemplateArgs()) { 11477 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11478 TemplateArgs = &TemplateArgsBuffer; 11479 } 11480 11481 Expr *Base; 11482 11483 // If we're filling in a static method where we used to have an 11484 // implicit member access, rewrite to a simple decl ref. 11485 if (MemExpr->isImplicitAccess()) { 11486 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11487 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11488 MemExpr->getQualifierLoc(), 11489 MemExpr->getTemplateKeywordLoc(), 11490 Fn, 11491 /*enclosing*/ false, 11492 MemExpr->getMemberLoc(), 11493 Fn->getType(), 11494 VK_LValue, 11495 Found.getDecl(), 11496 TemplateArgs); 11497 MarkDeclRefReferenced(DRE); 11498 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11499 return DRE; 11500 } else { 11501 SourceLocation Loc = MemExpr->getMemberLoc(); 11502 if (MemExpr->getQualifier()) 11503 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11504 CheckCXXThisCapture(Loc); 11505 Base = new (Context) CXXThisExpr(Loc, 11506 MemExpr->getBaseType(), 11507 /*isImplicit=*/true); 11508 } 11509 } else 11510 Base = MemExpr->getBase(); 11511 11512 ExprValueKind valueKind; 11513 QualType type; 11514 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11515 valueKind = VK_LValue; 11516 type = Fn->getType(); 11517 } else { 11518 valueKind = VK_RValue; 11519 type = Context.BoundMemberTy; 11520 } 11521 11522 MemberExpr *ME = MemberExpr::Create(Context, Base, 11523 MemExpr->isArrow(), 11524 MemExpr->getQualifierLoc(), 11525 MemExpr->getTemplateKeywordLoc(), 11526 Fn, 11527 Found, 11528 MemExpr->getMemberNameInfo(), 11529 TemplateArgs, 11530 type, valueKind, OK_Ordinary); 11531 ME->setHadMultipleCandidates(true); 11532 MarkMemberReferenced(ME); 11533 return ME; 11534 } 11535 11536 llvm_unreachable("Invalid reference to overloaded function"); 11537} 11538 11539ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11540 DeclAccessPair Found, 11541 FunctionDecl *Fn) { 11542 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11543} 11544 11545} // end namespace clang 11546