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