SemaTemplateDeduction.cpp revision a730f548325756d050d4caaa28fcbffdae8dfe95
1//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/ 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7//===----------------------------------------------------------------------===/ 8// 9// This file implements C++ template argument deduction. 10// 11//===----------------------------------------------------------------------===/ 12 13#include "clang/Sema/TemplateDeduction.h" 14#include "TreeTransform.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Sema/DeclSpec.h" 22#include "clang/Sema/Sema.h" 23#include "clang/Sema/Template.h" 24#include "llvm/ADT/SmallBitVector.h" 25#include <algorithm> 26 27namespace clang { 28 using namespace sema; 29 30 /// \brief Various flags that control template argument deduction. 31 /// 32 /// These flags can be bitwise-OR'd together. 33 enum TemplateDeductionFlags { 34 /// \brief No template argument deduction flags, which indicates the 35 /// strictest results for template argument deduction (as used for, e.g., 36 /// matching class template partial specializations). 37 TDF_None = 0, 38 /// \brief Within template argument deduction from a function call, we are 39 /// matching with a parameter type for which the original parameter was 40 /// a reference. 41 TDF_ParamWithReferenceType = 0x1, 42 /// \brief Within template argument deduction from a function call, we 43 /// are matching in a case where we ignore cv-qualifiers. 44 TDF_IgnoreQualifiers = 0x02, 45 /// \brief Within template argument deduction from a function call, 46 /// we are matching in a case where we can perform template argument 47 /// deduction from a template-id of a derived class of the argument type. 48 TDF_DerivedClass = 0x04, 49 /// \brief Allow non-dependent types to differ, e.g., when performing 50 /// template argument deduction from a function call where conversions 51 /// may apply. 52 TDF_SkipNonDependent = 0x08, 53 /// \brief Whether we are performing template argument deduction for 54 /// parameters and arguments in a top-level template argument 55 TDF_TopLevelParameterTypeList = 0x10, 56 /// \brief Within template argument deduction from overload resolution per 57 /// C++ [over.over] allow matching function types that are compatible in 58 /// terms of noreturn and default calling convention adjustments. 59 TDF_InOverloadResolution = 0x20 60 }; 61} 62 63using namespace clang; 64 65/// \brief Compare two APSInts, extending and switching the sign as 66/// necessary to compare their values regardless of underlying type. 67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) { 68 if (Y.getBitWidth() > X.getBitWidth()) 69 X = X.extend(Y.getBitWidth()); 70 else if (Y.getBitWidth() < X.getBitWidth()) 71 Y = Y.extend(X.getBitWidth()); 72 73 // If there is a signedness mismatch, correct it. 74 if (X.isSigned() != Y.isSigned()) { 75 // If the signed value is negative, then the values cannot be the same. 76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative())) 77 return false; 78 79 Y.setIsSigned(true); 80 X.setIsSigned(true); 81 } 82 83 return X == Y; 84} 85 86static Sema::TemplateDeductionResult 87DeduceTemplateArguments(Sema &S, 88 TemplateParameterList *TemplateParams, 89 const TemplateArgument &Param, 90 TemplateArgument Arg, 91 TemplateDeductionInfo &Info, 92 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 93 94/// \brief Whether template argument deduction for two reference parameters 95/// resulted in the argument type, parameter type, or neither type being more 96/// qualified than the other. 97enum DeductionQualifierComparison { 98 NeitherMoreQualified = 0, 99 ParamMoreQualified, 100 ArgMoreQualified 101}; 102 103/// \brief Stores the result of comparing two reference parameters while 104/// performing template argument deduction for partial ordering of function 105/// templates. 106struct RefParamPartialOrderingComparison { 107 /// \brief Whether the parameter type is an rvalue reference type. 108 bool ParamIsRvalueRef; 109 /// \brief Whether the argument type is an rvalue reference type. 110 bool ArgIsRvalueRef; 111 112 /// \brief Whether the parameter or argument (or neither) is more qualified. 113 DeductionQualifierComparison Qualifiers; 114}; 115 116 117 118static Sema::TemplateDeductionResult 119DeduceTemplateArgumentsByTypeMatch(Sema &S, 120 TemplateParameterList *TemplateParams, 121 QualType Param, 122 QualType Arg, 123 TemplateDeductionInfo &Info, 124 SmallVectorImpl<DeducedTemplateArgument> & 125 Deduced, 126 unsigned TDF, 127 bool PartialOrdering = false, 128 SmallVectorImpl<RefParamPartialOrderingComparison> * 129 RefParamComparisons = 0); 130 131static Sema::TemplateDeductionResult 132DeduceTemplateArguments(Sema &S, 133 TemplateParameterList *TemplateParams, 134 const TemplateArgument *Params, unsigned NumParams, 135 const TemplateArgument *Args, unsigned NumArgs, 136 TemplateDeductionInfo &Info, 137 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 138 139/// \brief If the given expression is of a form that permits the deduction 140/// of a non-type template parameter, return the declaration of that 141/// non-type template parameter. 142static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) { 143 // If we are within an alias template, the expression may have undergone 144 // any number of parameter substitutions already. 145 while (1) { 146 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E)) 147 E = IC->getSubExpr(); 148 else if (SubstNonTypeTemplateParmExpr *Subst = 149 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 150 E = Subst->getReplacement(); 151 else 152 break; 153 } 154 155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 156 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 157 158 return 0; 159} 160 161/// \brief Determine whether two declaration pointers refer to the same 162/// declaration. 163static bool isSameDeclaration(Decl *X, Decl *Y) { 164 if (NamedDecl *NX = dyn_cast<NamedDecl>(X)) 165 X = NX->getUnderlyingDecl(); 166 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y)) 167 Y = NY->getUnderlyingDecl(); 168 169 return X->getCanonicalDecl() == Y->getCanonicalDecl(); 170} 171 172/// \brief Verify that the given, deduced template arguments are compatible. 173/// 174/// \returns The deduced template argument, or a NULL template argument if 175/// the deduced template arguments were incompatible. 176static DeducedTemplateArgument 177checkDeducedTemplateArguments(ASTContext &Context, 178 const DeducedTemplateArgument &X, 179 const DeducedTemplateArgument &Y) { 180 // We have no deduction for one or both of the arguments; they're compatible. 181 if (X.isNull()) 182 return Y; 183 if (Y.isNull()) 184 return X; 185 186 switch (X.getKind()) { 187 case TemplateArgument::Null: 188 llvm_unreachable("Non-deduced template arguments handled above"); 189 190 case TemplateArgument::Type: 191 // If two template type arguments have the same type, they're compatible. 192 if (Y.getKind() == TemplateArgument::Type && 193 Context.hasSameType(X.getAsType(), Y.getAsType())) 194 return X; 195 196 return DeducedTemplateArgument(); 197 198 case TemplateArgument::Integral: 199 // If we deduced a constant in one case and either a dependent expression or 200 // declaration in another case, keep the integral constant. 201 // If both are integral constants with the same value, keep that value. 202 if (Y.getKind() == TemplateArgument::Expression || 203 Y.getKind() == TemplateArgument::Declaration || 204 (Y.getKind() == TemplateArgument::Integral && 205 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral()))) 206 return DeducedTemplateArgument(X, 207 X.wasDeducedFromArrayBound() && 208 Y.wasDeducedFromArrayBound()); 209 210 // All other combinations are incompatible. 211 return DeducedTemplateArgument(); 212 213 case TemplateArgument::Template: 214 if (Y.getKind() == TemplateArgument::Template && 215 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate())) 216 return X; 217 218 // All other combinations are incompatible. 219 return DeducedTemplateArgument(); 220 221 case TemplateArgument::TemplateExpansion: 222 if (Y.getKind() == TemplateArgument::TemplateExpansion && 223 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(), 224 Y.getAsTemplateOrTemplatePattern())) 225 return X; 226 227 // All other combinations are incompatible. 228 return DeducedTemplateArgument(); 229 230 case TemplateArgument::Expression: 231 // If we deduced a dependent expression in one case and either an integral 232 // constant or a declaration in another case, keep the integral constant 233 // or declaration. 234 if (Y.getKind() == TemplateArgument::Integral || 235 Y.getKind() == TemplateArgument::Declaration) 236 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() && 237 Y.wasDeducedFromArrayBound()); 238 239 if (Y.getKind() == TemplateArgument::Expression) { 240 // Compare the expressions for equality 241 llvm::FoldingSetNodeID ID1, ID2; 242 X.getAsExpr()->Profile(ID1, Context, true); 243 Y.getAsExpr()->Profile(ID2, Context, true); 244 if (ID1 == ID2) 245 return X; 246 } 247 248 // All other combinations are incompatible. 249 return DeducedTemplateArgument(); 250 251 case TemplateArgument::Declaration: 252 // If we deduced a declaration and a dependent expression, keep the 253 // declaration. 254 if (Y.getKind() == TemplateArgument::Expression) 255 return X; 256 257 // If we deduced a declaration and an integral constant, keep the 258 // integral constant. 259 if (Y.getKind() == TemplateArgument::Integral) 260 return Y; 261 262 // If we deduced two declarations, make sure they they refer to the 263 // same declaration. 264 if (Y.getKind() == TemplateArgument::Declaration && 265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) && 266 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam()) 267 return X; 268 269 // All other combinations are incompatible. 270 return DeducedTemplateArgument(); 271 272 case TemplateArgument::NullPtr: 273 // If we deduced a null pointer and a dependent expression, keep the 274 // null pointer. 275 if (Y.getKind() == TemplateArgument::Expression) 276 return X; 277 278 // If we deduced a null pointer and an integral constant, keep the 279 // integral constant. 280 if (Y.getKind() == TemplateArgument::Integral) 281 return Y; 282 283 // If we deduced two null pointers, make sure they have the same type. 284 if (Y.getKind() == TemplateArgument::NullPtr && 285 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType())) 286 return X; 287 288 // All other combinations are incompatible. 289 return DeducedTemplateArgument(); 290 291 case TemplateArgument::Pack: 292 if (Y.getKind() != TemplateArgument::Pack || 293 X.pack_size() != Y.pack_size()) 294 return DeducedTemplateArgument(); 295 296 for (TemplateArgument::pack_iterator XA = X.pack_begin(), 297 XAEnd = X.pack_end(), 298 YA = Y.pack_begin(); 299 XA != XAEnd; ++XA, ++YA) { 300 if (checkDeducedTemplateArguments(Context, 301 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), 302 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())) 303 .isNull()) 304 return DeducedTemplateArgument(); 305 } 306 307 return X; 308 } 309 310 llvm_unreachable("Invalid TemplateArgument Kind!"); 311} 312 313/// \brief Deduce the value of the given non-type template parameter 314/// from the given constant. 315static Sema::TemplateDeductionResult 316DeduceNonTypeTemplateArgument(Sema &S, 317 NonTypeTemplateParmDecl *NTTP, 318 llvm::APSInt Value, QualType ValueType, 319 bool DeducedFromArrayBound, 320 TemplateDeductionInfo &Info, 321 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 322 assert(NTTP->getDepth() == 0 && 323 "Cannot deduce non-type template argument with depth > 0"); 324 325 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType, 326 DeducedFromArrayBound); 327 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 328 Deduced[NTTP->getIndex()], 329 NewDeduced); 330 if (Result.isNull()) { 331 Info.Param = NTTP; 332 Info.FirstArg = Deduced[NTTP->getIndex()]; 333 Info.SecondArg = NewDeduced; 334 return Sema::TDK_Inconsistent; 335 } 336 337 Deduced[NTTP->getIndex()] = Result; 338 return Sema::TDK_Success; 339} 340 341/// \brief Deduce the value of the given non-type template parameter 342/// from the given type- or value-dependent expression. 343/// 344/// \returns true if deduction succeeded, false otherwise. 345static Sema::TemplateDeductionResult 346DeduceNonTypeTemplateArgument(Sema &S, 347 NonTypeTemplateParmDecl *NTTP, 348 Expr *Value, 349 TemplateDeductionInfo &Info, 350 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 351 assert(NTTP->getDepth() == 0 && 352 "Cannot deduce non-type template argument with depth > 0"); 353 assert((Value->isTypeDependent() || Value->isValueDependent()) && 354 "Expression template argument must be type- or value-dependent."); 355 356 DeducedTemplateArgument NewDeduced(Value); 357 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 358 Deduced[NTTP->getIndex()], 359 NewDeduced); 360 361 if (Result.isNull()) { 362 Info.Param = NTTP; 363 Info.FirstArg = Deduced[NTTP->getIndex()]; 364 Info.SecondArg = NewDeduced; 365 return Sema::TDK_Inconsistent; 366 } 367 368 Deduced[NTTP->getIndex()] = Result; 369 return Sema::TDK_Success; 370} 371 372/// \brief Deduce the value of the given non-type template parameter 373/// from the given declaration. 374/// 375/// \returns true if deduction succeeded, false otherwise. 376static Sema::TemplateDeductionResult 377DeduceNonTypeTemplateArgument(Sema &S, 378 NonTypeTemplateParmDecl *NTTP, 379 ValueDecl *D, 380 TemplateDeductionInfo &Info, 381 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 382 assert(NTTP->getDepth() == 0 && 383 "Cannot deduce non-type template argument with depth > 0"); 384 385 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : 0; 386 TemplateArgument New(D, NTTP->getType()->isReferenceType()); 387 DeducedTemplateArgument NewDeduced(New); 388 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 389 Deduced[NTTP->getIndex()], 390 NewDeduced); 391 if (Result.isNull()) { 392 Info.Param = NTTP; 393 Info.FirstArg = Deduced[NTTP->getIndex()]; 394 Info.SecondArg = NewDeduced; 395 return Sema::TDK_Inconsistent; 396 } 397 398 Deduced[NTTP->getIndex()] = Result; 399 return Sema::TDK_Success; 400} 401 402static Sema::TemplateDeductionResult 403DeduceTemplateArguments(Sema &S, 404 TemplateParameterList *TemplateParams, 405 TemplateName Param, 406 TemplateName Arg, 407 TemplateDeductionInfo &Info, 408 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 409 TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); 410 if (!ParamDecl) { 411 // The parameter type is dependent and is not a template template parameter, 412 // so there is nothing that we can deduce. 413 return Sema::TDK_Success; 414 } 415 416 if (TemplateTemplateParmDecl *TempParam 417 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) { 418 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg)); 419 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 420 Deduced[TempParam->getIndex()], 421 NewDeduced); 422 if (Result.isNull()) { 423 Info.Param = TempParam; 424 Info.FirstArg = Deduced[TempParam->getIndex()]; 425 Info.SecondArg = NewDeduced; 426 return Sema::TDK_Inconsistent; 427 } 428 429 Deduced[TempParam->getIndex()] = Result; 430 return Sema::TDK_Success; 431 } 432 433 // Verify that the two template names are equivalent. 434 if (S.Context.hasSameTemplateName(Param, Arg)) 435 return Sema::TDK_Success; 436 437 // Mismatch of non-dependent template parameter to argument. 438 Info.FirstArg = TemplateArgument(Param); 439 Info.SecondArg = TemplateArgument(Arg); 440 return Sema::TDK_NonDeducedMismatch; 441} 442 443/// \brief Deduce the template arguments by comparing the template parameter 444/// type (which is a template-id) with the template argument type. 445/// 446/// \param S the Sema 447/// 448/// \param TemplateParams the template parameters that we are deducing 449/// 450/// \param Param the parameter type 451/// 452/// \param Arg the argument type 453/// 454/// \param Info information about the template argument deduction itself 455/// 456/// \param Deduced the deduced template arguments 457/// 458/// \returns the result of template argument deduction so far. Note that a 459/// "success" result means that template argument deduction has not yet failed, 460/// but it may still fail, later, for other reasons. 461static Sema::TemplateDeductionResult 462DeduceTemplateArguments(Sema &S, 463 TemplateParameterList *TemplateParams, 464 const TemplateSpecializationType *Param, 465 QualType Arg, 466 TemplateDeductionInfo &Info, 467 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 468 assert(Arg.isCanonical() && "Argument type must be canonical"); 469 470 // Check whether the template argument is a dependent template-id. 471 if (const TemplateSpecializationType *SpecArg 472 = dyn_cast<TemplateSpecializationType>(Arg)) { 473 // Perform template argument deduction for the template name. 474 if (Sema::TemplateDeductionResult Result 475 = DeduceTemplateArguments(S, TemplateParams, 476 Param->getTemplateName(), 477 SpecArg->getTemplateName(), 478 Info, Deduced)) 479 return Result; 480 481 482 // Perform template argument deduction on each template 483 // argument. Ignore any missing/extra arguments, since they could be 484 // filled in by default arguments. 485 return DeduceTemplateArguments(S, TemplateParams, 486 Param->getArgs(), Param->getNumArgs(), 487 SpecArg->getArgs(), SpecArg->getNumArgs(), 488 Info, Deduced); 489 } 490 491 // If the argument type is a class template specialization, we 492 // perform template argument deduction using its template 493 // arguments. 494 const RecordType *RecordArg = dyn_cast<RecordType>(Arg); 495 if (!RecordArg) { 496 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 497 Info.SecondArg = TemplateArgument(Arg); 498 return Sema::TDK_NonDeducedMismatch; 499 } 500 501 ClassTemplateSpecializationDecl *SpecArg 502 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl()); 503 if (!SpecArg) { 504 Info.FirstArg = TemplateArgument(QualType(Param, 0)); 505 Info.SecondArg = TemplateArgument(Arg); 506 return Sema::TDK_NonDeducedMismatch; 507 } 508 509 // Perform template argument deduction for the template name. 510 if (Sema::TemplateDeductionResult Result 511 = DeduceTemplateArguments(S, 512 TemplateParams, 513 Param->getTemplateName(), 514 TemplateName(SpecArg->getSpecializedTemplate()), 515 Info, Deduced)) 516 return Result; 517 518 // Perform template argument deduction for the template arguments. 519 return DeduceTemplateArguments(S, TemplateParams, 520 Param->getArgs(), Param->getNumArgs(), 521 SpecArg->getTemplateArgs().data(), 522 SpecArg->getTemplateArgs().size(), 523 Info, Deduced); 524} 525 526/// \brief Determines whether the given type is an opaque type that 527/// might be more qualified when instantiated. 528static bool IsPossiblyOpaquelyQualifiedType(QualType T) { 529 switch (T->getTypeClass()) { 530 case Type::TypeOfExpr: 531 case Type::TypeOf: 532 case Type::DependentName: 533 case Type::Decltype: 534 case Type::UnresolvedUsing: 535 case Type::TemplateTypeParm: 536 return true; 537 538 case Type::ConstantArray: 539 case Type::IncompleteArray: 540 case Type::VariableArray: 541 case Type::DependentSizedArray: 542 return IsPossiblyOpaquelyQualifiedType( 543 cast<ArrayType>(T)->getElementType()); 544 545 default: 546 return false; 547 } 548} 549 550/// \brief Retrieve the depth and index of a template parameter. 551static std::pair<unsigned, unsigned> 552getDepthAndIndex(NamedDecl *ND) { 553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND)) 554 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 555 556 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND)) 557 return std::make_pair(NTTP->getDepth(), NTTP->getIndex()); 558 559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND); 560 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 561} 562 563/// \brief Retrieve the depth and index of an unexpanded parameter pack. 564static std::pair<unsigned, unsigned> 565getDepthAndIndex(UnexpandedParameterPack UPP) { 566 if (const TemplateTypeParmType *TTP 567 = UPP.first.dyn_cast<const TemplateTypeParmType *>()) 568 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 569 570 return getDepthAndIndex(UPP.first.get<NamedDecl *>()); 571} 572 573/// \brief Helper function to build a TemplateParameter when we don't 574/// know its type statically. 575static TemplateParameter makeTemplateParameter(Decl *D) { 576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D)) 577 return TemplateParameter(TTP); 578 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) 579 return TemplateParameter(NTTP); 580 581 return TemplateParameter(cast<TemplateTemplateParmDecl>(D)); 582} 583 584typedef SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2> 585 NewlyDeducedPacksType; 586 587/// \brief Prepare to perform template argument deduction for all of the 588/// arguments in a set of argument packs. 589static void 590PrepareArgumentPackDeduction(Sema &S, 591 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 592 ArrayRef<unsigned> PackIndices, 593 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks, 594 NewlyDeducedPacksType &NewlyDeducedPacks) { 595 // Save the deduced template arguments for each parameter pack expanded 596 // by this pack expansion, then clear out the deduction. 597 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 598 // Save the previously-deduced argument pack, then clear it out so that we 599 // can deduce a new argument pack. 600 SavedPacks[I] = Deduced[PackIndices[I]]; 601 Deduced[PackIndices[I]] = TemplateArgument(); 602 603 if (!S.CurrentInstantiationScope) 604 continue; 605 606 // If the template argument pack was explicitly specified, add that to 607 // the set of deduced arguments. 608 const TemplateArgument *ExplicitArgs; 609 unsigned NumExplicitArgs; 610 if (NamedDecl *PartiallySubstitutedPack 611 = S.CurrentInstantiationScope->getPartiallySubstitutedPack( 612 &ExplicitArgs, 613 &NumExplicitArgs)) { 614 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I]) 615 NewlyDeducedPacks[I].append(ExplicitArgs, 616 ExplicitArgs + NumExplicitArgs); 617 } 618 } 619} 620 621/// \brief Finish template argument deduction for a set of argument packs, 622/// producing the argument packs and checking for consistency with prior 623/// deductions. 624static Sema::TemplateDeductionResult 625FinishArgumentPackDeduction(Sema &S, 626 TemplateParameterList *TemplateParams, 627 bool HasAnyArguments, 628 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 629 ArrayRef<unsigned> PackIndices, 630 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks, 631 NewlyDeducedPacksType &NewlyDeducedPacks, 632 TemplateDeductionInfo &Info) { 633 // Build argument packs for each of the parameter packs expanded by this 634 // pack expansion. 635 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 636 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) { 637 // We were not able to deduce anything for this parameter pack, 638 // so just restore the saved argument pack. 639 Deduced[PackIndices[I]] = SavedPacks[I]; 640 continue; 641 } 642 643 DeducedTemplateArgument NewPack; 644 645 if (NewlyDeducedPacks[I].empty()) { 646 // If we deduced an empty argument pack, create it now. 647 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack()); 648 } else { 649 TemplateArgument *ArgumentPack 650 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()]; 651 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(), 652 ArgumentPack); 653 NewPack 654 = DeducedTemplateArgument(TemplateArgument(ArgumentPack, 655 NewlyDeducedPacks[I].size()), 656 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound()); 657 } 658 659 DeducedTemplateArgument Result 660 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack); 661 if (Result.isNull()) { 662 Info.Param 663 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I])); 664 Info.FirstArg = SavedPacks[I]; 665 Info.SecondArg = NewPack; 666 return Sema::TDK_Inconsistent; 667 } 668 669 Deduced[PackIndices[I]] = Result; 670 } 671 672 return Sema::TDK_Success; 673} 674 675/// \brief Deduce the template arguments by comparing the list of parameter 676/// types to the list of argument types, as in the parameter-type-lists of 677/// function types (C++ [temp.deduct.type]p10). 678/// 679/// \param S The semantic analysis object within which we are deducing 680/// 681/// \param TemplateParams The template parameters that we are deducing 682/// 683/// \param Params The list of parameter types 684/// 685/// \param NumParams The number of types in \c Params 686/// 687/// \param Args The list of argument types 688/// 689/// \param NumArgs The number of types in \c Args 690/// 691/// \param Info information about the template argument deduction itself 692/// 693/// \param Deduced the deduced template arguments 694/// 695/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 696/// how template argument deduction is performed. 697/// 698/// \param PartialOrdering If true, we are performing template argument 699/// deduction for during partial ordering for a call 700/// (C++0x [temp.deduct.partial]). 701/// 702/// \param RefParamComparisons If we're performing template argument deduction 703/// in the context of partial ordering, the set of qualifier comparisons. 704/// 705/// \returns the result of template argument deduction so far. Note that a 706/// "success" result means that template argument deduction has not yet failed, 707/// but it may still fail, later, for other reasons. 708static Sema::TemplateDeductionResult 709DeduceTemplateArguments(Sema &S, 710 TemplateParameterList *TemplateParams, 711 const QualType *Params, unsigned NumParams, 712 const QualType *Args, unsigned NumArgs, 713 TemplateDeductionInfo &Info, 714 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 715 unsigned TDF, 716 bool PartialOrdering = false, 717 SmallVectorImpl<RefParamPartialOrderingComparison> * 718 RefParamComparisons = 0) { 719 // Fast-path check to see if we have too many/too few arguments. 720 if (NumParams != NumArgs && 721 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) && 722 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1]))) 723 return Sema::TDK_MiscellaneousDeductionFailure; 724 725 // C++0x [temp.deduct.type]p10: 726 // Similarly, if P has a form that contains (T), then each parameter type 727 // Pi of the respective parameter-type- list of P is compared with the 728 // corresponding parameter type Ai of the corresponding parameter-type-list 729 // of A. [...] 730 unsigned ArgIdx = 0, ParamIdx = 0; 731 for (; ParamIdx != NumParams; ++ParamIdx) { 732 // Check argument types. 733 const PackExpansionType *Expansion 734 = dyn_cast<PackExpansionType>(Params[ParamIdx]); 735 if (!Expansion) { 736 // Simple case: compare the parameter and argument types at this point. 737 738 // Make sure we have an argument. 739 if (ArgIdx >= NumArgs) 740 return Sema::TDK_MiscellaneousDeductionFailure; 741 742 if (isa<PackExpansionType>(Args[ArgIdx])) { 743 // C++0x [temp.deduct.type]p22: 744 // If the original function parameter associated with A is a function 745 // parameter pack and the function parameter associated with P is not 746 // a function parameter pack, then template argument deduction fails. 747 return Sema::TDK_MiscellaneousDeductionFailure; 748 } 749 750 if (Sema::TemplateDeductionResult Result 751 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 752 Params[ParamIdx], Args[ArgIdx], 753 Info, Deduced, TDF, 754 PartialOrdering, 755 RefParamComparisons)) 756 return Result; 757 758 ++ArgIdx; 759 continue; 760 } 761 762 // C++0x [temp.deduct.type]p5: 763 // The non-deduced contexts are: 764 // - A function parameter pack that does not occur at the end of the 765 // parameter-declaration-clause. 766 if (ParamIdx + 1 < NumParams) 767 return Sema::TDK_Success; 768 769 // C++0x [temp.deduct.type]p10: 770 // If the parameter-declaration corresponding to Pi is a function 771 // parameter pack, then the type of its declarator- id is compared with 772 // each remaining parameter type in the parameter-type-list of A. Each 773 // comparison deduces template arguments for subsequent positions in the 774 // template parameter packs expanded by the function parameter pack. 775 776 // Compute the set of template parameter indices that correspond to 777 // parameter packs expanded by the pack expansion. 778 SmallVector<unsigned, 2> PackIndices; 779 QualType Pattern = Expansion->getPattern(); 780 { 781 llvm::SmallBitVector SawIndices(TemplateParams->size()); 782 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 783 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 784 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 785 unsigned Depth, Index; 786 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 787 if (Depth == 0 && !SawIndices[Index]) { 788 SawIndices[Index] = true; 789 PackIndices.push_back(Index); 790 } 791 } 792 } 793 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?"); 794 795 // Keep track of the deduced template arguments for each parameter pack 796 // expanded by this pack expansion (the outer index) and for each 797 // template argument (the inner SmallVectors). 798 NewlyDeducedPacksType NewlyDeducedPacks(PackIndices.size()); 799 SmallVector<DeducedTemplateArgument, 2> 800 SavedPacks(PackIndices.size()); 801 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks, 802 NewlyDeducedPacks); 803 804 bool HasAnyArguments = false; 805 for (; ArgIdx < NumArgs; ++ArgIdx) { 806 HasAnyArguments = true; 807 808 // Deduce template arguments from the pattern. 809 if (Sema::TemplateDeductionResult Result 810 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern, 811 Args[ArgIdx], Info, Deduced, 812 TDF, PartialOrdering, 813 RefParamComparisons)) 814 return Result; 815 816 // Capture the deduced template arguments for each parameter pack expanded 817 // by this pack expansion, add them to the list of arguments we've deduced 818 // for that pack, then clear out the deduced argument. 819 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 820 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]]; 821 if (!DeducedArg.isNull()) { 822 NewlyDeducedPacks[I].push_back(DeducedArg); 823 DeducedArg = DeducedTemplateArgument(); 824 } 825 } 826 } 827 828 // Build argument packs for each of the parameter packs expanded by this 829 // pack expansion. 830 if (Sema::TemplateDeductionResult Result 831 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments, 832 Deduced, PackIndices, SavedPacks, 833 NewlyDeducedPacks, Info)) 834 return Result; 835 } 836 837 // Make sure we don't have any extra arguments. 838 if (ArgIdx < NumArgs) 839 return Sema::TDK_MiscellaneousDeductionFailure; 840 841 return Sema::TDK_Success; 842} 843 844/// \brief Determine whether the parameter has qualifiers that are either 845/// inconsistent with or a superset of the argument's qualifiers. 846static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, 847 QualType ArgType) { 848 Qualifiers ParamQs = ParamType.getQualifiers(); 849 Qualifiers ArgQs = ArgType.getQualifiers(); 850 851 if (ParamQs == ArgQs) 852 return false; 853 854 // Mismatched (but not missing) Objective-C GC attributes. 855 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && 856 ParamQs.hasObjCGCAttr()) 857 return true; 858 859 // Mismatched (but not missing) address spaces. 860 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && 861 ParamQs.hasAddressSpace()) 862 return true; 863 864 // Mismatched (but not missing) Objective-C lifetime qualifiers. 865 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && 866 ParamQs.hasObjCLifetime()) 867 return true; 868 869 // CVR qualifier superset. 870 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) && 871 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers()) 872 == ParamQs.getCVRQualifiers()); 873} 874 875/// \brief Compare types for equality with respect to possibly compatible 876/// function types (noreturn adjustment, implicit calling conventions). If any 877/// of parameter and argument is not a function, just perform type comparison. 878/// 879/// \param Param the template parameter type. 880/// 881/// \param Arg the argument type. 882bool Sema::isSameOrCompatibleFunctionType(CanQualType Param, 883 CanQualType Arg) { 884 const FunctionType *ParamFunction = Param->getAs<FunctionType>(), 885 *ArgFunction = Arg->getAs<FunctionType>(); 886 887 // Just compare if not functions. 888 if (!ParamFunction || !ArgFunction) 889 return Param == Arg; 890 891 // Noreturn adjustment. 892 QualType AdjustedParam; 893 if (IsNoReturnConversion(Param, Arg, AdjustedParam)) 894 return Arg == Context.getCanonicalType(AdjustedParam); 895 896 // FIXME: Compatible calling conventions. 897 898 return Param == Arg; 899} 900 901/// \brief Deduce the template arguments by comparing the parameter type and 902/// the argument type (C++ [temp.deduct.type]). 903/// 904/// \param S the semantic analysis object within which we are deducing 905/// 906/// \param TemplateParams the template parameters that we are deducing 907/// 908/// \param ParamIn the parameter type 909/// 910/// \param ArgIn the argument type 911/// 912/// \param Info information about the template argument deduction itself 913/// 914/// \param Deduced the deduced template arguments 915/// 916/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 917/// how template argument deduction is performed. 918/// 919/// \param PartialOrdering Whether we're performing template argument deduction 920/// in the context of partial ordering (C++0x [temp.deduct.partial]). 921/// 922/// \param RefParamComparisons If we're performing template argument deduction 923/// in the context of partial ordering, the set of qualifier comparisons. 924/// 925/// \returns the result of template argument deduction so far. Note that a 926/// "success" result means that template argument deduction has not yet failed, 927/// but it may still fail, later, for other reasons. 928static Sema::TemplateDeductionResult 929DeduceTemplateArgumentsByTypeMatch(Sema &S, 930 TemplateParameterList *TemplateParams, 931 QualType ParamIn, QualType ArgIn, 932 TemplateDeductionInfo &Info, 933 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 934 unsigned TDF, 935 bool PartialOrdering, 936 SmallVectorImpl<RefParamPartialOrderingComparison> * 937 RefParamComparisons) { 938 // We only want to look at the canonical types, since typedefs and 939 // sugar are not part of template argument deduction. 940 QualType Param = S.Context.getCanonicalType(ParamIn); 941 QualType Arg = S.Context.getCanonicalType(ArgIn); 942 943 // If the argument type is a pack expansion, look at its pattern. 944 // This isn't explicitly called out 945 if (const PackExpansionType *ArgExpansion 946 = dyn_cast<PackExpansionType>(Arg)) 947 Arg = ArgExpansion->getPattern(); 948 949 if (PartialOrdering) { 950 // C++0x [temp.deduct.partial]p5: 951 // Before the partial ordering is done, certain transformations are 952 // performed on the types used for partial ordering: 953 // - If P is a reference type, P is replaced by the type referred to. 954 const ReferenceType *ParamRef = Param->getAs<ReferenceType>(); 955 if (ParamRef) 956 Param = ParamRef->getPointeeType(); 957 958 // - If A is a reference type, A is replaced by the type referred to. 959 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>(); 960 if (ArgRef) 961 Arg = ArgRef->getPointeeType(); 962 963 if (RefParamComparisons && ParamRef && ArgRef) { 964 // C++0x [temp.deduct.partial]p6: 965 // If both P and A were reference types (before being replaced with the 966 // type referred to above), determine which of the two types (if any) is 967 // more cv-qualified than the other; otherwise the types are considered 968 // to be equally cv-qualified for partial ordering purposes. The result 969 // of this determination will be used below. 970 // 971 // We save this information for later, using it only when deduction 972 // succeeds in both directions. 973 RefParamPartialOrderingComparison Comparison; 974 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>(); 975 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>(); 976 Comparison.Qualifiers = NeitherMoreQualified; 977 978 Qualifiers ParamQuals = Param.getQualifiers(); 979 Qualifiers ArgQuals = Arg.getQualifiers(); 980 if (ParamQuals.isStrictSupersetOf(ArgQuals)) 981 Comparison.Qualifiers = ParamMoreQualified; 982 else if (ArgQuals.isStrictSupersetOf(ParamQuals)) 983 Comparison.Qualifiers = ArgMoreQualified; 984 RefParamComparisons->push_back(Comparison); 985 } 986 987 // C++0x [temp.deduct.partial]p7: 988 // Remove any top-level cv-qualifiers: 989 // - If P is a cv-qualified type, P is replaced by the cv-unqualified 990 // version of P. 991 Param = Param.getUnqualifiedType(); 992 // - If A is a cv-qualified type, A is replaced by the cv-unqualified 993 // version of A. 994 Arg = Arg.getUnqualifiedType(); 995 } else { 996 // C++0x [temp.deduct.call]p4 bullet 1: 997 // - If the original P is a reference type, the deduced A (i.e., the type 998 // referred to by the reference) can be more cv-qualified than the 999 // transformed A. 1000 if (TDF & TDF_ParamWithReferenceType) { 1001 Qualifiers Quals; 1002 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals); 1003 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & 1004 Arg.getCVRQualifiers()); 1005 Param = S.Context.getQualifiedType(UnqualParam, Quals); 1006 } 1007 1008 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) { 1009 // C++0x [temp.deduct.type]p10: 1010 // If P and A are function types that originated from deduction when 1011 // taking the address of a function template (14.8.2.2) or when deducing 1012 // template arguments from a function declaration (14.8.2.6) and Pi and 1013 // Ai are parameters of the top-level parameter-type-list of P and A, 1014 // respectively, Pi is adjusted if it is an rvalue reference to a 1015 // cv-unqualified template parameter and Ai is an lvalue reference, in 1016 // which case the type of Pi is changed to be the template parameter 1017 // type (i.e., T&& is changed to simply T). [ Note: As a result, when 1018 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be 1019 // deduced as X&. - end note ] 1020 TDF &= ~TDF_TopLevelParameterTypeList; 1021 1022 if (const RValueReferenceType *ParamRef 1023 = Param->getAs<RValueReferenceType>()) { 1024 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) && 1025 !ParamRef->getPointeeType().getQualifiers()) 1026 if (Arg->isLValueReferenceType()) 1027 Param = ParamRef->getPointeeType(); 1028 } 1029 } 1030 } 1031 1032 // C++ [temp.deduct.type]p9: 1033 // A template type argument T, a template template argument TT or a 1034 // template non-type argument i can be deduced if P and A have one of 1035 // the following forms: 1036 // 1037 // T 1038 // cv-list T 1039 if (const TemplateTypeParmType *TemplateTypeParm 1040 = Param->getAs<TemplateTypeParmType>()) { 1041 // Just skip any attempts to deduce from a placeholder type. 1042 if (Arg->isPlaceholderType()) 1043 return Sema::TDK_Success; 1044 1045 unsigned Index = TemplateTypeParm->getIndex(); 1046 bool RecanonicalizeArg = false; 1047 1048 // If the argument type is an array type, move the qualifiers up to the 1049 // top level, so they can be matched with the qualifiers on the parameter. 1050 if (isa<ArrayType>(Arg)) { 1051 Qualifiers Quals; 1052 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals); 1053 if (Quals) { 1054 Arg = S.Context.getQualifiedType(Arg, Quals); 1055 RecanonicalizeArg = true; 1056 } 1057 } 1058 1059 // The argument type can not be less qualified than the parameter 1060 // type. 1061 if (!(TDF & TDF_IgnoreQualifiers) && 1062 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) { 1063 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1064 Info.FirstArg = TemplateArgument(Param); 1065 Info.SecondArg = TemplateArgument(Arg); 1066 return Sema::TDK_Underqualified; 1067 } 1068 1069 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0"); 1070 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function"); 1071 QualType DeducedType = Arg; 1072 1073 // Remove any qualifiers on the parameter from the deduced type. 1074 // We checked the qualifiers for consistency above. 1075 Qualifiers DeducedQs = DeducedType.getQualifiers(); 1076 Qualifiers ParamQs = Param.getQualifiers(); 1077 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers()); 1078 if (ParamQs.hasObjCGCAttr()) 1079 DeducedQs.removeObjCGCAttr(); 1080 if (ParamQs.hasAddressSpace()) 1081 DeducedQs.removeAddressSpace(); 1082 if (ParamQs.hasObjCLifetime()) 1083 DeducedQs.removeObjCLifetime(); 1084 1085 // Objective-C ARC: 1086 // If template deduction would produce a lifetime qualifier on a type 1087 // that is not a lifetime type, template argument deduction fails. 1088 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && 1089 !DeducedType->isDependentType()) { 1090 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1091 Info.FirstArg = TemplateArgument(Param); 1092 Info.SecondArg = TemplateArgument(Arg); 1093 return Sema::TDK_Underqualified; 1094 } 1095 1096 // Objective-C ARC: 1097 // If template deduction would produce an argument type with lifetime type 1098 // but no lifetime qualifier, the __strong lifetime qualifier is inferred. 1099 if (S.getLangOpts().ObjCAutoRefCount && 1100 DeducedType->isObjCLifetimeType() && 1101 !DeducedQs.hasObjCLifetime()) 1102 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); 1103 1104 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), 1105 DeducedQs); 1106 1107 if (RecanonicalizeArg) 1108 DeducedType = S.Context.getCanonicalType(DeducedType); 1109 1110 DeducedTemplateArgument NewDeduced(DeducedType); 1111 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 1112 Deduced[Index], 1113 NewDeduced); 1114 if (Result.isNull()) { 1115 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 1116 Info.FirstArg = Deduced[Index]; 1117 Info.SecondArg = NewDeduced; 1118 return Sema::TDK_Inconsistent; 1119 } 1120 1121 Deduced[Index] = Result; 1122 return Sema::TDK_Success; 1123 } 1124 1125 // Set up the template argument deduction information for a failure. 1126 Info.FirstArg = TemplateArgument(ParamIn); 1127 Info.SecondArg = TemplateArgument(ArgIn); 1128 1129 // If the parameter is an already-substituted template parameter 1130 // pack, do nothing: we don't know which of its arguments to look 1131 // at, so we have to wait until all of the parameter packs in this 1132 // expansion have arguments. 1133 if (isa<SubstTemplateTypeParmPackType>(Param)) 1134 return Sema::TDK_Success; 1135 1136 // Check the cv-qualifiers on the parameter and argument types. 1137 CanQualType CanParam = S.Context.getCanonicalType(Param); 1138 CanQualType CanArg = S.Context.getCanonicalType(Arg); 1139 if (!(TDF & TDF_IgnoreQualifiers)) { 1140 if (TDF & TDF_ParamWithReferenceType) { 1141 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg)) 1142 return Sema::TDK_NonDeducedMismatch; 1143 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) { 1144 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers()) 1145 return Sema::TDK_NonDeducedMismatch; 1146 } 1147 1148 // If the parameter type is not dependent, there is nothing to deduce. 1149 if (!Param->isDependentType()) { 1150 if (!(TDF & TDF_SkipNonDependent)) { 1151 bool NonDeduced = (TDF & TDF_InOverloadResolution)? 1152 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) : 1153 Param != Arg; 1154 if (NonDeduced) { 1155 return Sema::TDK_NonDeducedMismatch; 1156 } 1157 } 1158 return Sema::TDK_Success; 1159 } 1160 } else if (!Param->isDependentType()) { 1161 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(), 1162 ArgUnqualType = CanArg.getUnqualifiedType(); 1163 bool Success = (TDF & TDF_InOverloadResolution)? 1164 S.isSameOrCompatibleFunctionType(ParamUnqualType, 1165 ArgUnqualType) : 1166 ParamUnqualType == ArgUnqualType; 1167 if (Success) 1168 return Sema::TDK_Success; 1169 } 1170 1171 switch (Param->getTypeClass()) { 1172 // Non-canonical types cannot appear here. 1173#define NON_CANONICAL_TYPE(Class, Base) \ 1174 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); 1175#define TYPE(Class, Base) 1176#include "clang/AST/TypeNodes.def" 1177 1178 case Type::TemplateTypeParm: 1179 case Type::SubstTemplateTypeParmPack: 1180 llvm_unreachable("Type nodes handled above"); 1181 1182 // These types cannot be dependent, so simply check whether the types are 1183 // the same. 1184 case Type::Builtin: 1185 case Type::VariableArray: 1186 case Type::Vector: 1187 case Type::FunctionNoProto: 1188 case Type::Record: 1189 case Type::Enum: 1190 case Type::ObjCObject: 1191 case Type::ObjCInterface: 1192 case Type::ObjCObjectPointer: { 1193 if (TDF & TDF_SkipNonDependent) 1194 return Sema::TDK_Success; 1195 1196 if (TDF & TDF_IgnoreQualifiers) { 1197 Param = Param.getUnqualifiedType(); 1198 Arg = Arg.getUnqualifiedType(); 1199 } 1200 1201 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch; 1202 } 1203 1204 // _Complex T [placeholder extension] 1205 case Type::Complex: 1206 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>()) 1207 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1208 cast<ComplexType>(Param)->getElementType(), 1209 ComplexArg->getElementType(), 1210 Info, Deduced, TDF); 1211 1212 return Sema::TDK_NonDeducedMismatch; 1213 1214 // _Atomic T [extension] 1215 case Type::Atomic: 1216 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>()) 1217 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1218 cast<AtomicType>(Param)->getValueType(), 1219 AtomicArg->getValueType(), 1220 Info, Deduced, TDF); 1221 1222 return Sema::TDK_NonDeducedMismatch; 1223 1224 // T * 1225 case Type::Pointer: { 1226 QualType PointeeType; 1227 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) { 1228 PointeeType = PointerArg->getPointeeType(); 1229 } else if (const ObjCObjectPointerType *PointerArg 1230 = Arg->getAs<ObjCObjectPointerType>()) { 1231 PointeeType = PointerArg->getPointeeType(); 1232 } else { 1233 return Sema::TDK_NonDeducedMismatch; 1234 } 1235 1236 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass); 1237 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1238 cast<PointerType>(Param)->getPointeeType(), 1239 PointeeType, 1240 Info, Deduced, SubTDF); 1241 } 1242 1243 // T & 1244 case Type::LValueReference: { 1245 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>(); 1246 if (!ReferenceArg) 1247 return Sema::TDK_NonDeducedMismatch; 1248 1249 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1250 cast<LValueReferenceType>(Param)->getPointeeType(), 1251 ReferenceArg->getPointeeType(), Info, Deduced, 0); 1252 } 1253 1254 // T && [C++0x] 1255 case Type::RValueReference: { 1256 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>(); 1257 if (!ReferenceArg) 1258 return Sema::TDK_NonDeducedMismatch; 1259 1260 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1261 cast<RValueReferenceType>(Param)->getPointeeType(), 1262 ReferenceArg->getPointeeType(), 1263 Info, Deduced, 0); 1264 } 1265 1266 // T [] (implied, but not stated explicitly) 1267 case Type::IncompleteArray: { 1268 const IncompleteArrayType *IncompleteArrayArg = 1269 S.Context.getAsIncompleteArrayType(Arg); 1270 if (!IncompleteArrayArg) 1271 return Sema::TDK_NonDeducedMismatch; 1272 1273 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1274 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1275 S.Context.getAsIncompleteArrayType(Param)->getElementType(), 1276 IncompleteArrayArg->getElementType(), 1277 Info, Deduced, SubTDF); 1278 } 1279 1280 // T [integer-constant] 1281 case Type::ConstantArray: { 1282 const ConstantArrayType *ConstantArrayArg = 1283 S.Context.getAsConstantArrayType(Arg); 1284 if (!ConstantArrayArg) 1285 return Sema::TDK_NonDeducedMismatch; 1286 1287 const ConstantArrayType *ConstantArrayParm = 1288 S.Context.getAsConstantArrayType(Param); 1289 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize()) 1290 return Sema::TDK_NonDeducedMismatch; 1291 1292 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1293 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1294 ConstantArrayParm->getElementType(), 1295 ConstantArrayArg->getElementType(), 1296 Info, Deduced, SubTDF); 1297 } 1298 1299 // type [i] 1300 case Type::DependentSizedArray: { 1301 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg); 1302 if (!ArrayArg) 1303 return Sema::TDK_NonDeducedMismatch; 1304 1305 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 1306 1307 // Check the element type of the arrays 1308 const DependentSizedArrayType *DependentArrayParm 1309 = S.Context.getAsDependentSizedArrayType(Param); 1310 if (Sema::TemplateDeductionResult Result 1311 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1312 DependentArrayParm->getElementType(), 1313 ArrayArg->getElementType(), 1314 Info, Deduced, SubTDF)) 1315 return Result; 1316 1317 // Determine the array bound is something we can deduce. 1318 NonTypeTemplateParmDecl *NTTP 1319 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr()); 1320 if (!NTTP) 1321 return Sema::TDK_Success; 1322 1323 // We can perform template argument deduction for the given non-type 1324 // template parameter. 1325 assert(NTTP->getDepth() == 0 && 1326 "Cannot deduce non-type template argument at depth > 0"); 1327 if (const ConstantArrayType *ConstantArrayArg 1328 = dyn_cast<ConstantArrayType>(ArrayArg)) { 1329 llvm::APSInt Size(ConstantArrayArg->getSize()); 1330 return DeduceNonTypeTemplateArgument(S, NTTP, Size, 1331 S.Context.getSizeType(), 1332 /*ArrayBound=*/true, 1333 Info, Deduced); 1334 } 1335 if (const DependentSizedArrayType *DependentArrayArg 1336 = dyn_cast<DependentSizedArrayType>(ArrayArg)) 1337 if (DependentArrayArg->getSizeExpr()) 1338 return DeduceNonTypeTemplateArgument(S, NTTP, 1339 DependentArrayArg->getSizeExpr(), 1340 Info, Deduced); 1341 1342 // Incomplete type does not match a dependently-sized array type 1343 return Sema::TDK_NonDeducedMismatch; 1344 } 1345 1346 // type(*)(T) 1347 // T(*)() 1348 // T(*)(T) 1349 case Type::FunctionProto: { 1350 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList; 1351 const FunctionProtoType *FunctionProtoArg = 1352 dyn_cast<FunctionProtoType>(Arg); 1353 if (!FunctionProtoArg) 1354 return Sema::TDK_NonDeducedMismatch; 1355 1356 const FunctionProtoType *FunctionProtoParam = 1357 cast<FunctionProtoType>(Param); 1358 1359 if (FunctionProtoParam->getTypeQuals() 1360 != FunctionProtoArg->getTypeQuals() || 1361 FunctionProtoParam->getRefQualifier() 1362 != FunctionProtoArg->getRefQualifier() || 1363 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic()) 1364 return Sema::TDK_NonDeducedMismatch; 1365 1366 // Check return types. 1367 if (Sema::TemplateDeductionResult Result 1368 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1369 FunctionProtoParam->getResultType(), 1370 FunctionProtoArg->getResultType(), 1371 Info, Deduced, 0)) 1372 return Result; 1373 1374 return DeduceTemplateArguments(S, TemplateParams, 1375 FunctionProtoParam->arg_type_begin(), 1376 FunctionProtoParam->getNumArgs(), 1377 FunctionProtoArg->arg_type_begin(), 1378 FunctionProtoArg->getNumArgs(), 1379 Info, Deduced, SubTDF); 1380 } 1381 1382 case Type::InjectedClassName: { 1383 // Treat a template's injected-class-name as if the template 1384 // specialization type had been used. 1385 Param = cast<InjectedClassNameType>(Param) 1386 ->getInjectedSpecializationType(); 1387 assert(isa<TemplateSpecializationType>(Param) && 1388 "injected class name is not a template specialization type"); 1389 // fall through 1390 } 1391 1392 // template-name<T> (where template-name refers to a class template) 1393 // template-name<i> 1394 // TT<T> 1395 // TT<i> 1396 // TT<> 1397 case Type::TemplateSpecialization: { 1398 const TemplateSpecializationType *SpecParam 1399 = cast<TemplateSpecializationType>(Param); 1400 1401 // Try to deduce template arguments from the template-id. 1402 Sema::TemplateDeductionResult Result 1403 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, 1404 Info, Deduced); 1405 1406 if (Result && (TDF & TDF_DerivedClass)) { 1407 // C++ [temp.deduct.call]p3b3: 1408 // If P is a class, and P has the form template-id, then A can be a 1409 // derived class of the deduced A. Likewise, if P is a pointer to a 1410 // class of the form template-id, A can be a pointer to a derived 1411 // class pointed to by the deduced A. 1412 // 1413 // More importantly: 1414 // These alternatives are considered only if type deduction would 1415 // otherwise fail. 1416 if (const RecordType *RecordT = Arg->getAs<RecordType>()) { 1417 // We cannot inspect base classes as part of deduction when the type 1418 // is incomplete, so either instantiate any templates necessary to 1419 // complete the type, or skip over it if it cannot be completed. 1420 if (S.RequireCompleteType(Info.getLocation(), Arg, 0)) 1421 return Result; 1422 1423 // Use data recursion to crawl through the list of base classes. 1424 // Visited contains the set of nodes we have already visited, while 1425 // ToVisit is our stack of records that we still need to visit. 1426 llvm::SmallPtrSet<const RecordType *, 8> Visited; 1427 SmallVector<const RecordType *, 8> ToVisit; 1428 ToVisit.push_back(RecordT); 1429 bool Successful = false; 1430 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), 1431 Deduced.end()); 1432 while (!ToVisit.empty()) { 1433 // Retrieve the next class in the inheritance hierarchy. 1434 const RecordType *NextT = ToVisit.back(); 1435 ToVisit.pop_back(); 1436 1437 // If we have already seen this type, skip it. 1438 if (!Visited.insert(NextT)) 1439 continue; 1440 1441 // If this is a base class, try to perform template argument 1442 // deduction from it. 1443 if (NextT != RecordT) { 1444 TemplateDeductionInfo BaseInfo(Info.getLocation()); 1445 Sema::TemplateDeductionResult BaseResult 1446 = DeduceTemplateArguments(S, TemplateParams, SpecParam, 1447 QualType(NextT, 0), BaseInfo, 1448 Deduced); 1449 1450 // If template argument deduction for this base was successful, 1451 // note that we had some success. Otherwise, ignore any deductions 1452 // from this base class. 1453 if (BaseResult == Sema::TDK_Success) { 1454 Successful = true; 1455 DeducedOrig.clear(); 1456 DeducedOrig.append(Deduced.begin(), Deduced.end()); 1457 Info.Param = BaseInfo.Param; 1458 Info.FirstArg = BaseInfo.FirstArg; 1459 Info.SecondArg = BaseInfo.SecondArg; 1460 } 1461 else 1462 Deduced = DeducedOrig; 1463 } 1464 1465 // Visit base classes 1466 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl()); 1467 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(), 1468 BaseEnd = Next->bases_end(); 1469 Base != BaseEnd; ++Base) { 1470 assert(Base->getType()->isRecordType() && 1471 "Base class that isn't a record?"); 1472 ToVisit.push_back(Base->getType()->getAs<RecordType>()); 1473 } 1474 } 1475 1476 if (Successful) 1477 return Sema::TDK_Success; 1478 } 1479 1480 } 1481 1482 return Result; 1483 } 1484 1485 // T type::* 1486 // T T::* 1487 // T (type::*)() 1488 // type (T::*)() 1489 // type (type::*)(T) 1490 // type (T::*)(T) 1491 // T (type::*)(T) 1492 // T (T::*)() 1493 // T (T::*)(T) 1494 case Type::MemberPointer: { 1495 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param); 1496 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg); 1497 if (!MemPtrArg) 1498 return Sema::TDK_NonDeducedMismatch; 1499 1500 if (Sema::TemplateDeductionResult Result 1501 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1502 MemPtrParam->getPointeeType(), 1503 MemPtrArg->getPointeeType(), 1504 Info, Deduced, 1505 TDF & TDF_IgnoreQualifiers)) 1506 return Result; 1507 1508 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1509 QualType(MemPtrParam->getClass(), 0), 1510 QualType(MemPtrArg->getClass(), 0), 1511 Info, Deduced, 1512 TDF & TDF_IgnoreQualifiers); 1513 } 1514 1515 // (clang extension) 1516 // 1517 // type(^)(T) 1518 // T(^)() 1519 // T(^)(T) 1520 case Type::BlockPointer: { 1521 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param); 1522 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg); 1523 1524 if (!BlockPtrArg) 1525 return Sema::TDK_NonDeducedMismatch; 1526 1527 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1528 BlockPtrParam->getPointeeType(), 1529 BlockPtrArg->getPointeeType(), 1530 Info, Deduced, 0); 1531 } 1532 1533 // (clang extension) 1534 // 1535 // T __attribute__(((ext_vector_type(<integral constant>)))) 1536 case Type::ExtVector: { 1537 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param); 1538 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 1539 // Make sure that the vectors have the same number of elements. 1540 if (VectorParam->getNumElements() != VectorArg->getNumElements()) 1541 return Sema::TDK_NonDeducedMismatch; 1542 1543 // Perform deduction on the element types. 1544 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1545 VectorParam->getElementType(), 1546 VectorArg->getElementType(), 1547 Info, Deduced, TDF); 1548 } 1549 1550 if (const DependentSizedExtVectorType *VectorArg 1551 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 1552 // We can't check the number of elements, since the argument has a 1553 // dependent number of elements. This can only occur during partial 1554 // ordering. 1555 1556 // Perform deduction on the element types. 1557 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1558 VectorParam->getElementType(), 1559 VectorArg->getElementType(), 1560 Info, Deduced, TDF); 1561 } 1562 1563 return Sema::TDK_NonDeducedMismatch; 1564 } 1565 1566 // (clang extension) 1567 // 1568 // T __attribute__(((ext_vector_type(N)))) 1569 case Type::DependentSizedExtVector: { 1570 const DependentSizedExtVectorType *VectorParam 1571 = cast<DependentSizedExtVectorType>(Param); 1572 1573 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 1574 // Perform deduction on the element types. 1575 if (Sema::TemplateDeductionResult Result 1576 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1577 VectorParam->getElementType(), 1578 VectorArg->getElementType(), 1579 Info, Deduced, TDF)) 1580 return Result; 1581 1582 // Perform deduction on the vector size, if we can. 1583 NonTypeTemplateParmDecl *NTTP 1584 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 1585 if (!NTTP) 1586 return Sema::TDK_Success; 1587 1588 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 1589 ArgSize = VectorArg->getNumElements(); 1590 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy, 1591 false, Info, Deduced); 1592 } 1593 1594 if (const DependentSizedExtVectorType *VectorArg 1595 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 1596 // Perform deduction on the element types. 1597 if (Sema::TemplateDeductionResult Result 1598 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1599 VectorParam->getElementType(), 1600 VectorArg->getElementType(), 1601 Info, Deduced, TDF)) 1602 return Result; 1603 1604 // Perform deduction on the vector size, if we can. 1605 NonTypeTemplateParmDecl *NTTP 1606 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 1607 if (!NTTP) 1608 return Sema::TDK_Success; 1609 1610 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(), 1611 Info, Deduced); 1612 } 1613 1614 return Sema::TDK_NonDeducedMismatch; 1615 } 1616 1617 case Type::TypeOfExpr: 1618 case Type::TypeOf: 1619 case Type::DependentName: 1620 case Type::UnresolvedUsing: 1621 case Type::Decltype: 1622 case Type::UnaryTransform: 1623 case Type::Auto: 1624 case Type::DependentTemplateSpecialization: 1625 case Type::PackExpansion: 1626 // No template argument deduction for these types 1627 return Sema::TDK_Success; 1628 } 1629 1630 llvm_unreachable("Invalid Type Class!"); 1631} 1632 1633static Sema::TemplateDeductionResult 1634DeduceTemplateArguments(Sema &S, 1635 TemplateParameterList *TemplateParams, 1636 const TemplateArgument &Param, 1637 TemplateArgument Arg, 1638 TemplateDeductionInfo &Info, 1639 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1640 // If the template argument is a pack expansion, perform template argument 1641 // deduction against the pattern of that expansion. This only occurs during 1642 // partial ordering. 1643 if (Arg.isPackExpansion()) 1644 Arg = Arg.getPackExpansionPattern(); 1645 1646 switch (Param.getKind()) { 1647 case TemplateArgument::Null: 1648 llvm_unreachable("Null template argument in parameter list"); 1649 1650 case TemplateArgument::Type: 1651 if (Arg.getKind() == TemplateArgument::Type) 1652 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 1653 Param.getAsType(), 1654 Arg.getAsType(), 1655 Info, Deduced, 0); 1656 Info.FirstArg = Param; 1657 Info.SecondArg = Arg; 1658 return Sema::TDK_NonDeducedMismatch; 1659 1660 case TemplateArgument::Template: 1661 if (Arg.getKind() == TemplateArgument::Template) 1662 return DeduceTemplateArguments(S, TemplateParams, 1663 Param.getAsTemplate(), 1664 Arg.getAsTemplate(), Info, Deduced); 1665 Info.FirstArg = Param; 1666 Info.SecondArg = Arg; 1667 return Sema::TDK_NonDeducedMismatch; 1668 1669 case TemplateArgument::TemplateExpansion: 1670 llvm_unreachable("caller should handle pack expansions"); 1671 1672 case TemplateArgument::Declaration: 1673 if (Arg.getKind() == TemplateArgument::Declaration && 1674 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()) && 1675 Param.isDeclForReferenceParam() == Arg.isDeclForReferenceParam()) 1676 return Sema::TDK_Success; 1677 1678 Info.FirstArg = Param; 1679 Info.SecondArg = Arg; 1680 return Sema::TDK_NonDeducedMismatch; 1681 1682 case TemplateArgument::NullPtr: 1683 if (Arg.getKind() == TemplateArgument::NullPtr && 1684 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType())) 1685 return Sema::TDK_Success; 1686 1687 Info.FirstArg = Param; 1688 Info.SecondArg = Arg; 1689 return Sema::TDK_NonDeducedMismatch; 1690 1691 case TemplateArgument::Integral: 1692 if (Arg.getKind() == TemplateArgument::Integral) { 1693 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral())) 1694 return Sema::TDK_Success; 1695 1696 Info.FirstArg = Param; 1697 Info.SecondArg = Arg; 1698 return Sema::TDK_NonDeducedMismatch; 1699 } 1700 1701 if (Arg.getKind() == TemplateArgument::Expression) { 1702 Info.FirstArg = Param; 1703 Info.SecondArg = Arg; 1704 return Sema::TDK_NonDeducedMismatch; 1705 } 1706 1707 Info.FirstArg = Param; 1708 Info.SecondArg = Arg; 1709 return Sema::TDK_NonDeducedMismatch; 1710 1711 case TemplateArgument::Expression: { 1712 if (NonTypeTemplateParmDecl *NTTP 1713 = getDeducedParameterFromExpr(Param.getAsExpr())) { 1714 if (Arg.getKind() == TemplateArgument::Integral) 1715 return DeduceNonTypeTemplateArgument(S, NTTP, 1716 Arg.getAsIntegral(), 1717 Arg.getIntegralType(), 1718 /*ArrayBound=*/false, 1719 Info, Deduced); 1720 if (Arg.getKind() == TemplateArgument::Expression) 1721 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(), 1722 Info, Deduced); 1723 if (Arg.getKind() == TemplateArgument::Declaration) 1724 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(), 1725 Info, Deduced); 1726 1727 Info.FirstArg = Param; 1728 Info.SecondArg = Arg; 1729 return Sema::TDK_NonDeducedMismatch; 1730 } 1731 1732 // Can't deduce anything, but that's okay. 1733 return Sema::TDK_Success; 1734 } 1735 case TemplateArgument::Pack: 1736 llvm_unreachable("Argument packs should be expanded by the caller!"); 1737 } 1738 1739 llvm_unreachable("Invalid TemplateArgument Kind!"); 1740} 1741 1742/// \brief Determine whether there is a template argument to be used for 1743/// deduction. 1744/// 1745/// This routine "expands" argument packs in-place, overriding its input 1746/// parameters so that \c Args[ArgIdx] will be the available template argument. 1747/// 1748/// \returns true if there is another template argument (which will be at 1749/// \c Args[ArgIdx]), false otherwise. 1750static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args, 1751 unsigned &ArgIdx, 1752 unsigned &NumArgs) { 1753 if (ArgIdx == NumArgs) 1754 return false; 1755 1756 const TemplateArgument &Arg = Args[ArgIdx]; 1757 if (Arg.getKind() != TemplateArgument::Pack) 1758 return true; 1759 1760 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?"); 1761 Args = Arg.pack_begin(); 1762 NumArgs = Arg.pack_size(); 1763 ArgIdx = 0; 1764 return ArgIdx < NumArgs; 1765} 1766 1767/// \brief Determine whether the given set of template arguments has a pack 1768/// expansion that is not the last template argument. 1769static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args, 1770 unsigned NumArgs) { 1771 unsigned ArgIdx = 0; 1772 while (ArgIdx < NumArgs) { 1773 const TemplateArgument &Arg = Args[ArgIdx]; 1774 1775 // Unwrap argument packs. 1776 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) { 1777 Args = Arg.pack_begin(); 1778 NumArgs = Arg.pack_size(); 1779 ArgIdx = 0; 1780 continue; 1781 } 1782 1783 ++ArgIdx; 1784 if (ArgIdx == NumArgs) 1785 return false; 1786 1787 if (Arg.isPackExpansion()) 1788 return true; 1789 } 1790 1791 return false; 1792} 1793 1794static Sema::TemplateDeductionResult 1795DeduceTemplateArguments(Sema &S, 1796 TemplateParameterList *TemplateParams, 1797 const TemplateArgument *Params, unsigned NumParams, 1798 const TemplateArgument *Args, unsigned NumArgs, 1799 TemplateDeductionInfo &Info, 1800 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1801 // C++0x [temp.deduct.type]p9: 1802 // If the template argument list of P contains a pack expansion that is not 1803 // the last template argument, the entire template argument list is a 1804 // non-deduced context. 1805 if (hasPackExpansionBeforeEnd(Params, NumParams)) 1806 return Sema::TDK_Success; 1807 1808 // C++0x [temp.deduct.type]p9: 1809 // If P has a form that contains <T> or <i>, then each argument Pi of the 1810 // respective template argument list P is compared with the corresponding 1811 // argument Ai of the corresponding template argument list of A. 1812 unsigned ArgIdx = 0, ParamIdx = 0; 1813 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams); 1814 ++ParamIdx) { 1815 if (!Params[ParamIdx].isPackExpansion()) { 1816 // The simple case: deduce template arguments by matching Pi and Ai. 1817 1818 // Check whether we have enough arguments. 1819 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) 1820 return Sema::TDK_Success; 1821 1822 if (Args[ArgIdx].isPackExpansion()) { 1823 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here, 1824 // but applied to pack expansions that are template arguments. 1825 return Sema::TDK_MiscellaneousDeductionFailure; 1826 } 1827 1828 // Perform deduction for this Pi/Ai pair. 1829 if (Sema::TemplateDeductionResult Result 1830 = DeduceTemplateArguments(S, TemplateParams, 1831 Params[ParamIdx], Args[ArgIdx], 1832 Info, Deduced)) 1833 return Result; 1834 1835 // Move to the next argument. 1836 ++ArgIdx; 1837 continue; 1838 } 1839 1840 // The parameter is a pack expansion. 1841 1842 // C++0x [temp.deduct.type]p9: 1843 // If Pi is a pack expansion, then the pattern of Pi is compared with 1844 // each remaining argument in the template argument list of A. Each 1845 // comparison deduces template arguments for subsequent positions in the 1846 // template parameter packs expanded by Pi. 1847 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern(); 1848 1849 // Compute the set of template parameter indices that correspond to 1850 // parameter packs expanded by the pack expansion. 1851 SmallVector<unsigned, 2> PackIndices; 1852 { 1853 llvm::SmallBitVector SawIndices(TemplateParams->size()); 1854 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1855 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1856 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 1857 unsigned Depth, Index; 1858 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 1859 if (Depth == 0 && !SawIndices[Index]) { 1860 SawIndices[Index] = true; 1861 PackIndices.push_back(Index); 1862 } 1863 } 1864 } 1865 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?"); 1866 1867 // FIXME: If there are no remaining arguments, we can bail out early 1868 // and set any deduced parameter packs to an empty argument pack. 1869 // The latter part of this is a (minor) correctness issue. 1870 1871 // Save the deduced template arguments for each parameter pack expanded 1872 // by this pack expansion, then clear out the deduction. 1873 SmallVector<DeducedTemplateArgument, 2> 1874 SavedPacks(PackIndices.size()); 1875 NewlyDeducedPacksType NewlyDeducedPacks(PackIndices.size()); 1876 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks, 1877 NewlyDeducedPacks); 1878 1879 // Keep track of the deduced template arguments for each parameter pack 1880 // expanded by this pack expansion (the outer index) and for each 1881 // template argument (the inner SmallVectors). 1882 bool HasAnyArguments = false; 1883 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) { 1884 HasAnyArguments = true; 1885 1886 // Deduce template arguments from the pattern. 1887 if (Sema::TemplateDeductionResult Result 1888 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx], 1889 Info, Deduced)) 1890 return Result; 1891 1892 // Capture the deduced template arguments for each parameter pack expanded 1893 // by this pack expansion, add them to the list of arguments we've deduced 1894 // for that pack, then clear out the deduced argument. 1895 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 1896 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]]; 1897 if (!DeducedArg.isNull()) { 1898 NewlyDeducedPacks[I].push_back(DeducedArg); 1899 DeducedArg = DeducedTemplateArgument(); 1900 } 1901 } 1902 1903 ++ArgIdx; 1904 } 1905 1906 // Build argument packs for each of the parameter packs expanded by this 1907 // pack expansion. 1908 if (Sema::TemplateDeductionResult Result 1909 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments, 1910 Deduced, PackIndices, SavedPacks, 1911 NewlyDeducedPacks, Info)) 1912 return Result; 1913 } 1914 1915 return Sema::TDK_Success; 1916} 1917 1918static Sema::TemplateDeductionResult 1919DeduceTemplateArguments(Sema &S, 1920 TemplateParameterList *TemplateParams, 1921 const TemplateArgumentList &ParamList, 1922 const TemplateArgumentList &ArgList, 1923 TemplateDeductionInfo &Info, 1924 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 1925 return DeduceTemplateArguments(S, TemplateParams, 1926 ParamList.data(), ParamList.size(), 1927 ArgList.data(), ArgList.size(), 1928 Info, Deduced); 1929} 1930 1931/// \brief Determine whether two template arguments are the same. 1932static bool isSameTemplateArg(ASTContext &Context, 1933 const TemplateArgument &X, 1934 const TemplateArgument &Y) { 1935 if (X.getKind() != Y.getKind()) 1936 return false; 1937 1938 switch (X.getKind()) { 1939 case TemplateArgument::Null: 1940 llvm_unreachable("Comparing NULL template argument"); 1941 1942 case TemplateArgument::Type: 1943 return Context.getCanonicalType(X.getAsType()) == 1944 Context.getCanonicalType(Y.getAsType()); 1945 1946 case TemplateArgument::Declaration: 1947 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) && 1948 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam(); 1949 1950 case TemplateArgument::NullPtr: 1951 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()); 1952 1953 case TemplateArgument::Template: 1954 case TemplateArgument::TemplateExpansion: 1955 return Context.getCanonicalTemplateName( 1956 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() == 1957 Context.getCanonicalTemplateName( 1958 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer(); 1959 1960 case TemplateArgument::Integral: 1961 return X.getAsIntegral() == Y.getAsIntegral(); 1962 1963 case TemplateArgument::Expression: { 1964 llvm::FoldingSetNodeID XID, YID; 1965 X.getAsExpr()->Profile(XID, Context, true); 1966 Y.getAsExpr()->Profile(YID, Context, true); 1967 return XID == YID; 1968 } 1969 1970 case TemplateArgument::Pack: 1971 if (X.pack_size() != Y.pack_size()) 1972 return false; 1973 1974 for (TemplateArgument::pack_iterator XP = X.pack_begin(), 1975 XPEnd = X.pack_end(), 1976 YP = Y.pack_begin(); 1977 XP != XPEnd; ++XP, ++YP) 1978 if (!isSameTemplateArg(Context, *XP, *YP)) 1979 return false; 1980 1981 return true; 1982 } 1983 1984 llvm_unreachable("Invalid TemplateArgument Kind!"); 1985} 1986 1987/// \brief Allocate a TemplateArgumentLoc where all locations have 1988/// been initialized to the given location. 1989/// 1990/// \param S The semantic analysis object. 1991/// 1992/// \param Arg The template argument we are producing template argument 1993/// location information for. 1994/// 1995/// \param NTTPType For a declaration template argument, the type of 1996/// the non-type template parameter that corresponds to this template 1997/// argument. 1998/// 1999/// \param Loc The source location to use for the resulting template 2000/// argument. 2001static TemplateArgumentLoc 2002getTrivialTemplateArgumentLoc(Sema &S, 2003 const TemplateArgument &Arg, 2004 QualType NTTPType, 2005 SourceLocation Loc) { 2006 switch (Arg.getKind()) { 2007 case TemplateArgument::Null: 2008 llvm_unreachable("Can't get a NULL template argument here"); 2009 2010 case TemplateArgument::Type: 2011 return TemplateArgumentLoc(Arg, 2012 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc)); 2013 2014 case TemplateArgument::Declaration: { 2015 Expr *E 2016 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2017 .takeAs<Expr>(); 2018 return TemplateArgumentLoc(TemplateArgument(E), E); 2019 } 2020 2021 case TemplateArgument::NullPtr: { 2022 Expr *E 2023 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 2024 .takeAs<Expr>(); 2025 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true), 2026 E); 2027 } 2028 2029 case TemplateArgument::Integral: { 2030 Expr *E 2031 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>(); 2032 return TemplateArgumentLoc(TemplateArgument(E), E); 2033 } 2034 2035 case TemplateArgument::Template: 2036 case TemplateArgument::TemplateExpansion: { 2037 NestedNameSpecifierLocBuilder Builder; 2038 TemplateName Template = Arg.getAsTemplate(); 2039 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) 2040 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc); 2041 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2042 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc); 2043 2044 if (Arg.getKind() == TemplateArgument::Template) 2045 return TemplateArgumentLoc(Arg, 2046 Builder.getWithLocInContext(S.Context), 2047 Loc); 2048 2049 2050 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context), 2051 Loc, Loc); 2052 } 2053 2054 case TemplateArgument::Expression: 2055 return TemplateArgumentLoc(Arg, Arg.getAsExpr()); 2056 2057 case TemplateArgument::Pack: 2058 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); 2059 } 2060 2061 llvm_unreachable("Invalid TemplateArgument Kind!"); 2062} 2063 2064 2065/// \brief Convert the given deduced template argument and add it to the set of 2066/// fully-converted template arguments. 2067static bool 2068ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, 2069 DeducedTemplateArgument Arg, 2070 NamedDecl *Template, 2071 QualType NTTPType, 2072 unsigned ArgumentPackIndex, 2073 TemplateDeductionInfo &Info, 2074 bool InFunctionTemplate, 2075 SmallVectorImpl<TemplateArgument> &Output) { 2076 if (Arg.getKind() == TemplateArgument::Pack) { 2077 // This is a template argument pack, so check each of its arguments against 2078 // the template parameter. 2079 SmallVector<TemplateArgument, 2> PackedArgsBuilder; 2080 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(), 2081 PAEnd = Arg.pack_end(); 2082 PA != PAEnd; ++PA) { 2083 // When converting the deduced template argument, append it to the 2084 // general output list. We need to do this so that the template argument 2085 // checking logic has all of the prior template arguments available. 2086 DeducedTemplateArgument InnerArg(*PA); 2087 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); 2088 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template, 2089 NTTPType, PackedArgsBuilder.size(), 2090 Info, InFunctionTemplate, Output)) 2091 return true; 2092 2093 // Move the converted template argument into our argument pack. 2094 PackedArgsBuilder.push_back(Output.back()); 2095 Output.pop_back(); 2096 } 2097 2098 // Create the resulting argument pack. 2099 Output.push_back(TemplateArgument::CreatePackCopy(S.Context, 2100 PackedArgsBuilder.data(), 2101 PackedArgsBuilder.size())); 2102 return false; 2103 } 2104 2105 // Convert the deduced template argument into a template 2106 // argument that we can check, almost as if the user had written 2107 // the template argument explicitly. 2108 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType, 2109 Info.getLocation()); 2110 2111 // Check the template argument, converting it as necessary. 2112 return S.CheckTemplateArgument(Param, ArgLoc, 2113 Template, 2114 Template->getLocation(), 2115 Template->getSourceRange().getEnd(), 2116 ArgumentPackIndex, 2117 Output, 2118 InFunctionTemplate 2119 ? (Arg.wasDeducedFromArrayBound() 2120 ? Sema::CTAK_DeducedFromArrayBound 2121 : Sema::CTAK_Deduced) 2122 : Sema::CTAK_Specified); 2123} 2124 2125/// Complete template argument deduction for a class template partial 2126/// specialization. 2127static Sema::TemplateDeductionResult 2128FinishTemplateArgumentDeduction(Sema &S, 2129 ClassTemplatePartialSpecializationDecl *Partial, 2130 const TemplateArgumentList &TemplateArgs, 2131 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2132 TemplateDeductionInfo &Info) { 2133 // Unevaluated SFINAE context. 2134 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 2135 Sema::SFINAETrap Trap(S); 2136 2137 Sema::ContextRAII SavedContext(S, Partial); 2138 2139 // C++ [temp.deduct.type]p2: 2140 // [...] or if any template argument remains neither deduced nor 2141 // explicitly specified, template argument deduction fails. 2142 SmallVector<TemplateArgument, 4> Builder; 2143 TemplateParameterList *PartialParams = Partial->getTemplateParameters(); 2144 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) { 2145 NamedDecl *Param = PartialParams->getParam(I); 2146 if (Deduced[I].isNull()) { 2147 Info.Param = makeTemplateParameter(Param); 2148 return Sema::TDK_Incomplete; 2149 } 2150 2151 // We have deduced this argument, so it still needs to be 2152 // checked and converted. 2153 2154 // First, for a non-type template parameter type that is 2155 // initialized by a declaration, we need the type of the 2156 // corresponding non-type template parameter. 2157 QualType NTTPType; 2158 if (NonTypeTemplateParmDecl *NTTP 2159 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2160 NTTPType = NTTP->getType(); 2161 if (NTTPType->isDependentType()) { 2162 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2163 Builder.data(), Builder.size()); 2164 NTTPType = S.SubstType(NTTPType, 2165 MultiLevelTemplateArgumentList(TemplateArgs), 2166 NTTP->getLocation(), 2167 NTTP->getDeclName()); 2168 if (NTTPType.isNull()) { 2169 Info.Param = makeTemplateParameter(Param); 2170 // FIXME: These template arguments are temporary. Free them! 2171 Info.reset(TemplateArgumentList::CreateCopy(S.Context, 2172 Builder.data(), 2173 Builder.size())); 2174 return Sema::TDK_SubstitutionFailure; 2175 } 2176 } 2177 } 2178 2179 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], 2180 Partial, NTTPType, 0, Info, false, 2181 Builder)) { 2182 Info.Param = makeTemplateParameter(Param); 2183 // FIXME: These template arguments are temporary. Free them! 2184 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 2185 Builder.size())); 2186 return Sema::TDK_SubstitutionFailure; 2187 } 2188 } 2189 2190 // Form the template argument list from the deduced template arguments. 2191 TemplateArgumentList *DeducedArgumentList 2192 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 2193 Builder.size()); 2194 2195 Info.reset(DeducedArgumentList); 2196 2197 // Substitute the deduced template arguments into the template 2198 // arguments of the class template partial specialization, and 2199 // verify that the instantiated template arguments are both valid 2200 // and are equivalent to the template arguments originally provided 2201 // to the class template. 2202 LocalInstantiationScope InstScope(S); 2203 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate(); 2204 const TemplateArgumentLoc *PartialTemplateArgs 2205 = Partial->getTemplateArgsAsWritten(); 2206 2207 // Note that we don't provide the langle and rangle locations. 2208 TemplateArgumentListInfo InstArgs; 2209 2210 if (S.Subst(PartialTemplateArgs, 2211 Partial->getNumTemplateArgsAsWritten(), 2212 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 2213 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 2214 if (ParamIdx >= Partial->getTemplateParameters()->size()) 2215 ParamIdx = Partial->getTemplateParameters()->size() - 1; 2216 2217 Decl *Param 2218 = const_cast<NamedDecl *>( 2219 Partial->getTemplateParameters()->getParam(ParamIdx)); 2220 Info.Param = makeTemplateParameter(Param); 2221 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 2222 return Sema::TDK_SubstitutionFailure; 2223 } 2224 2225 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 2226 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(), 2227 InstArgs, false, ConvertedInstArgs)) 2228 return Sema::TDK_SubstitutionFailure; 2229 2230 TemplateParameterList *TemplateParams 2231 = ClassTemplate->getTemplateParameters(); 2232 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 2233 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 2234 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 2235 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 2236 Info.FirstArg = TemplateArgs[I]; 2237 Info.SecondArg = InstArg; 2238 return Sema::TDK_NonDeducedMismatch; 2239 } 2240 } 2241 2242 if (Trap.hasErrorOccurred()) 2243 return Sema::TDK_SubstitutionFailure; 2244 2245 return Sema::TDK_Success; 2246} 2247 2248/// \brief Perform template argument deduction to determine whether 2249/// the given template arguments match the given class template 2250/// partial specialization per C++ [temp.class.spec.match]. 2251Sema::TemplateDeductionResult 2252Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 2253 const TemplateArgumentList &TemplateArgs, 2254 TemplateDeductionInfo &Info) { 2255 if (Partial->isInvalidDecl()) 2256 return TDK_Invalid; 2257 2258 // C++ [temp.class.spec.match]p2: 2259 // A partial specialization matches a given actual template 2260 // argument list if the template arguments of the partial 2261 // specialization can be deduced from the actual template argument 2262 // list (14.8.2). 2263 2264 // Unevaluated SFINAE context. 2265 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2266 SFINAETrap Trap(*this); 2267 2268 SmallVector<DeducedTemplateArgument, 4> Deduced; 2269 Deduced.resize(Partial->getTemplateParameters()->size()); 2270 if (TemplateDeductionResult Result 2271 = ::DeduceTemplateArguments(*this, 2272 Partial->getTemplateParameters(), 2273 Partial->getTemplateArgs(), 2274 TemplateArgs, Info, Deduced)) 2275 return Result; 2276 2277 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2278 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial, 2279 DeducedArgs, Info); 2280 if (Inst) 2281 return TDK_InstantiationDepth; 2282 2283 if (Trap.hasErrorOccurred()) 2284 return Sema::TDK_SubstitutionFailure; 2285 2286 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs, 2287 Deduced, Info); 2288} 2289 2290/// \brief Determine whether the given type T is a simple-template-id type. 2291static bool isSimpleTemplateIdType(QualType T) { 2292 if (const TemplateSpecializationType *Spec 2293 = T->getAs<TemplateSpecializationType>()) 2294 return Spec->getTemplateName().getAsTemplateDecl() != 0; 2295 2296 return false; 2297} 2298 2299/// \brief Substitute the explicitly-provided template arguments into the 2300/// given function template according to C++ [temp.arg.explicit]. 2301/// 2302/// \param FunctionTemplate the function template into which the explicit 2303/// template arguments will be substituted. 2304/// 2305/// \param ExplicitTemplateArgs the explicitly-specified template 2306/// arguments. 2307/// 2308/// \param Deduced the deduced template arguments, which will be populated 2309/// with the converted and checked explicit template arguments. 2310/// 2311/// \param ParamTypes will be populated with the instantiated function 2312/// parameters. 2313/// 2314/// \param FunctionType if non-NULL, the result type of the function template 2315/// will also be instantiated and the pointed-to value will be updated with 2316/// the instantiated function type. 2317/// 2318/// \param Info if substitution fails for any reason, this object will be 2319/// populated with more information about the failure. 2320/// 2321/// \returns TDK_Success if substitution was successful, or some failure 2322/// condition. 2323Sema::TemplateDeductionResult 2324Sema::SubstituteExplicitTemplateArguments( 2325 FunctionTemplateDecl *FunctionTemplate, 2326 TemplateArgumentListInfo &ExplicitTemplateArgs, 2327 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2328 SmallVectorImpl<QualType> &ParamTypes, 2329 QualType *FunctionType, 2330 TemplateDeductionInfo &Info) { 2331 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 2332 TemplateParameterList *TemplateParams 2333 = FunctionTemplate->getTemplateParameters(); 2334 2335 if (ExplicitTemplateArgs.size() == 0) { 2336 // No arguments to substitute; just copy over the parameter types and 2337 // fill in the function type. 2338 for (FunctionDecl::param_iterator P = Function->param_begin(), 2339 PEnd = Function->param_end(); 2340 P != PEnd; 2341 ++P) 2342 ParamTypes.push_back((*P)->getType()); 2343 2344 if (FunctionType) 2345 *FunctionType = Function->getType(); 2346 return TDK_Success; 2347 } 2348 2349 // Unevaluated SFINAE context. 2350 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2351 SFINAETrap Trap(*this); 2352 2353 // C++ [temp.arg.explicit]p3: 2354 // Template arguments that are present shall be specified in the 2355 // declaration order of their corresponding template-parameters. The 2356 // template argument list shall not specify more template-arguments than 2357 // there are corresponding template-parameters. 2358 SmallVector<TemplateArgument, 4> Builder; 2359 2360 // Enter a new template instantiation context where we check the 2361 // explicitly-specified template arguments against this function template, 2362 // and then substitute them into the function parameter types. 2363 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2364 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(), 2365 FunctionTemplate, DeducedArgs, 2366 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution, 2367 Info); 2368 if (Inst) 2369 return TDK_InstantiationDepth; 2370 2371 if (CheckTemplateArgumentList(FunctionTemplate, 2372 SourceLocation(), 2373 ExplicitTemplateArgs, 2374 true, 2375 Builder) || Trap.hasErrorOccurred()) { 2376 unsigned Index = Builder.size(); 2377 if (Index >= TemplateParams->size()) 2378 Index = TemplateParams->size() - 1; 2379 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 2380 return TDK_InvalidExplicitArguments; 2381 } 2382 2383 // Form the template argument list from the explicitly-specified 2384 // template arguments. 2385 TemplateArgumentList *ExplicitArgumentList 2386 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 2387 Info.reset(ExplicitArgumentList); 2388 2389 // Template argument deduction and the final substitution should be 2390 // done in the context of the templated declaration. Explicit 2391 // argument substitution, on the other hand, needs to happen in the 2392 // calling context. 2393 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 2394 2395 // If we deduced template arguments for a template parameter pack, 2396 // note that the template argument pack is partially substituted and record 2397 // the explicit template arguments. They'll be used as part of deduction 2398 // for this template parameter pack. 2399 for (unsigned I = 0, N = Builder.size(); I != N; ++I) { 2400 const TemplateArgument &Arg = Builder[I]; 2401 if (Arg.getKind() == TemplateArgument::Pack) { 2402 CurrentInstantiationScope->SetPartiallySubstitutedPack( 2403 TemplateParams->getParam(I), 2404 Arg.pack_begin(), 2405 Arg.pack_size()); 2406 break; 2407 } 2408 } 2409 2410 const FunctionProtoType *Proto 2411 = Function->getType()->getAs<FunctionProtoType>(); 2412 assert(Proto && "Function template does not have a prototype?"); 2413 2414 // Instantiate the types of each of the function parameters given the 2415 // explicitly-specified template arguments. If the function has a trailing 2416 // return type, substitute it after the arguments to ensure we substitute 2417 // in lexical order. 2418 if (Proto->hasTrailingReturn()) { 2419 if (SubstParmTypes(Function->getLocation(), 2420 Function->param_begin(), Function->getNumParams(), 2421 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 2422 ParamTypes)) 2423 return TDK_SubstitutionFailure; 2424 } 2425 2426 // Instantiate the return type. 2427 // FIXME: exception-specifications? 2428 QualType ResultType; 2429 { 2430 // C++11 [expr.prim.general]p3: 2431 // If a declaration declares a member function or member function 2432 // template of a class X, the expression this is a prvalue of type 2433 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 2434 // and the end of the function-definition, member-declarator, or 2435 // declarator. 2436 unsigned ThisTypeQuals = 0; 2437 CXXRecordDecl *ThisContext = 0; 2438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 2439 ThisContext = Method->getParent(); 2440 ThisTypeQuals = Method->getTypeQualifiers(); 2441 } 2442 2443 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 2444 getLangOpts().CPlusPlus11); 2445 2446 ResultType = SubstType(Proto->getResultType(), 2447 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 2448 Function->getTypeSpecStartLoc(), 2449 Function->getDeclName()); 2450 if (ResultType.isNull() || Trap.hasErrorOccurred()) 2451 return TDK_SubstitutionFailure; 2452 } 2453 2454 // Instantiate the types of each of the function parameters given the 2455 // explicitly-specified template arguments if we didn't do so earlier. 2456 if (!Proto->hasTrailingReturn() && 2457 SubstParmTypes(Function->getLocation(), 2458 Function->param_begin(), Function->getNumParams(), 2459 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 2460 ParamTypes)) 2461 return TDK_SubstitutionFailure; 2462 2463 if (FunctionType) { 2464 *FunctionType = BuildFunctionType(ResultType, ParamTypes, 2465 Function->getLocation(), 2466 Function->getDeclName(), 2467 Proto->getExtProtoInfo()); 2468 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 2469 return TDK_SubstitutionFailure; 2470 } 2471 2472 // C++ [temp.arg.explicit]p2: 2473 // Trailing template arguments that can be deduced (14.8.2) may be 2474 // omitted from the list of explicit template-arguments. If all of the 2475 // template arguments can be deduced, they may all be omitted; in this 2476 // case, the empty template argument list <> itself may also be omitted. 2477 // 2478 // Take all of the explicitly-specified arguments and put them into 2479 // the set of deduced template arguments. Explicitly-specified 2480 // parameter packs, however, will be set to NULL since the deduction 2481 // mechanisms handle explicitly-specified argument packs directly. 2482 Deduced.reserve(TemplateParams->size()); 2483 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 2484 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 2485 if (Arg.getKind() == TemplateArgument::Pack) 2486 Deduced.push_back(DeducedTemplateArgument()); 2487 else 2488 Deduced.push_back(Arg); 2489 } 2490 2491 return TDK_Success; 2492} 2493 2494/// \brief Check whether the deduced argument type for a call to a function 2495/// template matches the actual argument type per C++ [temp.deduct.call]p4. 2496static bool 2497CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg, 2498 QualType DeducedA) { 2499 ASTContext &Context = S.Context; 2500 2501 QualType A = OriginalArg.OriginalArgType; 2502 QualType OriginalParamType = OriginalArg.OriginalParamType; 2503 2504 // Check for type equality (top-level cv-qualifiers are ignored). 2505 if (Context.hasSameUnqualifiedType(A, DeducedA)) 2506 return false; 2507 2508 // Strip off references on the argument types; they aren't needed for 2509 // the following checks. 2510 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 2511 DeducedA = DeducedARef->getPointeeType(); 2512 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 2513 A = ARef->getPointeeType(); 2514 2515 // C++ [temp.deduct.call]p4: 2516 // [...] However, there are three cases that allow a difference: 2517 // - If the original P is a reference type, the deduced A (i.e., the 2518 // type referred to by the reference) can be more cv-qualified than 2519 // the transformed A. 2520 if (const ReferenceType *OriginalParamRef 2521 = OriginalParamType->getAs<ReferenceType>()) { 2522 // We don't want to keep the reference around any more. 2523 OriginalParamType = OriginalParamRef->getPointeeType(); 2524 2525 Qualifiers AQuals = A.getQualifiers(); 2526 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 2527 2528 // Under Objective-C++ ARC, the deduced type may have implicitly been 2529 // given strong lifetime. If so, update the original qualifiers to 2530 // include this strong lifetime. 2531 if (S.getLangOpts().ObjCAutoRefCount && 2532 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong && 2533 AQuals.getObjCLifetime() == Qualifiers::OCL_None) { 2534 AQuals.setObjCLifetime(Qualifiers::OCL_Strong); 2535 } 2536 2537 if (AQuals == DeducedAQuals) { 2538 // Qualifiers match; there's nothing to do. 2539 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 2540 return true; 2541 } else { 2542 // Qualifiers are compatible, so have the argument type adopt the 2543 // deduced argument type's qualifiers as if we had performed the 2544 // qualification conversion. 2545 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 2546 } 2547 } 2548 2549 // - The transformed A can be another pointer or pointer to member 2550 // type that can be converted to the deduced A via a qualification 2551 // conversion. 2552 // 2553 // Also allow conversions which merely strip [[noreturn]] from function types 2554 // (recursively) as an extension. 2555 // FIXME: Currently, this doesn't place nicely with qualfication conversions. 2556 bool ObjCLifetimeConversion = false; 2557 QualType ResultTy; 2558 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 2559 (S.IsQualificationConversion(A, DeducedA, false, 2560 ObjCLifetimeConversion) || 2561 S.IsNoReturnConversion(A, DeducedA, ResultTy))) 2562 return false; 2563 2564 2565 // - If P is a class and P has the form simple-template-id, then the 2566 // transformed A can be a derived class of the deduced A. [...] 2567 // [...] Likewise, if P is a pointer to a class of the form 2568 // simple-template-id, the transformed A can be a pointer to a 2569 // derived class pointed to by the deduced A. 2570 if (const PointerType *OriginalParamPtr 2571 = OriginalParamType->getAs<PointerType>()) { 2572 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 2573 if (const PointerType *APtr = A->getAs<PointerType>()) { 2574 if (A->getPointeeType()->isRecordType()) { 2575 OriginalParamType = OriginalParamPtr->getPointeeType(); 2576 DeducedA = DeducedAPtr->getPointeeType(); 2577 A = APtr->getPointeeType(); 2578 } 2579 } 2580 } 2581 } 2582 2583 if (Context.hasSameUnqualifiedType(A, DeducedA)) 2584 return false; 2585 2586 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 2587 S.IsDerivedFrom(A, DeducedA)) 2588 return false; 2589 2590 return true; 2591} 2592 2593/// \brief Finish template argument deduction for a function template, 2594/// checking the deduced template arguments for completeness and forming 2595/// the function template specialization. 2596/// 2597/// \param OriginalCallArgs If non-NULL, the original call arguments against 2598/// which the deduced argument types should be compared. 2599Sema::TemplateDeductionResult 2600Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 2601 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 2602 unsigned NumExplicitlySpecified, 2603 FunctionDecl *&Specialization, 2604 TemplateDeductionInfo &Info, 2605 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) { 2606 TemplateParameterList *TemplateParams 2607 = FunctionTemplate->getTemplateParameters(); 2608 2609 // Unevaluated SFINAE context. 2610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 2611 SFINAETrap Trap(*this); 2612 2613 // Enter a new template instantiation context while we instantiate the 2614 // actual function declaration. 2615 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end()); 2616 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(), 2617 FunctionTemplate, DeducedArgs, 2618 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution, 2619 Info); 2620 if (Inst) 2621 return TDK_InstantiationDepth; 2622 2623 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 2624 2625 // C++ [temp.deduct.type]p2: 2626 // [...] or if any template argument remains neither deduced nor 2627 // explicitly specified, template argument deduction fails. 2628 SmallVector<TemplateArgument, 4> Builder; 2629 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2630 NamedDecl *Param = TemplateParams->getParam(I); 2631 2632 if (!Deduced[I].isNull()) { 2633 if (I < NumExplicitlySpecified) { 2634 // We have already fully type-checked and converted this 2635 // argument, because it was explicitly-specified. Just record the 2636 // presence of this argument. 2637 Builder.push_back(Deduced[I]); 2638 continue; 2639 } 2640 2641 // We have deduced this argument, so it still needs to be 2642 // checked and converted. 2643 2644 // First, for a non-type template parameter type that is 2645 // initialized by a declaration, we need the type of the 2646 // corresponding non-type template parameter. 2647 QualType NTTPType; 2648 if (NonTypeTemplateParmDecl *NTTP 2649 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2650 NTTPType = NTTP->getType(); 2651 if (NTTPType->isDependentType()) { 2652 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2653 Builder.data(), Builder.size()); 2654 NTTPType = SubstType(NTTPType, 2655 MultiLevelTemplateArgumentList(TemplateArgs), 2656 NTTP->getLocation(), 2657 NTTP->getDeclName()); 2658 if (NTTPType.isNull()) { 2659 Info.Param = makeTemplateParameter(Param); 2660 // FIXME: These template arguments are temporary. Free them! 2661 Info.reset(TemplateArgumentList::CreateCopy(Context, 2662 Builder.data(), 2663 Builder.size())); 2664 return TDK_SubstitutionFailure; 2665 } 2666 } 2667 } 2668 2669 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I], 2670 FunctionTemplate, NTTPType, 0, Info, 2671 true, Builder)) { 2672 Info.Param = makeTemplateParameter(Param); 2673 // FIXME: These template arguments are temporary. Free them! 2674 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 2675 Builder.size())); 2676 return TDK_SubstitutionFailure; 2677 } 2678 2679 continue; 2680 } 2681 2682 // C++0x [temp.arg.explicit]p3: 2683 // A trailing template parameter pack (14.5.3) not otherwise deduced will 2684 // be deduced to an empty sequence of template arguments. 2685 // FIXME: Where did the word "trailing" come from? 2686 if (Param->isTemplateParameterPack()) { 2687 // We may have had explicitly-specified template arguments for this 2688 // template parameter pack. If so, our empty deduction extends the 2689 // explicitly-specified set (C++0x [temp.arg.explicit]p9). 2690 const TemplateArgument *ExplicitArgs; 2691 unsigned NumExplicitArgs; 2692 if (CurrentInstantiationScope && 2693 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs, 2694 &NumExplicitArgs) 2695 == Param) { 2696 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs)); 2697 2698 // Forget the partially-substituted pack; it's substitution is now 2699 // complete. 2700 CurrentInstantiationScope->ResetPartiallySubstitutedPack(); 2701 } else { 2702 Builder.push_back(TemplateArgument::getEmptyPack()); 2703 } 2704 continue; 2705 } 2706 2707 // Substitute into the default template argument, if available. 2708 bool HasDefaultArg = false; 2709 TemplateArgumentLoc DefArg 2710 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate, 2711 FunctionTemplate->getLocation(), 2712 FunctionTemplate->getSourceRange().getEnd(), 2713 Param, 2714 Builder, HasDefaultArg); 2715 2716 // If there was no default argument, deduction is incomplete. 2717 if (DefArg.getArgument().isNull()) { 2718 Info.Param = makeTemplateParameter( 2719 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2720 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 2721 Builder.size())); 2722 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete; 2723 } 2724 2725 // Check whether we can actually use the default argument. 2726 if (CheckTemplateArgument(Param, DefArg, 2727 FunctionTemplate, 2728 FunctionTemplate->getLocation(), 2729 FunctionTemplate->getSourceRange().getEnd(), 2730 0, Builder, 2731 CTAK_Specified)) { 2732 Info.Param = makeTemplateParameter( 2733 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 2734 // FIXME: These template arguments are temporary. Free them! 2735 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 2736 Builder.size())); 2737 return TDK_SubstitutionFailure; 2738 } 2739 2740 // If we get here, we successfully used the default template argument. 2741 } 2742 2743 // Form the template argument list from the deduced template arguments. 2744 TemplateArgumentList *DeducedArgumentList 2745 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 2746 Info.reset(DeducedArgumentList); 2747 2748 // Substitute the deduced template arguments into the function template 2749 // declaration to produce the function template specialization. 2750 DeclContext *Owner = FunctionTemplate->getDeclContext(); 2751 if (FunctionTemplate->getFriendObjectKind()) 2752 Owner = FunctionTemplate->getLexicalDeclContext(); 2753 Specialization = cast_or_null<FunctionDecl>( 2754 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, 2755 MultiLevelTemplateArgumentList(*DeducedArgumentList))); 2756 if (!Specialization || Specialization->isInvalidDecl()) 2757 return TDK_SubstitutionFailure; 2758 2759 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() == 2760 FunctionTemplate->getCanonicalDecl()); 2761 2762 // If the template argument list is owned by the function template 2763 // specialization, release it. 2764 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 2765 !Trap.hasErrorOccurred()) 2766 Info.take(); 2767 2768 // There may have been an error that did not prevent us from constructing a 2769 // declaration. Mark the declaration invalid and return with a substitution 2770 // failure. 2771 if (Trap.hasErrorOccurred()) { 2772 Specialization->setInvalidDecl(true); 2773 return TDK_SubstitutionFailure; 2774 } 2775 2776 if (OriginalCallArgs) { 2777 // C++ [temp.deduct.call]p4: 2778 // In general, the deduction process attempts to find template argument 2779 // values that will make the deduced A identical to A (after the type A 2780 // is transformed as described above). [...] 2781 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { 2782 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; 2783 unsigned ParamIdx = OriginalArg.ArgIdx; 2784 2785 if (ParamIdx >= Specialization->getNumParams()) 2786 continue; 2787 2788 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType(); 2789 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) 2790 return Sema::TDK_SubstitutionFailure; 2791 } 2792 } 2793 2794 // If we suppressed any diagnostics while performing template argument 2795 // deduction, and if we haven't already instantiated this declaration, 2796 // keep track of these diagnostics. They'll be emitted if this specialization 2797 // is actually used. 2798 if (Info.diag_begin() != Info.diag_end()) { 2799 SuppressedDiagnosticsMap::iterator 2800 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl()); 2801 if (Pos == SuppressedDiagnostics.end()) 2802 SuppressedDiagnostics[Specialization->getCanonicalDecl()] 2803 .append(Info.diag_begin(), Info.diag_end()); 2804 } 2805 2806 return TDK_Success; 2807} 2808 2809/// Gets the type of a function for template-argument-deducton 2810/// purposes when it's considered as part of an overload set. 2811static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, 2812 FunctionDecl *Fn) { 2813 // We may need to deduce the return type of the function now. 2814 if (S.getLangOpts().CPlusPlus1y && Fn->getResultType()->isUndeducedType() && 2815 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/false)) 2816 return QualType(); 2817 2818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 2819 if (Method->isInstance()) { 2820 // An instance method that's referenced in a form that doesn't 2821 // look like a member pointer is just invalid. 2822 if (!R.HasFormOfMemberPointer) return QualType(); 2823 2824 return S.Context.getMemberPointerType(Fn->getType(), 2825 S.Context.getTypeDeclType(Method->getParent()).getTypePtr()); 2826 } 2827 2828 if (!R.IsAddressOfOperand) return Fn->getType(); 2829 return S.Context.getPointerType(Fn->getType()); 2830} 2831 2832/// Apply the deduction rules for overload sets. 2833/// 2834/// \return the null type if this argument should be treated as an 2835/// undeduced context 2836static QualType 2837ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, 2838 Expr *Arg, QualType ParamType, 2839 bool ParamWasReference) { 2840 2841 OverloadExpr::FindResult R = OverloadExpr::find(Arg); 2842 2843 OverloadExpr *Ovl = R.Expression; 2844 2845 // C++0x [temp.deduct.call]p4 2846 unsigned TDF = 0; 2847 if (ParamWasReference) 2848 TDF |= TDF_ParamWithReferenceType; 2849 if (R.IsAddressOfOperand) 2850 TDF |= TDF_IgnoreQualifiers; 2851 2852 // C++0x [temp.deduct.call]p6: 2853 // When P is a function type, pointer to function type, or pointer 2854 // to member function type: 2855 2856 if (!ParamType->isFunctionType() && 2857 !ParamType->isFunctionPointerType() && 2858 !ParamType->isMemberFunctionPointerType()) { 2859 if (Ovl->hasExplicitTemplateArgs()) { 2860 // But we can still look for an explicit specialization. 2861 if (FunctionDecl *ExplicitSpec 2862 = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) 2863 return GetTypeOfFunction(S, R, ExplicitSpec); 2864 } 2865 2866 return QualType(); 2867 } 2868 2869 // Gather the explicit template arguments, if any. 2870 TemplateArgumentListInfo ExplicitTemplateArgs; 2871 if (Ovl->hasExplicitTemplateArgs()) 2872 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 2873 QualType Match; 2874 for (UnresolvedSetIterator I = Ovl->decls_begin(), 2875 E = Ovl->decls_end(); I != E; ++I) { 2876 NamedDecl *D = (*I)->getUnderlyingDecl(); 2877 2878 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 2879 // - If the argument is an overload set containing one or more 2880 // function templates, the parameter is treated as a 2881 // non-deduced context. 2882 if (!Ovl->hasExplicitTemplateArgs()) 2883 return QualType(); 2884 2885 // Otherwise, see if we can resolve a function type 2886 FunctionDecl *Specialization = 0; 2887 TemplateDeductionInfo Info(Ovl->getNameLoc()); 2888 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs, 2889 Specialization, Info)) 2890 continue; 2891 2892 D = Specialization; 2893 } 2894 2895 FunctionDecl *Fn = cast<FunctionDecl>(D); 2896 QualType ArgType = GetTypeOfFunction(S, R, Fn); 2897 if (ArgType.isNull()) continue; 2898 2899 // Function-to-pointer conversion. 2900 if (!ParamWasReference && ParamType->isPointerType() && 2901 ArgType->isFunctionType()) 2902 ArgType = S.Context.getPointerType(ArgType); 2903 2904 // - If the argument is an overload set (not containing function 2905 // templates), trial argument deduction is attempted using each 2906 // of the members of the set. If deduction succeeds for only one 2907 // of the overload set members, that member is used as the 2908 // argument value for the deduction. If deduction succeeds for 2909 // more than one member of the overload set the parameter is 2910 // treated as a non-deduced context. 2911 2912 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: 2913 // Type deduction is done independently for each P/A pair, and 2914 // the deduced template argument values are then combined. 2915 // So we do not reject deductions which were made elsewhere. 2916 SmallVector<DeducedTemplateArgument, 8> 2917 Deduced(TemplateParams->size()); 2918 TemplateDeductionInfo Info(Ovl->getNameLoc()); 2919 Sema::TemplateDeductionResult Result 2920 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 2921 ArgType, Info, Deduced, TDF); 2922 if (Result) continue; 2923 if (!Match.isNull()) return QualType(); 2924 Match = ArgType; 2925 } 2926 2927 return Match; 2928} 2929 2930/// \brief Perform the adjustments to the parameter and argument types 2931/// described in C++ [temp.deduct.call]. 2932/// 2933/// \returns true if the caller should not attempt to perform any template 2934/// argument deduction based on this P/A pair because the argument is an 2935/// overloaded function set that could not be resolved. 2936static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, 2937 TemplateParameterList *TemplateParams, 2938 QualType &ParamType, 2939 QualType &ArgType, 2940 Expr *Arg, 2941 unsigned &TDF) { 2942 // C++0x [temp.deduct.call]p3: 2943 // If P is a cv-qualified type, the top level cv-qualifiers of P's type 2944 // are ignored for type deduction. 2945 if (ParamType.hasQualifiers()) 2946 ParamType = ParamType.getUnqualifiedType(); 2947 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); 2948 if (ParamRefType) { 2949 QualType PointeeType = ParamRefType->getPointeeType(); 2950 2951 // If the argument has incomplete array type, try to complete its type. 2952 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0)) 2953 ArgType = Arg->getType(); 2954 2955 // [C++0x] If P is an rvalue reference to a cv-unqualified 2956 // template parameter and the argument is an lvalue, the type 2957 // "lvalue reference to A" is used in place of A for type 2958 // deduction. 2959 if (isa<RValueReferenceType>(ParamType)) { 2960 if (!PointeeType.getQualifiers() && 2961 isa<TemplateTypeParmType>(PointeeType) && 2962 Arg->Classify(S.Context).isLValue() && 2963 Arg->getType() != S.Context.OverloadTy && 2964 Arg->getType() != S.Context.BoundMemberTy) 2965 ArgType = S.Context.getLValueReferenceType(ArgType); 2966 } 2967 2968 // [...] If P is a reference type, the type referred to by P is used 2969 // for type deduction. 2970 ParamType = PointeeType; 2971 } 2972 2973 // Overload sets usually make this parameter an undeduced 2974 // context, but there are sometimes special circumstances. 2975 if (ArgType == S.Context.OverloadTy) { 2976 ArgType = ResolveOverloadForDeduction(S, TemplateParams, 2977 Arg, ParamType, 2978 ParamRefType != 0); 2979 if (ArgType.isNull()) 2980 return true; 2981 } 2982 2983 if (ParamRefType) { 2984 // C++0x [temp.deduct.call]p3: 2985 // [...] If P is of the form T&&, where T is a template parameter, and 2986 // the argument is an lvalue, the type A& is used in place of A for 2987 // type deduction. 2988 if (ParamRefType->isRValueReferenceType() && 2989 ParamRefType->getAs<TemplateTypeParmType>() && 2990 Arg->isLValue()) 2991 ArgType = S.Context.getLValueReferenceType(ArgType); 2992 } else { 2993 // C++ [temp.deduct.call]p2: 2994 // If P is not a reference type: 2995 // - If A is an array type, the pointer type produced by the 2996 // array-to-pointer standard conversion (4.2) is used in place of 2997 // A for type deduction; otherwise, 2998 if (ArgType->isArrayType()) 2999 ArgType = S.Context.getArrayDecayedType(ArgType); 3000 // - If A is a function type, the pointer type produced by the 3001 // function-to-pointer standard conversion (4.3) is used in place 3002 // of A for type deduction; otherwise, 3003 else if (ArgType->isFunctionType()) 3004 ArgType = S.Context.getPointerType(ArgType); 3005 else { 3006 // - If A is a cv-qualified type, the top level cv-qualifiers of A's 3007 // type are ignored for type deduction. 3008 ArgType = ArgType.getUnqualifiedType(); 3009 } 3010 } 3011 3012 // C++0x [temp.deduct.call]p4: 3013 // In general, the deduction process attempts to find template argument 3014 // values that will make the deduced A identical to A (after the type A 3015 // is transformed as described above). [...] 3016 TDF = TDF_SkipNonDependent; 3017 3018 // - If the original P is a reference type, the deduced A (i.e., the 3019 // type referred to by the reference) can be more cv-qualified than 3020 // the transformed A. 3021 if (ParamRefType) 3022 TDF |= TDF_ParamWithReferenceType; 3023 // - The transformed A can be another pointer or pointer to member 3024 // type that can be converted to the deduced A via a qualification 3025 // conversion (4.4). 3026 if (ArgType->isPointerType() || ArgType->isMemberPointerType() || 3027 ArgType->isObjCObjectPointerType()) 3028 TDF |= TDF_IgnoreQualifiers; 3029 // - If P is a class and P has the form simple-template-id, then the 3030 // transformed A can be a derived class of the deduced A. Likewise, 3031 // if P is a pointer to a class of the form simple-template-id, the 3032 // transformed A can be a pointer to a derived class pointed to by 3033 // the deduced A. 3034 if (isSimpleTemplateIdType(ParamType) || 3035 (isa<PointerType>(ParamType) && 3036 isSimpleTemplateIdType( 3037 ParamType->getAs<PointerType>()->getPointeeType()))) 3038 TDF |= TDF_DerivedClass; 3039 3040 return false; 3041} 3042 3043static bool hasDeducibleTemplateParameters(Sema &S, 3044 FunctionTemplateDecl *FunctionTemplate, 3045 QualType T); 3046 3047/// \brief Perform template argument deduction by matching a parameter type 3048/// against a single expression, where the expression is an element of 3049/// an initializer list that was originally matched against a parameter 3050/// of type \c initializer_list\<ParamType\>. 3051static Sema::TemplateDeductionResult 3052DeduceTemplateArgumentByListElement(Sema &S, 3053 TemplateParameterList *TemplateParams, 3054 QualType ParamType, Expr *Arg, 3055 TemplateDeductionInfo &Info, 3056 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 3057 unsigned TDF) { 3058 // Handle the case where an init list contains another init list as the 3059 // element. 3060 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 3061 QualType X; 3062 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X)) 3063 return Sema::TDK_Success; // Just ignore this expression. 3064 3065 // Recurse down into the init list. 3066 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 3067 if (Sema::TemplateDeductionResult Result = 3068 DeduceTemplateArgumentByListElement(S, TemplateParams, X, 3069 ILE->getInit(i), 3070 Info, Deduced, TDF)) 3071 return Result; 3072 } 3073 return Sema::TDK_Success; 3074 } 3075 3076 // For all other cases, just match by type. 3077 QualType ArgType = Arg->getType(); 3078 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType, 3079 ArgType, Arg, TDF)) { 3080 Info.Expression = Arg; 3081 return Sema::TDK_FailedOverloadResolution; 3082 } 3083 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 3084 ArgType, Info, Deduced, TDF); 3085} 3086 3087/// \brief Perform template argument deduction from a function call 3088/// (C++ [temp.deduct.call]). 3089/// 3090/// \param FunctionTemplate the function template for which we are performing 3091/// template argument deduction. 3092/// 3093/// \param ExplicitTemplateArgs the explicit template arguments provided 3094/// for this call. 3095/// 3096/// \param Args the function call arguments 3097/// 3098/// \param Specialization if template argument deduction was successful, 3099/// this will be set to the function template specialization produced by 3100/// template argument deduction. 3101/// 3102/// \param Info the argument will be updated to provide additional information 3103/// about template argument deduction. 3104/// 3105/// \returns the result of template argument deduction. 3106Sema::TemplateDeductionResult 3107Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 3108 TemplateArgumentListInfo *ExplicitTemplateArgs, 3109 llvm::ArrayRef<Expr *> Args, 3110 FunctionDecl *&Specialization, 3111 TemplateDeductionInfo &Info) { 3112 if (FunctionTemplate->isInvalidDecl()) 3113 return TDK_Invalid; 3114 3115 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3116 3117 // C++ [temp.deduct.call]p1: 3118 // Template argument deduction is done by comparing each function template 3119 // parameter type (call it P) with the type of the corresponding argument 3120 // of the call (call it A) as described below. 3121 unsigned CheckArgs = Args.size(); 3122 if (Args.size() < Function->getMinRequiredArguments()) 3123 return TDK_TooFewArguments; 3124 else if (Args.size() > Function->getNumParams()) { 3125 const FunctionProtoType *Proto 3126 = Function->getType()->getAs<FunctionProtoType>(); 3127 if (Proto->isTemplateVariadic()) 3128 /* Do nothing */; 3129 else if (Proto->isVariadic()) 3130 CheckArgs = Function->getNumParams(); 3131 else 3132 return TDK_TooManyArguments; 3133 } 3134 3135 // The types of the parameters from which we will perform template argument 3136 // deduction. 3137 LocalInstantiationScope InstScope(*this); 3138 TemplateParameterList *TemplateParams 3139 = FunctionTemplate->getTemplateParameters(); 3140 SmallVector<DeducedTemplateArgument, 4> Deduced; 3141 SmallVector<QualType, 4> ParamTypes; 3142 unsigned NumExplicitlySpecified = 0; 3143 if (ExplicitTemplateArgs) { 3144 TemplateDeductionResult Result = 3145 SubstituteExplicitTemplateArguments(FunctionTemplate, 3146 *ExplicitTemplateArgs, 3147 Deduced, 3148 ParamTypes, 3149 0, 3150 Info); 3151 if (Result) 3152 return Result; 3153 3154 NumExplicitlySpecified = Deduced.size(); 3155 } else { 3156 // Just fill in the parameter types from the function declaration. 3157 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 3158 ParamTypes.push_back(Function->getParamDecl(I)->getType()); 3159 } 3160 3161 // Deduce template arguments from the function parameters. 3162 Deduced.resize(TemplateParams->size()); 3163 unsigned ArgIdx = 0; 3164 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 3165 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size(); 3166 ParamIdx != NumParams; ++ParamIdx) { 3167 QualType OrigParamType = ParamTypes[ParamIdx]; 3168 QualType ParamType = OrigParamType; 3169 3170 const PackExpansionType *ParamExpansion 3171 = dyn_cast<PackExpansionType>(ParamType); 3172 if (!ParamExpansion) { 3173 // Simple case: matching a function parameter to a function argument. 3174 if (ArgIdx >= CheckArgs) 3175 break; 3176 3177 Expr *Arg = Args[ArgIdx++]; 3178 QualType ArgType = Arg->getType(); 3179 3180 unsigned TDF = 0; 3181 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 3182 ParamType, ArgType, Arg, 3183 TDF)) 3184 continue; 3185 3186 // If we have nothing to deduce, we're done. 3187 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 3188 continue; 3189 3190 // If the argument is an initializer list ... 3191 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 3192 // ... then the parameter is an undeduced context, unless the parameter 3193 // type is (reference to cv) std::initializer_list<P'>, in which case 3194 // deduction is done for each element of the initializer list, and the 3195 // result is the deduced type if it's the same for all elements. 3196 QualType X; 3197 // Removing references was already done. 3198 if (!isStdInitializerList(ParamType, &X)) 3199 continue; 3200 3201 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 3202 if (TemplateDeductionResult Result = 3203 DeduceTemplateArgumentByListElement(*this, TemplateParams, X, 3204 ILE->getInit(i), 3205 Info, Deduced, TDF)) 3206 return Result; 3207 } 3208 // Don't track the argument type, since an initializer list has none. 3209 continue; 3210 } 3211 3212 // Keep track of the argument type and corresponding parameter index, 3213 // so we can check for compatibility between the deduced A and A. 3214 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1, 3215 ArgType)); 3216 3217 if (TemplateDeductionResult Result 3218 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3219 ParamType, ArgType, 3220 Info, Deduced, TDF)) 3221 return Result; 3222 3223 continue; 3224 } 3225 3226 // C++0x [temp.deduct.call]p1: 3227 // For a function parameter pack that occurs at the end of the 3228 // parameter-declaration-list, the type A of each remaining argument of 3229 // the call is compared with the type P of the declarator-id of the 3230 // function parameter pack. Each comparison deduces template arguments 3231 // for subsequent positions in the template parameter packs expanded by 3232 // the function parameter pack. For a function parameter pack that does 3233 // not occur at the end of the parameter-declaration-list, the type of 3234 // the parameter pack is a non-deduced context. 3235 if (ParamIdx + 1 < NumParams) 3236 break; 3237 3238 QualType ParamPattern = ParamExpansion->getPattern(); 3239 SmallVector<unsigned, 2> PackIndices; 3240 { 3241 llvm::SmallBitVector SawIndices(TemplateParams->size()); 3242 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 3243 collectUnexpandedParameterPacks(ParamPattern, Unexpanded); 3244 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 3245 unsigned Depth, Index; 3246 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 3247 if (Depth == 0 && !SawIndices[Index]) { 3248 SawIndices[Index] = true; 3249 PackIndices.push_back(Index); 3250 } 3251 } 3252 } 3253 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?"); 3254 3255 // Keep track of the deduced template arguments for each parameter pack 3256 // expanded by this pack expansion (the outer index) and for each 3257 // template argument (the inner SmallVectors). 3258 NewlyDeducedPacksType NewlyDeducedPacks(PackIndices.size()); 3259 SmallVector<DeducedTemplateArgument, 2> 3260 SavedPacks(PackIndices.size()); 3261 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks, 3262 NewlyDeducedPacks); 3263 bool HasAnyArguments = false; 3264 for (; ArgIdx < Args.size(); ++ArgIdx) { 3265 HasAnyArguments = true; 3266 3267 QualType OrigParamType = ParamPattern; 3268 ParamType = OrigParamType; 3269 Expr *Arg = Args[ArgIdx]; 3270 QualType ArgType = Arg->getType(); 3271 3272 unsigned TDF = 0; 3273 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 3274 ParamType, ArgType, Arg, 3275 TDF)) { 3276 // We can't actually perform any deduction for this argument, so stop 3277 // deduction at this point. 3278 ++ArgIdx; 3279 break; 3280 } 3281 3282 // As above, initializer lists need special handling. 3283 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 3284 QualType X; 3285 if (!isStdInitializerList(ParamType, &X)) { 3286 ++ArgIdx; 3287 break; 3288 } 3289 3290 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 3291 if (TemplateDeductionResult Result = 3292 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X, 3293 ILE->getInit(i)->getType(), 3294 Info, Deduced, TDF)) 3295 return Result; 3296 } 3297 } else { 3298 3299 // Keep track of the argument type and corresponding argument index, 3300 // so we can check for compatibility between the deduced A and A. 3301 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 3302 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx, 3303 ArgType)); 3304 3305 if (TemplateDeductionResult Result 3306 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3307 ParamType, ArgType, Info, 3308 Deduced, TDF)) 3309 return Result; 3310 } 3311 3312 // Capture the deduced template arguments for each parameter pack expanded 3313 // by this pack expansion, add them to the list of arguments we've deduced 3314 // for that pack, then clear out the deduced argument. 3315 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 3316 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]]; 3317 if (!DeducedArg.isNull()) { 3318 NewlyDeducedPacks[I].push_back(DeducedArg); 3319 DeducedArg = DeducedTemplateArgument(); 3320 } 3321 } 3322 } 3323 3324 // Build argument packs for each of the parameter packs expanded by this 3325 // pack expansion. 3326 if (Sema::TemplateDeductionResult Result 3327 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments, 3328 Deduced, PackIndices, SavedPacks, 3329 NewlyDeducedPacks, Info)) 3330 return Result; 3331 3332 // After we've matching against a parameter pack, we're done. 3333 break; 3334 } 3335 3336 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 3337 NumExplicitlySpecified, 3338 Specialization, Info, &OriginalCallArgs); 3339} 3340 3341/// \brief Deduce template arguments when taking the address of a function 3342/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 3343/// a template. 3344/// 3345/// \param FunctionTemplate the function template for which we are performing 3346/// template argument deduction. 3347/// 3348/// \param ExplicitTemplateArgs the explicitly-specified template 3349/// arguments. 3350/// 3351/// \param ArgFunctionType the function type that will be used as the 3352/// "argument" type (A) when performing template argument deduction from the 3353/// function template's function type. This type may be NULL, if there is no 3354/// argument type to compare against, in C++0x [temp.arg.explicit]p3. 3355/// 3356/// \param Specialization if template argument deduction was successful, 3357/// this will be set to the function template specialization produced by 3358/// template argument deduction. 3359/// 3360/// \param Info the argument will be updated to provide additional information 3361/// about template argument deduction. 3362/// 3363/// \returns the result of template argument deduction. 3364Sema::TemplateDeductionResult 3365Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 3366 TemplateArgumentListInfo *ExplicitTemplateArgs, 3367 QualType ArgFunctionType, 3368 FunctionDecl *&Specialization, 3369 TemplateDeductionInfo &Info, 3370 bool InOverloadResolution) { 3371 if (FunctionTemplate->isInvalidDecl()) 3372 return TDK_Invalid; 3373 3374 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 3375 TemplateParameterList *TemplateParams 3376 = FunctionTemplate->getTemplateParameters(); 3377 QualType FunctionType = Function->getType(); 3378 3379 // Substitute any explicit template arguments. 3380 LocalInstantiationScope InstScope(*this); 3381 SmallVector<DeducedTemplateArgument, 4> Deduced; 3382 unsigned NumExplicitlySpecified = 0; 3383 SmallVector<QualType, 4> ParamTypes; 3384 if (ExplicitTemplateArgs) { 3385 if (TemplateDeductionResult Result 3386 = SubstituteExplicitTemplateArguments(FunctionTemplate, 3387 *ExplicitTemplateArgs, 3388 Deduced, ParamTypes, 3389 &FunctionType, Info)) 3390 return Result; 3391 3392 NumExplicitlySpecified = Deduced.size(); 3393 } 3394 3395 // Unevaluated SFINAE context. 3396 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3397 SFINAETrap Trap(*this); 3398 3399 Deduced.resize(TemplateParams->size()); 3400 3401 // If the function has a deduced return type, substitute it for a dependent 3402 // type so that we treat it as a non-deduced context in what follows. 3403 bool HasUndeducedReturnType = false; 3404 if (getLangOpts().CPlusPlus1y && InOverloadResolution && 3405 Function->getResultType()->isUndeducedType()) { 3406 FunctionType = SubstAutoType(FunctionType, Context.DependentTy); 3407 HasUndeducedReturnType = true; 3408 } 3409 3410 if (!ArgFunctionType.isNull()) { 3411 unsigned TDF = TDF_TopLevelParameterTypeList; 3412 if (InOverloadResolution) TDF |= TDF_InOverloadResolution; 3413 // Deduce template arguments from the function type. 3414 if (TemplateDeductionResult Result 3415 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3416 FunctionType, ArgFunctionType, 3417 Info, Deduced, TDF)) 3418 return Result; 3419 } 3420 3421 if (TemplateDeductionResult Result 3422 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 3423 NumExplicitlySpecified, 3424 Specialization, Info)) 3425 return Result; 3426 3427 // If the function has a deduced return type, deduce it now, so we can check 3428 // that the deduced function type matches the requested type. 3429 if (HasUndeducedReturnType && 3430 Specialization->getResultType()->isUndeducedType() && 3431 DeduceReturnType(Specialization, Info.getLocation(), false)) 3432 return TDK_MiscellaneousDeductionFailure; 3433 3434 // If the requested function type does not match the actual type of the 3435 // specialization with respect to arguments of compatible pointer to function 3436 // types, template argument deduction fails. 3437 if (!ArgFunctionType.isNull()) { 3438 if (InOverloadResolution && !isSameOrCompatibleFunctionType( 3439 Context.getCanonicalType(Specialization->getType()), 3440 Context.getCanonicalType(ArgFunctionType))) 3441 return TDK_MiscellaneousDeductionFailure; 3442 else if(!InOverloadResolution && 3443 !Context.hasSameType(Specialization->getType(), ArgFunctionType)) 3444 return TDK_MiscellaneousDeductionFailure; 3445 } 3446 3447 return TDK_Success; 3448} 3449 3450/// \brief Deduce template arguments for a templated conversion 3451/// function (C++ [temp.deduct.conv]) and, if successful, produce a 3452/// conversion function template specialization. 3453Sema::TemplateDeductionResult 3454Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 3455 QualType ToType, 3456 CXXConversionDecl *&Specialization, 3457 TemplateDeductionInfo &Info) { 3458 if (FunctionTemplate->isInvalidDecl()) 3459 return TDK_Invalid; 3460 3461 CXXConversionDecl *Conv 3462 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()); 3463 QualType FromType = Conv->getConversionType(); 3464 3465 // Canonicalize the types for deduction. 3466 QualType P = Context.getCanonicalType(FromType); 3467 QualType A = Context.getCanonicalType(ToType); 3468 3469 // C++0x [temp.deduct.conv]p2: 3470 // If P is a reference type, the type referred to by P is used for 3471 // type deduction. 3472 if (const ReferenceType *PRef = P->getAs<ReferenceType>()) 3473 P = PRef->getPointeeType(); 3474 3475 // C++0x [temp.deduct.conv]p4: 3476 // [...] If A is a reference type, the type referred to by A is used 3477 // for type deduction. 3478 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 3479 A = ARef->getPointeeType().getUnqualifiedType(); 3480 // C++ [temp.deduct.conv]p3: 3481 // 3482 // If A is not a reference type: 3483 else { 3484 assert(!A->isReferenceType() && "Reference types were handled above"); 3485 3486 // - If P is an array type, the pointer type produced by the 3487 // array-to-pointer standard conversion (4.2) is used in place 3488 // of P for type deduction; otherwise, 3489 if (P->isArrayType()) 3490 P = Context.getArrayDecayedType(P); 3491 // - If P is a function type, the pointer type produced by the 3492 // function-to-pointer standard conversion (4.3) is used in 3493 // place of P for type deduction; otherwise, 3494 else if (P->isFunctionType()) 3495 P = Context.getPointerType(P); 3496 // - If P is a cv-qualified type, the top level cv-qualifiers of 3497 // P's type are ignored for type deduction. 3498 else 3499 P = P.getUnqualifiedType(); 3500 3501 // C++0x [temp.deduct.conv]p4: 3502 // If A is a cv-qualified type, the top level cv-qualifiers of A's 3503 // type are ignored for type deduction. If A is a reference type, the type 3504 // referred to by A is used for type deduction. 3505 A = A.getUnqualifiedType(); 3506 } 3507 3508 // Unevaluated SFINAE context. 3509 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3510 SFINAETrap Trap(*this); 3511 3512 // C++ [temp.deduct.conv]p1: 3513 // Template argument deduction is done by comparing the return 3514 // type of the template conversion function (call it P) with the 3515 // type that is required as the result of the conversion (call it 3516 // A) as described in 14.8.2.4. 3517 TemplateParameterList *TemplateParams 3518 = FunctionTemplate->getTemplateParameters(); 3519 SmallVector<DeducedTemplateArgument, 4> Deduced; 3520 Deduced.resize(TemplateParams->size()); 3521 3522 // C++0x [temp.deduct.conv]p4: 3523 // In general, the deduction process attempts to find template 3524 // argument values that will make the deduced A identical to 3525 // A. However, there are two cases that allow a difference: 3526 unsigned TDF = 0; 3527 // - If the original A is a reference type, A can be more 3528 // cv-qualified than the deduced A (i.e., the type referred to 3529 // by the reference) 3530 if (ToType->isReferenceType()) 3531 TDF |= TDF_ParamWithReferenceType; 3532 // - The deduced A can be another pointer or pointer to member 3533 // type that can be converted to A via a qualification 3534 // conversion. 3535 // 3536 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when 3537 // both P and A are pointers or member pointers. In this case, we 3538 // just ignore cv-qualifiers completely). 3539 if ((P->isPointerType() && A->isPointerType()) || 3540 (P->isMemberPointerType() && A->isMemberPointerType())) 3541 TDF |= TDF_IgnoreQualifiers; 3542 if (TemplateDeductionResult Result 3543 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 3544 P, A, Info, Deduced, TDF)) 3545 return Result; 3546 3547 // Finish template argument deduction. 3548 LocalInstantiationScope InstScope(*this); 3549 FunctionDecl *Spec = 0; 3550 TemplateDeductionResult Result 3551 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec, 3552 Info); 3553 Specialization = cast_or_null<CXXConversionDecl>(Spec); 3554 return Result; 3555} 3556 3557/// \brief Deduce template arguments for a function template when there is 3558/// nothing to deduce against (C++0x [temp.arg.explicit]p3). 3559/// 3560/// \param FunctionTemplate the function template for which we are performing 3561/// template argument deduction. 3562/// 3563/// \param ExplicitTemplateArgs the explicitly-specified template 3564/// arguments. 3565/// 3566/// \param Specialization if template argument deduction was successful, 3567/// this will be set to the function template specialization produced by 3568/// template argument deduction. 3569/// 3570/// \param Info the argument will be updated to provide additional information 3571/// about template argument deduction. 3572/// 3573/// \returns the result of template argument deduction. 3574Sema::TemplateDeductionResult 3575Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 3576 TemplateArgumentListInfo *ExplicitTemplateArgs, 3577 FunctionDecl *&Specialization, 3578 TemplateDeductionInfo &Info, 3579 bool InOverloadResolution) { 3580 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 3581 QualType(), Specialization, Info, 3582 InOverloadResolution); 3583} 3584 3585namespace { 3586 /// Substitute the 'auto' type specifier within a type for a given replacement 3587 /// type. 3588 class SubstituteAutoTransform : 3589 public TreeTransform<SubstituteAutoTransform> { 3590 QualType Replacement; 3591 public: 3592 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) : 3593 TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) { 3594 } 3595 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { 3596 // If we're building the type pattern to deduce against, don't wrap the 3597 // substituted type in an AutoType. Certain template deduction rules 3598 // apply only when a template type parameter appears directly (and not if 3599 // the parameter is found through desugaring). For instance: 3600 // auto &&lref = lvalue; 3601 // must transform into "rvalue reference to T" not "rvalue reference to 3602 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. 3603 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) { 3604 QualType Result = Replacement; 3605 TemplateTypeParmTypeLoc NewTL = 3606 TLB.push<TemplateTypeParmTypeLoc>(Result); 3607 NewTL.setNameLoc(TL.getNameLoc()); 3608 return Result; 3609 } else { 3610 bool Dependent = 3611 !Replacement.isNull() && Replacement->isDependentType(); 3612 QualType Result = 3613 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement, 3614 TL.getTypePtr()->isDecltypeAuto(), 3615 Dependent); 3616 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result); 3617 NewTL.setNameLoc(TL.getNameLoc()); 3618 return Result; 3619 } 3620 } 3621 3622 ExprResult TransformLambdaExpr(LambdaExpr *E) { 3623 // Lambdas never need to be transformed. 3624 return E; 3625 } 3626 3627 QualType Apply(TypeLoc TL) { 3628 // Create some scratch storage for the transformed type locations. 3629 // FIXME: We're just going to throw this information away. Don't build it. 3630 TypeLocBuilder TLB; 3631 TLB.reserve(TL.getFullDataSize()); 3632 return TransformType(TLB, TL); 3633 } 3634 }; 3635} 3636 3637Sema::DeduceAutoResult 3638Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) { 3639 return DeduceAutoType(Type->getTypeLoc(), Init, Result); 3640} 3641 3642/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 3643/// 3644/// \param Type the type pattern using the auto type-specifier. 3645/// \param Init the initializer for the variable whose type is to be deduced. 3646/// \param Result if type deduction was successful, this will be set to the 3647/// deduced type. 3648Sema::DeduceAutoResult 3649Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) { 3650 if (Init->getType()->isNonOverloadPlaceholderType()) { 3651 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init); 3652 if (NonPlaceholder.isInvalid()) 3653 return DAR_FailedAlreadyDiagnosed; 3654 Init = NonPlaceholder.take(); 3655 } 3656 3657 if (Init->isTypeDependent() || Type.getType()->isDependentType()) { 3658 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type); 3659 assert(!Result.isNull() && "substituting DependentTy can't fail"); 3660 return DAR_Succeeded; 3661 } 3662 3663 // If this is a 'decltype(auto)' specifier, do the decltype dance. 3664 // Since 'decltype(auto)' can only occur at the top of the type, we 3665 // don't need to go digging for it. 3666 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) { 3667 if (AT->isDecltypeAuto()) { 3668 if (isa<InitListExpr>(Init)) { 3669 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list); 3670 return DAR_FailedAlreadyDiagnosed; 3671 } 3672 3673 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart()); 3674 // FIXME: Support a non-canonical deduced type for 'auto'. 3675 Deduced = Context.getCanonicalType(Deduced); 3676 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type); 3677 if (Result.isNull()) 3678 return DAR_FailedAlreadyDiagnosed; 3679 return DAR_Succeeded; 3680 } 3681 } 3682 3683 SourceLocation Loc = Init->getExprLoc(); 3684 3685 LocalInstantiationScope InstScope(*this); 3686 3687 // Build template<class TemplParam> void Func(FuncParam); 3688 TemplateTypeParmDecl *TemplParam = 3689 TemplateTypeParmDecl::Create(Context, 0, SourceLocation(), Loc, 0, 0, 0, 3690 false, false); 3691 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 3692 NamedDecl *TemplParamPtr = TemplParam; 3693 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr, 3694 Loc); 3695 3696 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type); 3697 assert(!FuncParam.isNull() && 3698 "substituting template parameter for 'auto' failed"); 3699 3700 // Deduce type of TemplParam in Func(Init) 3701 SmallVector<DeducedTemplateArgument, 1> Deduced; 3702 Deduced.resize(1); 3703 QualType InitType = Init->getType(); 3704 unsigned TDF = 0; 3705 3706 TemplateDeductionInfo Info(Loc); 3707 3708 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 3709 if (InitList) { 3710 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 3711 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams, 3712 TemplArg, 3713 InitList->getInit(i), 3714 Info, Deduced, TDF)) 3715 return DAR_Failed; 3716 } 3717 } else { 3718 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams, 3719 FuncParam, InitType, Init, 3720 TDF)) 3721 return DAR_Failed; 3722 3723 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam, 3724 InitType, Info, Deduced, TDF)) 3725 return DAR_Failed; 3726 } 3727 3728 if (Deduced[0].getKind() != TemplateArgument::Type) 3729 return DAR_Failed; 3730 3731 QualType DeducedType = Deduced[0].getAsType(); 3732 3733 if (InitList) { 3734 DeducedType = BuildStdInitializerList(DeducedType, Loc); 3735 if (DeducedType.isNull()) 3736 return DAR_FailedAlreadyDiagnosed; 3737 } 3738 3739 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type); 3740 if (Result.isNull()) 3741 return DAR_FailedAlreadyDiagnosed; 3742 3743 // Check that the deduced argument type is compatible with the original 3744 // argument type per C++ [temp.deduct.call]p4. 3745 if (!InitList && !Result.isNull() && 3746 CheckOriginalCallArgDeduction(*this, 3747 Sema::OriginalCallArg(FuncParam,0,InitType), 3748 Result)) { 3749 Result = QualType(); 3750 return DAR_Failed; 3751 } 3752 3753 return DAR_Succeeded; 3754} 3755 3756QualType Sema::SubstAutoType(QualType Type, QualType Deduced) { 3757 return SubstituteAutoTransform(*this, Deduced).TransformType(Type); 3758} 3759 3760void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 3761 if (isa<InitListExpr>(Init)) 3762 Diag(VDecl->getLocation(), 3763 diag::err_auto_var_deduction_failure_from_init_list) 3764 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 3765 else 3766 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 3767 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 3768 << Init->getSourceRange(); 3769} 3770 3771bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 3772 bool Diagnose) { 3773 assert(FD->getResultType()->isUndeducedType()); 3774 3775 if (FD->getTemplateInstantiationPattern()) 3776 InstantiateFunctionDefinition(Loc, FD); 3777 3778 bool StillUndeduced = FD->getResultType()->isUndeducedType(); 3779 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) { 3780 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD; 3781 Diag(FD->getLocation(), diag::note_callee_decl) << FD; 3782 } 3783 3784 return StillUndeduced; 3785} 3786 3787static void 3788MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 3789 bool OnlyDeduced, 3790 unsigned Level, 3791 llvm::SmallBitVector &Deduced); 3792 3793/// \brief If this is a non-static member function, 3794static void 3795AddImplicitObjectParameterType(ASTContext &Context, 3796 CXXMethodDecl *Method, 3797 SmallVectorImpl<QualType> &ArgTypes) { 3798 // C++11 [temp.func.order]p3: 3799 // [...] The new parameter is of type "reference to cv A," where cv are 3800 // the cv-qualifiers of the function template (if any) and A is 3801 // the class of which the function template is a member. 3802 // 3803 // The standard doesn't say explicitly, but we pick the appropriate kind of 3804 // reference type based on [over.match.funcs]p4. 3805 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 3806 ArgTy = Context.getQualifiedType(ArgTy, 3807 Qualifiers::fromCVRMask(Method->getTypeQualifiers())); 3808 if (Method->getRefQualifier() == RQ_RValue) 3809 ArgTy = Context.getRValueReferenceType(ArgTy); 3810 else 3811 ArgTy = Context.getLValueReferenceType(ArgTy); 3812 ArgTypes.push_back(ArgTy); 3813} 3814 3815/// \brief Determine whether the function template \p FT1 is at least as 3816/// specialized as \p FT2. 3817static bool isAtLeastAsSpecializedAs(Sema &S, 3818 SourceLocation Loc, 3819 FunctionTemplateDecl *FT1, 3820 FunctionTemplateDecl *FT2, 3821 TemplatePartialOrderingContext TPOC, 3822 unsigned NumCallArguments, 3823 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) { 3824 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 3825 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 3826 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 3827 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 3828 3829 assert(Proto1 && Proto2 && "Function templates must have prototypes"); 3830 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 3831 SmallVector<DeducedTemplateArgument, 4> Deduced; 3832 Deduced.resize(TemplateParams->size()); 3833 3834 // C++0x [temp.deduct.partial]p3: 3835 // The types used to determine the ordering depend on the context in which 3836 // the partial ordering is done: 3837 TemplateDeductionInfo Info(Loc); 3838 CXXMethodDecl *Method1 = 0; 3839 CXXMethodDecl *Method2 = 0; 3840 bool IsNonStatic2 = false; 3841 bool IsNonStatic1 = false; 3842 unsigned Skip2 = 0; 3843 switch (TPOC) { 3844 case TPOC_Call: { 3845 // - In the context of a function call, the function parameter types are 3846 // used. 3847 Method1 = dyn_cast<CXXMethodDecl>(FD1); 3848 Method2 = dyn_cast<CXXMethodDecl>(FD2); 3849 IsNonStatic1 = Method1 && !Method1->isStatic(); 3850 IsNonStatic2 = Method2 && !Method2->isStatic(); 3851 3852 // C++11 [temp.func.order]p3: 3853 // [...] If only one of the function templates is a non-static 3854 // member, that function template is considered to have a new 3855 // first parameter inserted in its function parameter list. The 3856 // new parameter is of type "reference to cv A," where cv are 3857 // the cv-qualifiers of the function template (if any) and A is 3858 // the class of which the function template is a member. 3859 // 3860 // Note that we interpret this to mean "if one of the function 3861 // templates is a non-static member and the other is a non-member"; 3862 // otherwise, the ordering rules for static functions against non-static 3863 // functions don't make any sense. 3864 // 3865 // C++98/03 doesn't have this provision, so instead we drop the 3866 // first argument of the free function, which seems to match 3867 // existing practice. 3868 SmallVector<QualType, 4> Args1; 3869 unsigned Skip1 = !S.getLangOpts().CPlusPlus11 && IsNonStatic2 && !Method1; 3870 if (S.getLangOpts().CPlusPlus11 && IsNonStatic1 && !Method2) 3871 AddImplicitObjectParameterType(S.Context, Method1, Args1); 3872 Args1.insert(Args1.end(), 3873 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end()); 3874 3875 SmallVector<QualType, 4> Args2; 3876 Skip2 = !S.getLangOpts().CPlusPlus11 && IsNonStatic1 && !Method2; 3877 if (S.getLangOpts().CPlusPlus11 && IsNonStatic2 && !Method1) 3878 AddImplicitObjectParameterType(S.Context, Method2, Args2); 3879 Args2.insert(Args2.end(), 3880 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end()); 3881 3882 // C++ [temp.func.order]p5: 3883 // The presence of unused ellipsis and default arguments has no effect on 3884 // the partial ordering of function templates. 3885 if (Args1.size() > NumCallArguments) 3886 Args1.resize(NumCallArguments); 3887 if (Args2.size() > NumCallArguments) 3888 Args2.resize(NumCallArguments); 3889 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 3890 Args1.data(), Args1.size(), Info, Deduced, 3891 TDF_None, /*PartialOrdering=*/true, 3892 RefParamComparisons)) 3893 return false; 3894 3895 break; 3896 } 3897 3898 case TPOC_Conversion: 3899 // - In the context of a call to a conversion operator, the return types 3900 // of the conversion function templates are used. 3901 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 3902 Proto2->getResultType(), 3903 Proto1->getResultType(), 3904 Info, Deduced, TDF_None, 3905 /*PartialOrdering=*/true, 3906 RefParamComparisons)) 3907 return false; 3908 break; 3909 3910 case TPOC_Other: 3911 // - In other contexts (14.6.6.2) the function template's function type 3912 // is used. 3913 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 3914 FD2->getType(), FD1->getType(), 3915 Info, Deduced, TDF_None, 3916 /*PartialOrdering=*/true, 3917 RefParamComparisons)) 3918 return false; 3919 break; 3920 } 3921 3922 // C++0x [temp.deduct.partial]p11: 3923 // In most cases, all template parameters must have values in order for 3924 // deduction to succeed, but for partial ordering purposes a template 3925 // parameter may remain without a value provided it is not used in the 3926 // types being used for partial ordering. [ Note: a template parameter used 3927 // in a non-deduced context is considered used. -end note] 3928 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 3929 for (; ArgIdx != NumArgs; ++ArgIdx) 3930 if (Deduced[ArgIdx].isNull()) 3931 break; 3932 3933 if (ArgIdx == NumArgs) { 3934 // All template arguments were deduced. FT1 is at least as specialized 3935 // as FT2. 3936 return true; 3937 } 3938 3939 // Figure out which template parameters were used. 3940 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 3941 switch (TPOC) { 3942 case TPOC_Call: { 3943 unsigned NumParams = std::min(NumCallArguments, 3944 std::min(Proto1->getNumArgs(), 3945 Proto2->getNumArgs())); 3946 if (S.getLangOpts().CPlusPlus11 && IsNonStatic2 && !IsNonStatic1) 3947 ::MarkUsedTemplateParameters(S.Context, Method2->getThisType(S.Context), 3948 false, 3949 TemplateParams->getDepth(), UsedParameters); 3950 for (unsigned I = Skip2; I < NumParams; ++I) 3951 ::MarkUsedTemplateParameters(S.Context, Proto2->getArgType(I), false, 3952 TemplateParams->getDepth(), 3953 UsedParameters); 3954 break; 3955 } 3956 3957 case TPOC_Conversion: 3958 ::MarkUsedTemplateParameters(S.Context, Proto2->getResultType(), false, 3959 TemplateParams->getDepth(), 3960 UsedParameters); 3961 break; 3962 3963 case TPOC_Other: 3964 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 3965 TemplateParams->getDepth(), 3966 UsedParameters); 3967 break; 3968 } 3969 3970 for (; ArgIdx != NumArgs; ++ArgIdx) 3971 // If this argument had no value deduced but was used in one of the types 3972 // used for partial ordering, then deduction fails. 3973 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 3974 return false; 3975 3976 return true; 3977} 3978 3979/// \brief Determine whether this a function template whose parameter-type-list 3980/// ends with a function parameter pack. 3981static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 3982 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 3983 unsigned NumParams = Function->getNumParams(); 3984 if (NumParams == 0) 3985 return false; 3986 3987 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 3988 if (!Last->isParameterPack()) 3989 return false; 3990 3991 // Make sure that no previous parameter is a parameter pack. 3992 while (--NumParams > 0) { 3993 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 3994 return false; 3995 } 3996 3997 return true; 3998} 3999 4000/// \brief Returns the more specialized function template according 4001/// to the rules of function template partial ordering (C++ [temp.func.order]). 4002/// 4003/// \param FT1 the first function template 4004/// 4005/// \param FT2 the second function template 4006/// 4007/// \param TPOC the context in which we are performing partial ordering of 4008/// function templates. 4009/// 4010/// \param NumCallArguments The number of arguments in a call, used only 4011/// when \c TPOC is \c TPOC_Call. 4012/// 4013/// \returns the more specialized function template. If neither 4014/// template is more specialized, returns NULL. 4015FunctionTemplateDecl * 4016Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 4017 FunctionTemplateDecl *FT2, 4018 SourceLocation Loc, 4019 TemplatePartialOrderingContext TPOC, 4020 unsigned NumCallArguments) { 4021 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons; 4022 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 4023 NumCallArguments, 0); 4024 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 4025 NumCallArguments, 4026 &RefParamComparisons); 4027 4028 if (Better1 != Better2) // We have a clear winner 4029 return Better1? FT1 : FT2; 4030 4031 if (!Better1 && !Better2) // Neither is better than the other 4032 return 0; 4033 4034 // C++0x [temp.deduct.partial]p10: 4035 // If for each type being considered a given template is at least as 4036 // specialized for all types and more specialized for some set of types and 4037 // the other template is not more specialized for any types or is not at 4038 // least as specialized for any types, then the given template is more 4039 // specialized than the other template. Otherwise, neither template is more 4040 // specialized than the other. 4041 Better1 = false; 4042 Better2 = false; 4043 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) { 4044 // C++0x [temp.deduct.partial]p9: 4045 // If, for a given type, deduction succeeds in both directions (i.e., the 4046 // types are identical after the transformations above) and both P and A 4047 // were reference types (before being replaced with the type referred to 4048 // above): 4049 4050 // -- if the type from the argument template was an lvalue reference 4051 // and the type from the parameter template was not, the argument 4052 // type is considered to be more specialized than the other; 4053 // otherwise, 4054 if (!RefParamComparisons[I].ArgIsRvalueRef && 4055 RefParamComparisons[I].ParamIsRvalueRef) { 4056 Better2 = true; 4057 if (Better1) 4058 return 0; 4059 continue; 4060 } else if (!RefParamComparisons[I].ParamIsRvalueRef && 4061 RefParamComparisons[I].ArgIsRvalueRef) { 4062 Better1 = true; 4063 if (Better2) 4064 return 0; 4065 continue; 4066 } 4067 4068 // -- if the type from the argument template is more cv-qualified than 4069 // the type from the parameter template (as described above), the 4070 // argument type is considered to be more specialized than the 4071 // other; otherwise, 4072 switch (RefParamComparisons[I].Qualifiers) { 4073 case NeitherMoreQualified: 4074 break; 4075 4076 case ParamMoreQualified: 4077 Better1 = true; 4078 if (Better2) 4079 return 0; 4080 continue; 4081 4082 case ArgMoreQualified: 4083 Better2 = true; 4084 if (Better1) 4085 return 0; 4086 continue; 4087 } 4088 4089 // -- neither type is more specialized than the other. 4090 } 4091 4092 assert(!(Better1 && Better2) && "Should have broken out in the loop above"); 4093 if (Better1) 4094 return FT1; 4095 else if (Better2) 4096 return FT2; 4097 4098 // FIXME: This mimics what GCC implements, but doesn't match up with the 4099 // proposed resolution for core issue 692. This area needs to be sorted out, 4100 // but for now we attempt to maintain compatibility. 4101 bool Variadic1 = isVariadicFunctionTemplate(FT1); 4102 bool Variadic2 = isVariadicFunctionTemplate(FT2); 4103 if (Variadic1 != Variadic2) 4104 return Variadic1? FT2 : FT1; 4105 4106 return 0; 4107} 4108 4109/// \brief Determine if the two templates are equivalent. 4110static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 4111 if (T1 == T2) 4112 return true; 4113 4114 if (!T1 || !T2) 4115 return false; 4116 4117 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 4118} 4119 4120/// \brief Retrieve the most specialized of the given function template 4121/// specializations. 4122/// 4123/// \param SpecBegin the start iterator of the function template 4124/// specializations that we will be comparing. 4125/// 4126/// \param SpecEnd the end iterator of the function template 4127/// specializations, paired with \p SpecBegin. 4128/// 4129/// \param TPOC the partial ordering context to use to compare the function 4130/// template specializations. 4131/// 4132/// \param NumCallArguments The number of arguments in a call, used only 4133/// when \c TPOC is \c TPOC_Call. 4134/// 4135/// \param Loc the location where the ambiguity or no-specializations 4136/// diagnostic should occur. 4137/// 4138/// \param NoneDiag partial diagnostic used to diagnose cases where there are 4139/// no matching candidates. 4140/// 4141/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 4142/// occurs. 4143/// 4144/// \param CandidateDiag partial diagnostic used for each function template 4145/// specialization that is a candidate in the ambiguous ordering. One parameter 4146/// in this diagnostic should be unbound, which will correspond to the string 4147/// describing the template arguments for the function template specialization. 4148/// 4149/// \returns the most specialized function template specialization, if 4150/// found. Otherwise, returns SpecEnd. 4151UnresolvedSetIterator Sema::getMostSpecialized( 4152 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd, 4153 TemplateSpecCandidateSet &FailedCandidates, 4154 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments, 4155 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 4156 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, 4157 bool Complain, QualType TargetType) { 4158 if (SpecBegin == SpecEnd) { 4159 if (Complain) { 4160 Diag(Loc, NoneDiag); 4161 FailedCandidates.NoteCandidates(*this, Loc); 4162 } 4163 return SpecEnd; 4164 } 4165 4166 if (SpecBegin + 1 == SpecEnd) 4167 return SpecBegin; 4168 4169 // Find the function template that is better than all of the templates it 4170 // has been compared to. 4171 UnresolvedSetIterator Best = SpecBegin; 4172 FunctionTemplateDecl *BestTemplate 4173 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 4174 assert(BestTemplate && "Not a function template specialization?"); 4175 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 4176 FunctionTemplateDecl *Challenger 4177 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 4178 assert(Challenger && "Not a function template specialization?"); 4179 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 4180 Loc, TPOC, NumCallArguments), 4181 Challenger)) { 4182 Best = I; 4183 BestTemplate = Challenger; 4184 } 4185 } 4186 4187 // Make sure that the "best" function template is more specialized than all 4188 // of the others. 4189 bool Ambiguous = false; 4190 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 4191 FunctionTemplateDecl *Challenger 4192 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 4193 if (I != Best && 4194 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 4195 Loc, TPOC, NumCallArguments), 4196 BestTemplate)) { 4197 Ambiguous = true; 4198 break; 4199 } 4200 } 4201 4202 if (!Ambiguous) { 4203 // We found an answer. Return it. 4204 return Best; 4205 } 4206 4207 // Diagnose the ambiguity. 4208 if (Complain) { 4209 Diag(Loc, AmbigDiag); 4210 4211 // FIXME: Can we order the candidates in some sane way? 4212 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 4213 PartialDiagnostic PD = CandidateDiag; 4214 PD << getTemplateArgumentBindingsText( 4215 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(), 4216 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs()); 4217 if (!TargetType.isNull()) 4218 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(), 4219 TargetType); 4220 Diag((*I)->getLocation(), PD); 4221 } 4222 } 4223 4224 return SpecEnd; 4225} 4226 4227/// \brief Returns the more specialized class template partial specialization 4228/// according to the rules of partial ordering of class template partial 4229/// specializations (C++ [temp.class.order]). 4230/// 4231/// \param PS1 the first class template partial specialization 4232/// 4233/// \param PS2 the second class template partial specialization 4234/// 4235/// \returns the more specialized class template partial specialization. If 4236/// neither partial specialization is more specialized, returns NULL. 4237ClassTemplatePartialSpecializationDecl * 4238Sema::getMoreSpecializedPartialSpecialization( 4239 ClassTemplatePartialSpecializationDecl *PS1, 4240 ClassTemplatePartialSpecializationDecl *PS2, 4241 SourceLocation Loc) { 4242 // C++ [temp.class.order]p1: 4243 // For two class template partial specializations, the first is at least as 4244 // specialized as the second if, given the following rewrite to two 4245 // function templates, the first function template is at least as 4246 // specialized as the second according to the ordering rules for function 4247 // templates (14.6.6.2): 4248 // - the first function template has the same template parameters as the 4249 // first partial specialization and has a single function parameter 4250 // whose type is a class template specialization with the template 4251 // arguments of the first partial specialization, and 4252 // - the second function template has the same template parameters as the 4253 // second partial specialization and has a single function parameter 4254 // whose type is a class template specialization with the template 4255 // arguments of the second partial specialization. 4256 // 4257 // Rather than synthesize function templates, we merely perform the 4258 // equivalent partial ordering by performing deduction directly on 4259 // the template arguments of the class template partial 4260 // specializations. This computation is slightly simpler than the 4261 // general problem of function template partial ordering, because 4262 // class template partial specializations are more constrained. We 4263 // know that every template parameter is deducible from the class 4264 // template partial specialization's template arguments, for 4265 // example. 4266 SmallVector<DeducedTemplateArgument, 4> Deduced; 4267 TemplateDeductionInfo Info(Loc); 4268 4269 QualType PT1 = PS1->getInjectedSpecializationType(); 4270 QualType PT2 = PS2->getInjectedSpecializationType(); 4271 4272 // Determine whether PS1 is at least as specialized as PS2 4273 Deduced.resize(PS2->getTemplateParameters()->size()); 4274 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this, 4275 PS2->getTemplateParameters(), 4276 PT2, PT1, Info, Deduced, TDF_None, 4277 /*PartialOrdering=*/true, 4278 /*RefParamComparisons=*/0); 4279 if (Better1) { 4280 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end()); 4281 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2, 4282 DeducedArgs, Info); 4283 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2, 4284 PS1->getTemplateArgs(), 4285 Deduced, Info); 4286 } 4287 4288 // Determine whether PS2 is at least as specialized as PS1 4289 Deduced.clear(); 4290 Deduced.resize(PS1->getTemplateParameters()->size()); 4291 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this, 4292 PS1->getTemplateParameters(), 4293 PT1, PT2, Info, Deduced, TDF_None, 4294 /*PartialOrdering=*/true, 4295 /*RefParamComparisons=*/0); 4296 if (Better2) { 4297 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end()); 4298 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1, 4299 DeducedArgs, Info); 4300 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1, 4301 PS2->getTemplateArgs(), 4302 Deduced, Info); 4303 } 4304 4305 if (Better1 == Better2) 4306 return 0; 4307 4308 return Better1? PS1 : PS2; 4309} 4310 4311static void 4312MarkUsedTemplateParameters(ASTContext &Ctx, 4313 const TemplateArgument &TemplateArg, 4314 bool OnlyDeduced, 4315 unsigned Depth, 4316 llvm::SmallBitVector &Used); 4317 4318/// \brief Mark the template parameters that are used by the given 4319/// expression. 4320static void 4321MarkUsedTemplateParameters(ASTContext &Ctx, 4322 const Expr *E, 4323 bool OnlyDeduced, 4324 unsigned Depth, 4325 llvm::SmallBitVector &Used) { 4326 // We can deduce from a pack expansion. 4327 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 4328 E = Expansion->getPattern(); 4329 4330 // Skip through any implicit casts we added while type-checking, and any 4331 // substitutions performed by template alias expansion. 4332 while (1) { 4333 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 4334 E = ICE->getSubExpr(); 4335 else if (const SubstNonTypeTemplateParmExpr *Subst = 4336 dyn_cast<SubstNonTypeTemplateParmExpr>(E)) 4337 E = Subst->getReplacement(); 4338 else 4339 break; 4340 } 4341 4342 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to 4343 // find other occurrences of template parameters. 4344 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 4345 if (!DRE) 4346 return; 4347 4348 const NonTypeTemplateParmDecl *NTTP 4349 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 4350 if (!NTTP) 4351 return; 4352 4353 if (NTTP->getDepth() == Depth) 4354 Used[NTTP->getIndex()] = true; 4355} 4356 4357/// \brief Mark the template parameters that are used by the given 4358/// nested name specifier. 4359static void 4360MarkUsedTemplateParameters(ASTContext &Ctx, 4361 NestedNameSpecifier *NNS, 4362 bool OnlyDeduced, 4363 unsigned Depth, 4364 llvm::SmallBitVector &Used) { 4365 if (!NNS) 4366 return; 4367 4368 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 4369 Used); 4370 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 4371 OnlyDeduced, Depth, Used); 4372} 4373 4374/// \brief Mark the template parameters that are used by the given 4375/// template name. 4376static void 4377MarkUsedTemplateParameters(ASTContext &Ctx, 4378 TemplateName Name, 4379 bool OnlyDeduced, 4380 unsigned Depth, 4381 llvm::SmallBitVector &Used) { 4382 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 4383 if (TemplateTemplateParmDecl *TTP 4384 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 4385 if (TTP->getDepth() == Depth) 4386 Used[TTP->getIndex()] = true; 4387 } 4388 return; 4389 } 4390 4391 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 4392 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 4393 Depth, Used); 4394 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 4395 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 4396 Depth, Used); 4397} 4398 4399/// \brief Mark the template parameters that are used by the given 4400/// type. 4401static void 4402MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 4403 bool OnlyDeduced, 4404 unsigned Depth, 4405 llvm::SmallBitVector &Used) { 4406 if (T.isNull()) 4407 return; 4408 4409 // Non-dependent types have nothing deducible 4410 if (!T->isDependentType()) 4411 return; 4412 4413 T = Ctx.getCanonicalType(T); 4414 switch (T->getTypeClass()) { 4415 case Type::Pointer: 4416 MarkUsedTemplateParameters(Ctx, 4417 cast<PointerType>(T)->getPointeeType(), 4418 OnlyDeduced, 4419 Depth, 4420 Used); 4421 break; 4422 4423 case Type::BlockPointer: 4424 MarkUsedTemplateParameters(Ctx, 4425 cast<BlockPointerType>(T)->getPointeeType(), 4426 OnlyDeduced, 4427 Depth, 4428 Used); 4429 break; 4430 4431 case Type::LValueReference: 4432 case Type::RValueReference: 4433 MarkUsedTemplateParameters(Ctx, 4434 cast<ReferenceType>(T)->getPointeeType(), 4435 OnlyDeduced, 4436 Depth, 4437 Used); 4438 break; 4439 4440 case Type::MemberPointer: { 4441 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 4442 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 4443 Depth, Used); 4444 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 4445 OnlyDeduced, Depth, Used); 4446 break; 4447 } 4448 4449 case Type::DependentSizedArray: 4450 MarkUsedTemplateParameters(Ctx, 4451 cast<DependentSizedArrayType>(T)->getSizeExpr(), 4452 OnlyDeduced, Depth, Used); 4453 // Fall through to check the element type 4454 4455 case Type::ConstantArray: 4456 case Type::IncompleteArray: 4457 MarkUsedTemplateParameters(Ctx, 4458 cast<ArrayType>(T)->getElementType(), 4459 OnlyDeduced, Depth, Used); 4460 break; 4461 4462 case Type::Vector: 4463 case Type::ExtVector: 4464 MarkUsedTemplateParameters(Ctx, 4465 cast<VectorType>(T)->getElementType(), 4466 OnlyDeduced, Depth, Used); 4467 break; 4468 4469 case Type::DependentSizedExtVector: { 4470 const DependentSizedExtVectorType *VecType 4471 = cast<DependentSizedExtVectorType>(T); 4472 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 4473 Depth, Used); 4474 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 4475 Depth, Used); 4476 break; 4477 } 4478 4479 case Type::FunctionProto: { 4480 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 4481 MarkUsedTemplateParameters(Ctx, Proto->getResultType(), OnlyDeduced, 4482 Depth, Used); 4483 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I) 4484 MarkUsedTemplateParameters(Ctx, Proto->getArgType(I), OnlyDeduced, 4485 Depth, Used); 4486 break; 4487 } 4488 4489 case Type::TemplateTypeParm: { 4490 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 4491 if (TTP->getDepth() == Depth) 4492 Used[TTP->getIndex()] = true; 4493 break; 4494 } 4495 4496 case Type::SubstTemplateTypeParmPack: { 4497 const SubstTemplateTypeParmPackType *Subst 4498 = cast<SubstTemplateTypeParmPackType>(T); 4499 MarkUsedTemplateParameters(Ctx, 4500 QualType(Subst->getReplacedParameter(), 0), 4501 OnlyDeduced, Depth, Used); 4502 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 4503 OnlyDeduced, Depth, Used); 4504 break; 4505 } 4506 4507 case Type::InjectedClassName: 4508 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 4509 // fall through 4510 4511 case Type::TemplateSpecialization: { 4512 const TemplateSpecializationType *Spec 4513 = cast<TemplateSpecializationType>(T); 4514 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 4515 Depth, Used); 4516 4517 // C++0x [temp.deduct.type]p9: 4518 // If the template argument list of P contains a pack expansion that is not 4519 // the last template argument, the entire template argument list is a 4520 // non-deduced context. 4521 if (OnlyDeduced && 4522 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 4523 break; 4524 4525 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 4526 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 4527 Used); 4528 break; 4529 } 4530 4531 case Type::Complex: 4532 if (!OnlyDeduced) 4533 MarkUsedTemplateParameters(Ctx, 4534 cast<ComplexType>(T)->getElementType(), 4535 OnlyDeduced, Depth, Used); 4536 break; 4537 4538 case Type::Atomic: 4539 if (!OnlyDeduced) 4540 MarkUsedTemplateParameters(Ctx, 4541 cast<AtomicType>(T)->getValueType(), 4542 OnlyDeduced, Depth, Used); 4543 break; 4544 4545 case Type::DependentName: 4546 if (!OnlyDeduced) 4547 MarkUsedTemplateParameters(Ctx, 4548 cast<DependentNameType>(T)->getQualifier(), 4549 OnlyDeduced, Depth, Used); 4550 break; 4551 4552 case Type::DependentTemplateSpecialization: { 4553 const DependentTemplateSpecializationType *Spec 4554 = cast<DependentTemplateSpecializationType>(T); 4555 if (!OnlyDeduced) 4556 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 4557 OnlyDeduced, Depth, Used); 4558 4559 // C++0x [temp.deduct.type]p9: 4560 // If the template argument list of P contains a pack expansion that is not 4561 // the last template argument, the entire template argument list is a 4562 // non-deduced context. 4563 if (OnlyDeduced && 4564 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 4565 break; 4566 4567 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 4568 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 4569 Used); 4570 break; 4571 } 4572 4573 case Type::TypeOf: 4574 if (!OnlyDeduced) 4575 MarkUsedTemplateParameters(Ctx, 4576 cast<TypeOfType>(T)->getUnderlyingType(), 4577 OnlyDeduced, Depth, Used); 4578 break; 4579 4580 case Type::TypeOfExpr: 4581 if (!OnlyDeduced) 4582 MarkUsedTemplateParameters(Ctx, 4583 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 4584 OnlyDeduced, Depth, Used); 4585 break; 4586 4587 case Type::Decltype: 4588 if (!OnlyDeduced) 4589 MarkUsedTemplateParameters(Ctx, 4590 cast<DecltypeType>(T)->getUnderlyingExpr(), 4591 OnlyDeduced, Depth, Used); 4592 break; 4593 4594 case Type::UnaryTransform: 4595 if (!OnlyDeduced) 4596 MarkUsedTemplateParameters(Ctx, 4597 cast<UnaryTransformType>(T)->getUnderlyingType(), 4598 OnlyDeduced, Depth, Used); 4599 break; 4600 4601 case Type::PackExpansion: 4602 MarkUsedTemplateParameters(Ctx, 4603 cast<PackExpansionType>(T)->getPattern(), 4604 OnlyDeduced, Depth, Used); 4605 break; 4606 4607 case Type::Auto: 4608 MarkUsedTemplateParameters(Ctx, 4609 cast<AutoType>(T)->getDeducedType(), 4610 OnlyDeduced, Depth, Used); 4611 4612 // None of these types have any template parameters in them. 4613 case Type::Builtin: 4614 case Type::VariableArray: 4615 case Type::FunctionNoProto: 4616 case Type::Record: 4617 case Type::Enum: 4618 case Type::ObjCInterface: 4619 case Type::ObjCObject: 4620 case Type::ObjCObjectPointer: 4621 case Type::UnresolvedUsing: 4622#define TYPE(Class, Base) 4623#define ABSTRACT_TYPE(Class, Base) 4624#define DEPENDENT_TYPE(Class, Base) 4625#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 4626#include "clang/AST/TypeNodes.def" 4627 break; 4628 } 4629} 4630 4631/// \brief Mark the template parameters that are used by this 4632/// template argument. 4633static void 4634MarkUsedTemplateParameters(ASTContext &Ctx, 4635 const TemplateArgument &TemplateArg, 4636 bool OnlyDeduced, 4637 unsigned Depth, 4638 llvm::SmallBitVector &Used) { 4639 switch (TemplateArg.getKind()) { 4640 case TemplateArgument::Null: 4641 case TemplateArgument::Integral: 4642 case TemplateArgument::Declaration: 4643 break; 4644 4645 case TemplateArgument::NullPtr: 4646 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced, 4647 Depth, Used); 4648 break; 4649 4650 case TemplateArgument::Type: 4651 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 4652 Depth, Used); 4653 break; 4654 4655 case TemplateArgument::Template: 4656 case TemplateArgument::TemplateExpansion: 4657 MarkUsedTemplateParameters(Ctx, 4658 TemplateArg.getAsTemplateOrTemplatePattern(), 4659 OnlyDeduced, Depth, Used); 4660 break; 4661 4662 case TemplateArgument::Expression: 4663 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 4664 Depth, Used); 4665 break; 4666 4667 case TemplateArgument::Pack: 4668 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(), 4669 PEnd = TemplateArg.pack_end(); 4670 P != PEnd; ++P) 4671 MarkUsedTemplateParameters(Ctx, *P, OnlyDeduced, Depth, Used); 4672 break; 4673 } 4674} 4675 4676/// \brief Mark which template parameters can be deduced from a given 4677/// template argument list. 4678/// 4679/// \param TemplateArgs the template argument list from which template 4680/// parameters will be deduced. 4681/// 4682/// \param Used a bit vector whose elements will be set to \c true 4683/// to indicate when the corresponding template parameter will be 4684/// deduced. 4685void 4686Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 4687 bool OnlyDeduced, unsigned Depth, 4688 llvm::SmallBitVector &Used) { 4689 // C++0x [temp.deduct.type]p9: 4690 // If the template argument list of P contains a pack expansion that is not 4691 // the last template argument, the entire template argument list is a 4692 // non-deduced context. 4693 if (OnlyDeduced && 4694 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size())) 4695 return; 4696 4697 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 4698 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 4699 Depth, Used); 4700} 4701 4702/// \brief Marks all of the template parameters that will be deduced by a 4703/// call to the given function template. 4704void 4705Sema::MarkDeducedTemplateParameters(ASTContext &Ctx, 4706 const FunctionTemplateDecl *FunctionTemplate, 4707 llvm::SmallBitVector &Deduced) { 4708 TemplateParameterList *TemplateParams 4709 = FunctionTemplate->getTemplateParameters(); 4710 Deduced.clear(); 4711 Deduced.resize(TemplateParams->size()); 4712 4713 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 4714 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 4715 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 4716 true, TemplateParams->getDepth(), Deduced); 4717} 4718 4719bool hasDeducibleTemplateParameters(Sema &S, 4720 FunctionTemplateDecl *FunctionTemplate, 4721 QualType T) { 4722 if (!T->isDependentType()) 4723 return false; 4724 4725 TemplateParameterList *TemplateParams 4726 = FunctionTemplate->getTemplateParameters(); 4727 llvm::SmallBitVector Deduced(TemplateParams->size()); 4728 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(), 4729 Deduced); 4730 4731 return Deduced.any(); 4732} 4733