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