1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ 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 instantiation. 10 // 11 //===----------------------------------------------------------------------===/ 12 13 #include "clang/Sema/SemaInternal.h" 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Sema/DeclSpec.h" 22 #include "clang/Sema/Initialization.h" 23 #include "clang/Sema/Lookup.h" 24 #include "clang/Sema/Template.h" 25 #include "clang/Sema/TemplateDeduction.h" 26 27 using namespace clang; 28 using namespace sema; 29 30 //===----------------------------------------------------------------------===/ 31 // Template Instantiation Support 32 //===----------------------------------------------------------------------===/ 33 34 /// \brief Retrieve the template argument list(s) that should be used to 35 /// instantiate the definition of the given declaration. 36 /// 37 /// \param D the declaration for which we are computing template instantiation 38 /// arguments. 39 /// 40 /// \param Innermost if non-NULL, the innermost template argument list. 41 /// 42 /// \param RelativeToPrimary true if we should get the template 43 /// arguments relative to the primary template, even when we're 44 /// dealing with a specialization. This is only relevant for function 45 /// template specializations. 46 /// 47 /// \param Pattern If non-NULL, indicates the pattern from which we will be 48 /// instantiating the definition of the given declaration, \p D. This is 49 /// used to determine the proper set of template instantiation arguments for 50 /// friend function template specializations. 51 MultiLevelTemplateArgumentList 52 Sema::getTemplateInstantiationArgs(NamedDecl *D, 53 const TemplateArgumentList *Innermost, 54 bool RelativeToPrimary, 55 const FunctionDecl *Pattern) { 56 // Accumulate the set of template argument lists in this structure. 57 MultiLevelTemplateArgumentList Result; 58 59 if (Innermost) 60 Result.addOuterTemplateArguments(Innermost); 61 62 DeclContext *Ctx = dyn_cast<DeclContext>(D); 63 if (!Ctx) { 64 Ctx = D->getDeclContext(); 65 66 // Add template arguments from a variable template instantiation. 67 if (VarTemplateSpecializationDecl *Spec = 68 dyn_cast<VarTemplateSpecializationDecl>(D)) { 69 // We're done when we hit an explicit specialization. 70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization && 71 !isa<VarTemplatePartialSpecializationDecl>(Spec)) 72 return Result; 73 74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); 75 76 // If this variable template specialization was instantiated from a 77 // specialized member that is a variable template, we're done. 78 assert(Spec->getSpecializedTemplate() && "No variable template?"); 79 llvm::PointerUnion<VarTemplateDecl*, 80 VarTemplatePartialSpecializationDecl*> Specialized 81 = Spec->getSpecializedTemplateOrPartial(); 82 if (VarTemplatePartialSpecializationDecl *Partial = 83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 84 if (Partial->isMemberSpecialization()) 85 return Result; 86 } else { 87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>(); 88 if (Tmpl->isMemberSpecialization()) 89 return Result; 90 } 91 } 92 93 // If we have a template template parameter with translation unit context, 94 // then we're performing substitution into a default template argument of 95 // this template template parameter before we've constructed the template 96 // that will own this template template parameter. In this case, we 97 // use empty template parameter lists for all of the outer templates 98 // to avoid performing any substitutions. 99 if (Ctx->isTranslationUnit()) { 100 if (TemplateTemplateParmDecl *TTP 101 = dyn_cast<TemplateTemplateParmDecl>(D)) { 102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) 103 Result.addOuterTemplateArguments(None); 104 return Result; 105 } 106 } 107 } 108 109 while (!Ctx->isFileContext()) { 110 // Add template arguments from a class template instantiation. 111 if (ClassTemplateSpecializationDecl *Spec 112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) { 113 // We're done when we hit an explicit specialization. 114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization && 115 !isa<ClassTemplatePartialSpecializationDecl>(Spec)) 116 break; 117 118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); 119 120 // If this class template specialization was instantiated from a 121 // specialized member that is a class template, we're done. 122 assert(Spec->getSpecializedTemplate() && "No class template?"); 123 if (Spec->getSpecializedTemplate()->isMemberSpecialization()) 124 break; 125 } 126 // Add template arguments from a function template specialization. 127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { 128 if (!RelativeToPrimary && 129 (Function->getTemplateSpecializationKind() == 130 TSK_ExplicitSpecialization && 131 !Function->getClassScopeSpecializationPattern())) 132 break; 133 134 if (const TemplateArgumentList *TemplateArgs 135 = Function->getTemplateSpecializationArgs()) { 136 // Add the template arguments for this specialization. 137 Result.addOuterTemplateArguments(TemplateArgs); 138 139 // If this function was instantiated from a specialized member that is 140 // a function template, we're done. 141 assert(Function->getPrimaryTemplate() && "No function template?"); 142 if (Function->getPrimaryTemplate()->isMemberSpecialization()) 143 break; 144 145 // If this function is a generic lambda specialization, we are done. 146 if (isGenericLambdaCallOperatorSpecialization(Function)) 147 break; 148 149 } else if (FunctionTemplateDecl *FunTmpl 150 = Function->getDescribedFunctionTemplate()) { 151 // Add the "injected" template arguments. 152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs()); 153 } 154 155 // If this is a friend declaration and it declares an entity at 156 // namespace scope, take arguments from its lexical parent 157 // instead of its semantic parent, unless of course the pattern we're 158 // instantiating actually comes from the file's context! 159 if (Function->getFriendObjectKind() && 160 Function->getDeclContext()->isFileContext() && 161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { 162 Ctx = Function->getLexicalDeclContext(); 163 RelativeToPrimary = false; 164 continue; 165 } 166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) { 167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { 168 QualType T = ClassTemplate->getInjectedClassNameSpecialization(); 169 const TemplateSpecializationType *TST = 170 cast<TemplateSpecializationType>(Context.getCanonicalType(T)); 171 Result.addOuterTemplateArguments( 172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs())); 173 if (ClassTemplate->isMemberSpecialization()) 174 break; 175 } 176 } 177 178 Ctx = Ctx->getParent(); 179 RelativeToPrimary = false; 180 } 181 182 return Result; 183 } 184 185 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const { 186 switch (Kind) { 187 case TemplateInstantiation: 188 case ExceptionSpecInstantiation: 189 case DefaultTemplateArgumentInstantiation: 190 case DefaultFunctionArgumentInstantiation: 191 case ExplicitTemplateArgumentSubstitution: 192 case DeducedTemplateArgumentSubstitution: 193 case PriorTemplateArgumentSubstitution: 194 return true; 195 196 case DefaultTemplateArgumentChecking: 197 return false; 198 } 199 200 llvm_unreachable("Invalid InstantiationKind!"); 201 } 202 203 void Sema::InstantiatingTemplate::Initialize( 204 ActiveTemplateInstantiation::InstantiationKind Kind, 205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, 207 sema::TemplateDeductionInfo *DeductionInfo) { 208 SavedInNonInstantiationSFINAEContext = 209 SemaRef.InNonInstantiationSFINAEContext; 210 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); 211 if (!Invalid) { 212 ActiveTemplateInstantiation Inst; 213 Inst.Kind = Kind; 214 Inst.PointOfInstantiation = PointOfInstantiation; 215 Inst.Entity = Entity; 216 Inst.Template = Template; 217 Inst.TemplateArgs = TemplateArgs.data(); 218 Inst.NumTemplateArgs = TemplateArgs.size(); 219 Inst.DeductionInfo = DeductionInfo; 220 Inst.InstantiationRange = InstantiationRange; 221 SemaRef.InNonInstantiationSFINAEContext = false; 222 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 223 if (!Inst.isInstantiationRecord()) 224 ++SemaRef.NonInstantiationEntries; 225 } 226 } 227 228 Sema::InstantiatingTemplate:: 229 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 230 Decl *Entity, 231 SourceRange InstantiationRange) 232 : SemaRef(SemaRef) 233 { 234 Initialize(ActiveTemplateInstantiation::TemplateInstantiation, 235 PointOfInstantiation, InstantiationRange, Entity); 236 } 237 238 Sema::InstantiatingTemplate:: 239 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 240 FunctionDecl *Entity, ExceptionSpecification, 241 SourceRange InstantiationRange) 242 : SemaRef(SemaRef) 243 { 244 Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation, 245 PointOfInstantiation, InstantiationRange, Entity); 246 } 247 248 Sema::InstantiatingTemplate:: 249 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 250 TemplateDecl *Template, 251 ArrayRef<TemplateArgument> TemplateArgs, 252 SourceRange InstantiationRange) 253 : SemaRef(SemaRef) 254 { 255 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation, 256 PointOfInstantiation, InstantiationRange, 257 Template, nullptr, TemplateArgs); 258 } 259 260 Sema::InstantiatingTemplate:: 261 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 262 FunctionTemplateDecl *FunctionTemplate, 263 ArrayRef<TemplateArgument> TemplateArgs, 264 ActiveTemplateInstantiation::InstantiationKind Kind, 265 sema::TemplateDeductionInfo &DeductionInfo, 266 SourceRange InstantiationRange) 267 : SemaRef(SemaRef) 268 { 269 Initialize(Kind, PointOfInstantiation, InstantiationRange, 270 FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo); 271 } 272 273 Sema::InstantiatingTemplate:: 274 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 275 ClassTemplatePartialSpecializationDecl *PartialSpec, 276 ArrayRef<TemplateArgument> TemplateArgs, 277 sema::TemplateDeductionInfo &DeductionInfo, 278 SourceRange InstantiationRange) 279 : SemaRef(SemaRef) 280 { 281 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution, 282 PointOfInstantiation, InstantiationRange, 283 PartialSpec, nullptr, TemplateArgs, &DeductionInfo); 284 } 285 286 Sema::InstantiatingTemplate::InstantiatingTemplate( 287 Sema &SemaRef, SourceLocation PointOfInstantiation, 288 VarTemplatePartialSpecializationDecl *PartialSpec, 289 ArrayRef<TemplateArgument> TemplateArgs, 290 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 291 : SemaRef(SemaRef) 292 { 293 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution, 294 PointOfInstantiation, InstantiationRange, 295 PartialSpec, nullptr, TemplateArgs, &DeductionInfo); 296 } 297 298 Sema::InstantiatingTemplate:: 299 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 300 ParmVarDecl *Param, 301 ArrayRef<TemplateArgument> TemplateArgs, 302 SourceRange InstantiationRange) 303 : SemaRef(SemaRef) 304 { 305 Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation, 306 PointOfInstantiation, InstantiationRange, 307 Param, nullptr, TemplateArgs); 308 } 309 310 311 Sema::InstantiatingTemplate:: 312 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 313 NamedDecl *Template, NonTypeTemplateParmDecl *Param, 314 ArrayRef<TemplateArgument> TemplateArgs, 315 SourceRange InstantiationRange) 316 : SemaRef(SemaRef) 317 { 318 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution, 319 PointOfInstantiation, InstantiationRange, 320 Param, Template, TemplateArgs); 321 } 322 323 Sema::InstantiatingTemplate:: 324 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 325 NamedDecl *Template, TemplateTemplateParmDecl *Param, 326 ArrayRef<TemplateArgument> TemplateArgs, 327 SourceRange InstantiationRange) 328 : SemaRef(SemaRef) 329 { 330 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution, 331 PointOfInstantiation, InstantiationRange, 332 Param, Template, TemplateArgs); 333 } 334 335 Sema::InstantiatingTemplate:: 336 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 337 TemplateDecl *Template, NamedDecl *Param, 338 ArrayRef<TemplateArgument> TemplateArgs, 339 SourceRange InstantiationRange) 340 : SemaRef(SemaRef) 341 { 342 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking, 343 PointOfInstantiation, InstantiationRange, 344 Param, Template, TemplateArgs); 345 } 346 347 void Sema::InstantiatingTemplate::Clear() { 348 if (!Invalid) { 349 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) { 350 assert(SemaRef.NonInstantiationEntries > 0); 351 --SemaRef.NonInstantiationEntries; 352 } 353 SemaRef.InNonInstantiationSFINAEContext 354 = SavedInNonInstantiationSFINAEContext; 355 356 // Name lookup no longer looks in this template's defining module. 357 assert(SemaRef.ActiveTemplateInstantiations.size() >= 358 SemaRef.ActiveTemplateInstantiationLookupModules.size() && 359 "forgot to remove a lookup module for a template instantiation"); 360 if (SemaRef.ActiveTemplateInstantiations.size() == 361 SemaRef.ActiveTemplateInstantiationLookupModules.size()) { 362 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back()) 363 SemaRef.LookupModulesCache.erase(M); 364 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back(); 365 } 366 367 SemaRef.ActiveTemplateInstantiations.pop_back(); 368 Invalid = true; 369 } 370 } 371 372 bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 373 SourceLocation PointOfInstantiation, 374 SourceRange InstantiationRange) { 375 assert(SemaRef.NonInstantiationEntries <= 376 SemaRef.ActiveTemplateInstantiations.size()); 377 if ((SemaRef.ActiveTemplateInstantiations.size() - 378 SemaRef.NonInstantiationEntries) 379 <= SemaRef.getLangOpts().InstantiationDepth) 380 return false; 381 382 SemaRef.Diag(PointOfInstantiation, 383 diag::err_template_recursion_depth_exceeded) 384 << SemaRef.getLangOpts().InstantiationDepth 385 << InstantiationRange; 386 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 387 << SemaRef.getLangOpts().InstantiationDepth; 388 return true; 389 } 390 391 /// \brief Prints the current instantiation stack through a series of 392 /// notes. 393 void Sema::PrintInstantiationStack() { 394 // Determine which template instantiations to skip, if any. 395 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart; 396 unsigned Limit = Diags.getTemplateBacktraceLimit(); 397 if (Limit && Limit < ActiveTemplateInstantiations.size()) { 398 SkipStart = Limit / 2 + Limit % 2; 399 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2; 400 } 401 402 // FIXME: In all of these cases, we need to show the template arguments 403 unsigned InstantiationIdx = 0; 404 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator 405 Active = ActiveTemplateInstantiations.rbegin(), 406 ActiveEnd = ActiveTemplateInstantiations.rend(); 407 Active != ActiveEnd; 408 ++Active, ++InstantiationIdx) { 409 // Skip this instantiation? 410 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { 411 if (InstantiationIdx == SkipStart) { 412 // Note that we're skipping instantiations. 413 Diags.Report(Active->PointOfInstantiation, 414 diag::note_instantiation_contexts_suppressed) 415 << unsigned(ActiveTemplateInstantiations.size() - Limit); 416 } 417 continue; 418 } 419 420 switch (Active->Kind) { 421 case ActiveTemplateInstantiation::TemplateInstantiation: { 422 Decl *D = Active->Entity; 423 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 424 unsigned DiagID = diag::note_template_member_class_here; 425 if (isa<ClassTemplateSpecializationDecl>(Record)) 426 DiagID = diag::note_template_class_instantiation_here; 427 Diags.Report(Active->PointOfInstantiation, DiagID) 428 << Context.getTypeDeclType(Record) 429 << Active->InstantiationRange; 430 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 431 unsigned DiagID; 432 if (Function->getPrimaryTemplate()) 433 DiagID = diag::note_function_template_spec_here; 434 else 435 DiagID = diag::note_template_member_function_here; 436 Diags.Report(Active->PointOfInstantiation, DiagID) 437 << Function 438 << Active->InstantiationRange; 439 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 440 Diags.Report(Active->PointOfInstantiation, 441 VD->isStaticDataMember()? 442 diag::note_template_static_data_member_def_here 443 : diag::note_template_variable_def_here) 444 << VD 445 << Active->InstantiationRange; 446 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 447 Diags.Report(Active->PointOfInstantiation, 448 diag::note_template_enum_def_here) 449 << ED 450 << Active->InstantiationRange; 451 } else { 452 Diags.Report(Active->PointOfInstantiation, 453 diag::note_template_type_alias_instantiation_here) 454 << cast<TypeAliasTemplateDecl>(D) 455 << Active->InstantiationRange; 456 } 457 break; 458 } 459 460 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { 461 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity); 462 SmallVector<char, 128> TemplateArgsStr; 463 llvm::raw_svector_ostream OS(TemplateArgsStr); 464 Template->printName(OS); 465 TemplateSpecializationType::PrintTemplateArgumentList(OS, 466 Active->TemplateArgs, 467 Active->NumTemplateArgs, 468 getPrintingPolicy()); 469 Diags.Report(Active->PointOfInstantiation, 470 diag::note_default_arg_instantiation_here) 471 << OS.str() 472 << Active->InstantiationRange; 473 break; 474 } 475 476 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: { 477 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity); 478 Diags.Report(Active->PointOfInstantiation, 479 diag::note_explicit_template_arg_substitution_here) 480 << FnTmpl 481 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 482 Active->TemplateArgs, 483 Active->NumTemplateArgs) 484 << Active->InstantiationRange; 485 break; 486 } 487 488 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 489 if (ClassTemplatePartialSpecializationDecl *PartialSpec = 490 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) { 491 Diags.Report(Active->PointOfInstantiation, 492 diag::note_partial_spec_deduct_instantiation_here) 493 << Context.getTypeDeclType(PartialSpec) 494 << getTemplateArgumentBindingsText( 495 PartialSpec->getTemplateParameters(), 496 Active->TemplateArgs, 497 Active->NumTemplateArgs) 498 << Active->InstantiationRange; 499 } else { 500 FunctionTemplateDecl *FnTmpl 501 = cast<FunctionTemplateDecl>(Active->Entity); 502 Diags.Report(Active->PointOfInstantiation, 503 diag::note_function_template_deduction_instantiation_here) 504 << FnTmpl 505 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 506 Active->TemplateArgs, 507 Active->NumTemplateArgs) 508 << Active->InstantiationRange; 509 } 510 break; 511 512 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: { 513 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity); 514 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 515 516 SmallVector<char, 128> TemplateArgsStr; 517 llvm::raw_svector_ostream OS(TemplateArgsStr); 518 FD->printName(OS); 519 TemplateSpecializationType::PrintTemplateArgumentList(OS, 520 Active->TemplateArgs, 521 Active->NumTemplateArgs, 522 getPrintingPolicy()); 523 Diags.Report(Active->PointOfInstantiation, 524 diag::note_default_function_arg_instantiation_here) 525 << OS.str() 526 << Active->InstantiationRange; 527 break; 528 } 529 530 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: { 531 NamedDecl *Parm = cast<NamedDecl>(Active->Entity); 532 std::string Name; 533 if (!Parm->getName().empty()) 534 Name = std::string(" '") + Parm->getName().str() + "'"; 535 536 TemplateParameterList *TemplateParams = 0; 537 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) 538 TemplateParams = Template->getTemplateParameters(); 539 else 540 TemplateParams = 541 cast<ClassTemplatePartialSpecializationDecl>(Active->Template) 542 ->getTemplateParameters(); 543 Diags.Report(Active->PointOfInstantiation, 544 diag::note_prior_template_arg_substitution) 545 << isa<TemplateTemplateParmDecl>(Parm) 546 << Name 547 << getTemplateArgumentBindingsText(TemplateParams, 548 Active->TemplateArgs, 549 Active->NumTemplateArgs) 550 << Active->InstantiationRange; 551 break; 552 } 553 554 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: { 555 TemplateParameterList *TemplateParams = 0; 556 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) 557 TemplateParams = Template->getTemplateParameters(); 558 else 559 TemplateParams = 560 cast<ClassTemplatePartialSpecializationDecl>(Active->Template) 561 ->getTemplateParameters(); 562 563 Diags.Report(Active->PointOfInstantiation, 564 diag::note_template_default_arg_checking) 565 << getTemplateArgumentBindingsText(TemplateParams, 566 Active->TemplateArgs, 567 Active->NumTemplateArgs) 568 << Active->InstantiationRange; 569 break; 570 } 571 572 case ActiveTemplateInstantiation::ExceptionSpecInstantiation: 573 Diags.Report(Active->PointOfInstantiation, 574 diag::note_template_exception_spec_instantiation_here) 575 << cast<FunctionDecl>(Active->Entity) 576 << Active->InstantiationRange; 577 break; 578 } 579 } 580 } 581 582 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { 583 if (InNonInstantiationSFINAEContext) 584 return Optional<TemplateDeductionInfo *>(0); 585 586 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator 587 Active = ActiveTemplateInstantiations.rbegin(), 588 ActiveEnd = ActiveTemplateInstantiations.rend(); 589 Active != ActiveEnd; 590 ++Active) 591 { 592 switch(Active->Kind) { 593 case ActiveTemplateInstantiation::TemplateInstantiation: 594 // An instantiation of an alias template may or may not be a SFINAE 595 // context, depending on what else is on the stack. 596 if (isa<TypeAliasTemplateDecl>(Active->Entity)) 597 break; 598 // Fall through. 599 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: 600 case ActiveTemplateInstantiation::ExceptionSpecInstantiation: 601 // This is a template instantiation, so there is no SFINAE. 602 return None; 603 604 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: 605 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: 606 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: 607 // A default template argument instantiation and substitution into 608 // template parameters with arguments for prior parameters may or may 609 // not be a SFINAE context; look further up the stack. 610 break; 611 612 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: 613 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 614 // We're either substitution explicitly-specified template arguments 615 // or deduced template arguments, so SFINAE applies. 616 assert(Active->DeductionInfo && "Missing deduction info pointer"); 617 return Active->DeductionInfo; 618 } 619 } 620 621 return None; 622 } 623 624 /// \brief Retrieve the depth and index of a parameter pack. 625 static std::pair<unsigned, unsigned> 626 getDepthAndIndex(NamedDecl *ND) { 627 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND)) 628 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 629 630 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND)) 631 return std::make_pair(NTTP->getDepth(), NTTP->getIndex()); 632 633 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND); 634 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 635 } 636 637 //===----------------------------------------------------------------------===/ 638 // Template Instantiation for Types 639 //===----------------------------------------------------------------------===/ 640 namespace { 641 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { 642 const MultiLevelTemplateArgumentList &TemplateArgs; 643 SourceLocation Loc; 644 DeclarationName Entity; 645 646 public: 647 typedef TreeTransform<TemplateInstantiator> inherited; 648 649 TemplateInstantiator(Sema &SemaRef, 650 const MultiLevelTemplateArgumentList &TemplateArgs, 651 SourceLocation Loc, 652 DeclarationName Entity) 653 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), 654 Entity(Entity) { } 655 656 /// \brief Determine whether the given type \p T has already been 657 /// transformed. 658 /// 659 /// For the purposes of template instantiation, a type has already been 660 /// transformed if it is NULL or if it is not dependent. 661 bool AlreadyTransformed(QualType T); 662 663 /// \brief Returns the location of the entity being instantiated, if known. 664 SourceLocation getBaseLocation() { return Loc; } 665 666 /// \brief Returns the name of the entity being instantiated, if any. 667 DeclarationName getBaseEntity() { return Entity; } 668 669 /// \brief Sets the "base" location and entity when that 670 /// information is known based on another transformation. 671 void setBase(SourceLocation Loc, DeclarationName Entity) { 672 this->Loc = Loc; 673 this->Entity = Entity; 674 } 675 676 bool TryExpandParameterPacks(SourceLocation EllipsisLoc, 677 SourceRange PatternRange, 678 ArrayRef<UnexpandedParameterPack> Unexpanded, 679 bool &ShouldExpand, bool &RetainExpansion, 680 Optional<unsigned> &NumExpansions) { 681 return getSema().CheckParameterPacksForExpansion(EllipsisLoc, 682 PatternRange, Unexpanded, 683 TemplateArgs, 684 ShouldExpand, 685 RetainExpansion, 686 NumExpansions); 687 } 688 689 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { 690 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); 691 } 692 693 TemplateArgument ForgetPartiallySubstitutedPack() { 694 TemplateArgument Result; 695 if (NamedDecl *PartialPack 696 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ 697 MultiLevelTemplateArgumentList &TemplateArgs 698 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); 699 unsigned Depth, Index; 700 std::tie(Depth, Index) = getDepthAndIndex(PartialPack); 701 if (TemplateArgs.hasTemplateArgument(Depth, Index)) { 702 Result = TemplateArgs(Depth, Index); 703 TemplateArgs.setArgument(Depth, Index, TemplateArgument()); 704 } 705 } 706 707 return Result; 708 } 709 710 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { 711 if (Arg.isNull()) 712 return; 713 714 if (NamedDecl *PartialPack 715 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ 716 MultiLevelTemplateArgumentList &TemplateArgs 717 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); 718 unsigned Depth, Index; 719 std::tie(Depth, Index) = getDepthAndIndex(PartialPack); 720 TemplateArgs.setArgument(Depth, Index, Arg); 721 } 722 } 723 724 /// \brief Transform the given declaration by instantiating a reference to 725 /// this declaration. 726 Decl *TransformDecl(SourceLocation Loc, Decl *D); 727 728 void transformAttrs(Decl *Old, Decl *New) { 729 SemaRef.InstantiateAttrs(TemplateArgs, Old, New); 730 } 731 732 void transformedLocalDecl(Decl *Old, Decl *New) { 733 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); 734 } 735 736 /// \brief Transform the definition of the given declaration by 737 /// instantiating it. 738 Decl *TransformDefinition(SourceLocation Loc, Decl *D); 739 740 /// \brief Transform the first qualifier within a scope by instantiating the 741 /// declaration. 742 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); 743 744 /// \brief Rebuild the exception declaration and register the declaration 745 /// as an instantiated local. 746 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, 747 TypeSourceInfo *Declarator, 748 SourceLocation StartLoc, 749 SourceLocation NameLoc, 750 IdentifierInfo *Name); 751 752 /// \brief Rebuild the Objective-C exception declaration and register the 753 /// declaration as an instantiated local. 754 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 755 TypeSourceInfo *TSInfo, QualType T); 756 757 /// \brief Check for tag mismatches when instantiating an 758 /// elaborated type. 759 QualType RebuildElaboratedType(SourceLocation KeywordLoc, 760 ElaboratedTypeKeyword Keyword, 761 NestedNameSpecifierLoc QualifierLoc, 762 QualType T); 763 764 TemplateName TransformTemplateName(CXXScopeSpec &SS, 765 TemplateName Name, 766 SourceLocation NameLoc, 767 QualType ObjectType = QualType(), 768 NamedDecl *FirstQualifierInScope = 0); 769 770 ExprResult TransformPredefinedExpr(PredefinedExpr *E); 771 ExprResult TransformDeclRefExpr(DeclRefExpr *E); 772 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); 773 774 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, 775 NonTypeTemplateParmDecl *D); 776 ExprResult TransformSubstNonTypeTemplateParmPackExpr( 777 SubstNonTypeTemplateParmPackExpr *E); 778 779 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference. 780 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc); 781 782 /// \brief Transform a reference to a function parameter pack. 783 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, 784 ParmVarDecl *PD); 785 786 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't 787 /// expand a function parameter pack reference which refers to an expanded 788 /// pack. 789 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E); 790 791 QualType TransformFunctionProtoType(TypeLocBuilder &TLB, 792 FunctionProtoTypeLoc TL); 793 QualType TransformFunctionProtoType(TypeLocBuilder &TLB, 794 FunctionProtoTypeLoc TL, 795 CXXRecordDecl *ThisContext, 796 unsigned ThisTypeQuals); 797 798 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, 799 int indexAdjustment, 800 Optional<unsigned> NumExpansions, 801 bool ExpectParameterPack); 802 803 /// \brief Transforms a template type parameter type by performing 804 /// substitution of the corresponding template type argument. 805 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, 806 TemplateTypeParmTypeLoc TL); 807 808 /// \brief Transforms an already-substituted template type parameter pack 809 /// into either itself (if we aren't substituting into its pack expansion) 810 /// or the appropriate substituted argument. 811 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, 812 SubstTemplateTypeParmPackTypeLoc TL); 813 814 ExprResult TransformCallExpr(CallExpr *CE) { 815 getSema().CallsUndergoingInstantiation.push_back(CE); 816 ExprResult Result = 817 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE); 818 getSema().CallsUndergoingInstantiation.pop_back(); 819 return Result; 820 } 821 822 ExprResult TransformLambdaExpr(LambdaExpr *E) { 823 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 824 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E); 825 } 826 827 ExprResult TransformLambdaScope(LambdaExpr *E, 828 CXXMethodDecl *NewCallOperator, 829 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) { 830 CXXMethodDecl *const OldCallOperator = E->getCallOperator(); 831 // In the generic lambda case, we set the NewTemplate to be considered 832 // an "instantiation" of the OldTemplate. 833 if (FunctionTemplateDecl *const NewCallOperatorTemplate = 834 NewCallOperator->getDescribedFunctionTemplate()) { 835 836 FunctionTemplateDecl *const OldCallOperatorTemplate = 837 OldCallOperator->getDescribedFunctionTemplate(); 838 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate( 839 OldCallOperatorTemplate); 840 } else 841 // For a non-generic lambda we set the NewCallOperator to 842 // be an instantiation of the OldCallOperator. 843 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator, 844 TSK_ImplicitInstantiation); 845 846 return inherited::TransformLambdaScope(E, NewCallOperator, 847 InitCaptureExprsAndTypes); 848 } 849 TemplateParameterList *TransformTemplateParameterList( 850 TemplateParameterList *OrigTPL) { 851 if (!OrigTPL || !OrigTPL->size()) return OrigTPL; 852 853 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext(); 854 TemplateDeclInstantiator DeclInstantiator(getSema(), 855 /* DeclContext *Owner */ Owner, TemplateArgs); 856 return DeclInstantiator.SubstTemplateParams(OrigTPL); 857 } 858 private: 859 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm, 860 SourceLocation loc, 861 TemplateArgument arg); 862 }; 863 } 864 865 bool TemplateInstantiator::AlreadyTransformed(QualType T) { 866 if (T.isNull()) 867 return true; 868 869 if (T->isInstantiationDependentType() || T->isVariablyModifiedType()) 870 return false; 871 872 getSema().MarkDeclarationsReferencedInType(Loc, T); 873 return true; 874 } 875 876 static TemplateArgument 877 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) { 878 assert(S.ArgumentPackSubstitutionIndex >= 0); 879 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 880 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex]; 881 if (Arg.isPackExpansion()) 882 Arg = Arg.getPackExpansionPattern(); 883 return Arg; 884 } 885 886 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { 887 if (!D) 888 return 0; 889 890 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { 891 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 892 // If the corresponding template argument is NULL or non-existent, it's 893 // because we are performing instantiation from explicitly-specified 894 // template arguments in a function template, but there were some 895 // arguments left unspecified. 896 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 897 TTP->getPosition())) 898 return D; 899 900 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); 901 902 if (TTP->isParameterPack()) { 903 assert(Arg.getKind() == TemplateArgument::Pack && 904 "Missing argument pack"); 905 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 906 } 907 908 TemplateName Template = Arg.getAsTemplate(); 909 assert(!Template.isNull() && Template.getAsTemplateDecl() && 910 "Wrong kind of template template argument"); 911 return Template.getAsTemplateDecl(); 912 } 913 914 // Fall through to find the instantiated declaration for this template 915 // template parameter. 916 } 917 918 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs); 919 } 920 921 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { 922 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); 923 if (!Inst) 924 return 0; 925 926 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); 927 return Inst; 928 } 929 930 NamedDecl * 931 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, 932 SourceLocation Loc) { 933 // If the first part of the nested-name-specifier was a template type 934 // parameter, instantiate that type parameter down to a tag type. 935 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { 936 const TemplateTypeParmType *TTP 937 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); 938 939 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 940 // FIXME: This needs testing w/ member access expressions. 941 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); 942 943 if (TTP->isParameterPack()) { 944 assert(Arg.getKind() == TemplateArgument::Pack && 945 "Missing argument pack"); 946 947 if (getSema().ArgumentPackSubstitutionIndex == -1) 948 return 0; 949 950 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 951 } 952 953 QualType T = Arg.getAsType(); 954 if (T.isNull()) 955 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 956 957 if (const TagType *Tag = T->getAs<TagType>()) 958 return Tag->getDecl(); 959 960 // The resulting type is not a tag; complain. 961 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; 962 return 0; 963 } 964 } 965 966 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 967 } 968 969 VarDecl * 970 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, 971 TypeSourceInfo *Declarator, 972 SourceLocation StartLoc, 973 SourceLocation NameLoc, 974 IdentifierInfo *Name) { 975 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, 976 StartLoc, NameLoc, Name); 977 if (Var) 978 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 979 return Var; 980 } 981 982 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 983 TypeSourceInfo *TSInfo, 984 QualType T) { 985 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); 986 if (Var) 987 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 988 return Var; 989 } 990 991 QualType 992 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc, 993 ElaboratedTypeKeyword Keyword, 994 NestedNameSpecifierLoc QualifierLoc, 995 QualType T) { 996 if (const TagType *TT = T->getAs<TagType>()) { 997 TagDecl* TD = TT->getDecl(); 998 999 SourceLocation TagLocation = KeywordLoc; 1000 1001 IdentifierInfo *Id = TD->getIdentifier(); 1002 1003 // TODO: should we even warn on struct/class mismatches for this? Seems 1004 // like it's likely to produce a lot of spurious errors. 1005 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) { 1006 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword); 1007 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false, 1008 TagLocation, *Id)) { 1009 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) 1010 << Id 1011 << FixItHint::CreateReplacement(SourceRange(TagLocation), 1012 TD->getKindName()); 1013 SemaRef.Diag(TD->getLocation(), diag::note_previous_use); 1014 } 1015 } 1016 } 1017 1018 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc, 1019 Keyword, 1020 QualifierLoc, 1021 T); 1022 } 1023 1024 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS, 1025 TemplateName Name, 1026 SourceLocation NameLoc, 1027 QualType ObjectType, 1028 NamedDecl *FirstQualifierInScope) { 1029 if (TemplateTemplateParmDecl *TTP 1030 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) { 1031 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 1032 // If the corresponding template argument is NULL or non-existent, it's 1033 // because we are performing instantiation from explicitly-specified 1034 // template arguments in a function template, but there were some 1035 // arguments left unspecified. 1036 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 1037 TTP->getPosition())) 1038 return Name; 1039 1040 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); 1041 1042 if (TTP->isParameterPack()) { 1043 assert(Arg.getKind() == TemplateArgument::Pack && 1044 "Missing argument pack"); 1045 1046 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1047 // We have the template argument pack to substitute, but we're not 1048 // actually expanding the enclosing pack expansion yet. So, just 1049 // keep the entire argument pack. 1050 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg); 1051 } 1052 1053 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1054 } 1055 1056 TemplateName Template = Arg.getAsTemplate(); 1057 assert(!Template.isNull() && "Null template template argument"); 1058 1059 // We don't ever want to substitute for a qualified template name, since 1060 // the qualifier is handled separately. So, look through the qualified 1061 // template name to its underlying declaration. 1062 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 1063 Template = TemplateName(QTN->getTemplateDecl()); 1064 1065 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template); 1066 return Template; 1067 } 1068 } 1069 1070 if (SubstTemplateTemplateParmPackStorage *SubstPack 1071 = Name.getAsSubstTemplateTemplateParmPack()) { 1072 if (getSema().ArgumentPackSubstitutionIndex == -1) 1073 return Name; 1074 1075 TemplateArgument Arg = SubstPack->getArgumentPack(); 1076 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1077 return Arg.getAsTemplate(); 1078 } 1079 1080 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, 1081 FirstQualifierInScope); 1082 } 1083 1084 ExprResult 1085 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { 1086 if (!E->isTypeDependent()) 1087 return SemaRef.Owned(E); 1088 1089 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType()); 1090 } 1091 1092 ExprResult 1093 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, 1094 NonTypeTemplateParmDecl *NTTP) { 1095 // If the corresponding template argument is NULL or non-existent, it's 1096 // because we are performing instantiation from explicitly-specified 1097 // template arguments in a function template, but there were some 1098 // arguments left unspecified. 1099 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), 1100 NTTP->getPosition())) 1101 return SemaRef.Owned(E); 1102 1103 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); 1104 if (NTTP->isParameterPack()) { 1105 assert(Arg.getKind() == TemplateArgument::Pack && 1106 "Missing argument pack"); 1107 1108 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1109 // We have an argument pack, but we can't select a particular argument 1110 // out of it yet. Therefore, we'll build an expression to hold on to that 1111 // argument pack. 1112 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, 1113 E->getLocation(), 1114 NTTP->getDeclName()); 1115 if (TargetType.isNull()) 1116 return ExprError(); 1117 1118 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType, 1119 NTTP, 1120 E->getLocation(), 1121 Arg); 1122 } 1123 1124 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1125 } 1126 1127 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg); 1128 } 1129 1130 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( 1131 NonTypeTemplateParmDecl *parm, 1132 SourceLocation loc, 1133 TemplateArgument arg) { 1134 ExprResult result; 1135 QualType type; 1136 1137 // The template argument itself might be an expression, in which 1138 // case we just return that expression. 1139 if (arg.getKind() == TemplateArgument::Expression) { 1140 Expr *argExpr = arg.getAsExpr(); 1141 result = SemaRef.Owned(argExpr); 1142 type = argExpr->getType(); 1143 1144 } else if (arg.getKind() == TemplateArgument::Declaration || 1145 arg.getKind() == TemplateArgument::NullPtr) { 1146 ValueDecl *VD; 1147 if (arg.getKind() == TemplateArgument::Declaration) { 1148 VD = cast<ValueDecl>(arg.getAsDecl()); 1149 1150 // Find the instantiation of the template argument. This is 1151 // required for nested templates. 1152 VD = cast_or_null<ValueDecl>( 1153 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs)); 1154 if (!VD) 1155 return ExprError(); 1156 } else { 1157 // Propagate NULL template argument. 1158 VD = 0; 1159 } 1160 1161 // Derive the type we want the substituted decl to have. This had 1162 // better be non-dependent, or these checks will have serious problems. 1163 if (parm->isExpandedParameterPack()) { 1164 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex); 1165 } else if (parm->isParameterPack() && 1166 isa<PackExpansionType>(parm->getType())) { 1167 type = SemaRef.SubstType( 1168 cast<PackExpansionType>(parm->getType())->getPattern(), 1169 TemplateArgs, loc, parm->getDeclName()); 1170 } else { 1171 type = SemaRef.SubstType(parm->getType(), TemplateArgs, 1172 loc, parm->getDeclName()); 1173 } 1174 assert(!type.isNull() && "type substitution failed for param type"); 1175 assert(!type->isDependentType() && "param type still dependent"); 1176 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc); 1177 1178 if (!result.isInvalid()) type = result.get()->getType(); 1179 } else { 1180 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc); 1181 1182 // Note that this type can be different from the type of 'result', 1183 // e.g. if it's an enum type. 1184 type = arg.getIntegralType(); 1185 } 1186 if (result.isInvalid()) return ExprError(); 1187 1188 Expr *resultExpr = result.take(); 1189 return SemaRef.Owned(new (SemaRef.Context) 1190 SubstNonTypeTemplateParmExpr(type, 1191 resultExpr->getValueKind(), 1192 loc, parm, resultExpr)); 1193 } 1194 1195 ExprResult 1196 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( 1197 SubstNonTypeTemplateParmPackExpr *E) { 1198 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1199 // We aren't expanding the parameter pack, so just return ourselves. 1200 return getSema().Owned(E); 1201 } 1202 1203 TemplateArgument Arg = E->getArgumentPack(); 1204 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1205 return transformNonTypeTemplateParmRef(E->getParameterPack(), 1206 E->getParameterPackLocation(), 1207 Arg); 1208 } 1209 1210 ExprResult 1211 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD, 1212 SourceLocation Loc) { 1213 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc); 1214 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD); 1215 } 1216 1217 ExprResult 1218 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) { 1219 if (getSema().ArgumentPackSubstitutionIndex != -1) { 1220 // We can expand this parameter pack now. 1221 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex); 1222 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D)); 1223 if (!VD) 1224 return ExprError(); 1225 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc()); 1226 } 1227 1228 QualType T = TransformType(E->getType()); 1229 if (T.isNull()) 1230 return ExprError(); 1231 1232 // Transform each of the parameter expansions into the corresponding 1233 // parameters in the instantiation of the function decl. 1234 SmallVector<Decl *, 8> Parms; 1235 Parms.reserve(E->getNumExpansions()); 1236 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end(); 1237 I != End; ++I) { 1238 ParmVarDecl *D = 1239 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I)); 1240 if (!D) 1241 return ExprError(); 1242 Parms.push_back(D); 1243 } 1244 1245 return FunctionParmPackExpr::Create(getSema().Context, T, 1246 E->getParameterPack(), 1247 E->getParameterPackLocation(), Parms); 1248 } 1249 1250 ExprResult 1251 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E, 1252 ParmVarDecl *PD) { 1253 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 1254 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 1255 = getSema().CurrentInstantiationScope->findInstantiationOf(PD); 1256 assert(Found && "no instantiation for parameter pack"); 1257 1258 Decl *TransformedDecl; 1259 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) { 1260 // If this is a reference to a function parameter pack which we can substitute 1261 // but can't yet expand, build a FunctionParmPackExpr for it. 1262 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1263 QualType T = TransformType(E->getType()); 1264 if (T.isNull()) 1265 return ExprError(); 1266 return FunctionParmPackExpr::Create(getSema().Context, T, PD, 1267 E->getExprLoc(), *Pack); 1268 } 1269 1270 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex]; 1271 } else { 1272 TransformedDecl = Found->get<Decl*>(); 1273 } 1274 1275 // We have either an unexpanded pack or a specific expansion. 1276 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl), 1277 E->getExprLoc()); 1278 } 1279 1280 ExprResult 1281 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { 1282 NamedDecl *D = E->getDecl(); 1283 1284 // Handle references to non-type template parameters and non-type template 1285 // parameter packs. 1286 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { 1287 if (NTTP->getDepth() < TemplateArgs.getNumLevels()) 1288 return TransformTemplateParmRefExpr(E, NTTP); 1289 1290 // We have a non-type template parameter that isn't fully substituted; 1291 // FindInstantiatedDecl will find it in the local instantiation scope. 1292 } 1293 1294 // Handle references to function parameter packs. 1295 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) 1296 if (PD->isParameterPack()) 1297 return TransformFunctionParmPackRefExpr(E, PD); 1298 1299 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E); 1300 } 1301 1302 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( 1303 CXXDefaultArgExpr *E) { 1304 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> 1305 getDescribedFunctionTemplate() && 1306 "Default arg expressions are never formed in dependent cases."); 1307 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(), 1308 cast<FunctionDecl>(E->getParam()->getDeclContext()), 1309 E->getParam()); 1310 } 1311 1312 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, 1313 FunctionProtoTypeLoc TL) { 1314 // We need a local instantiation scope for this function prototype. 1315 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 1316 return inherited::TransformFunctionProtoType(TLB, TL); 1317 } 1318 1319 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, 1320 FunctionProtoTypeLoc TL, 1321 CXXRecordDecl *ThisContext, 1322 unsigned ThisTypeQuals) { 1323 // We need a local instantiation scope for this function prototype. 1324 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 1325 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext, 1326 ThisTypeQuals); 1327 } 1328 1329 ParmVarDecl * 1330 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm, 1331 int indexAdjustment, 1332 Optional<unsigned> NumExpansions, 1333 bool ExpectParameterPack) { 1334 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment, 1335 NumExpansions, ExpectParameterPack); 1336 } 1337 1338 QualType 1339 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, 1340 TemplateTypeParmTypeLoc TL) { 1341 const TemplateTypeParmType *T = TL.getTypePtr(); 1342 if (T->getDepth() < TemplateArgs.getNumLevels()) { 1343 // Replace the template type parameter with its corresponding 1344 // template argument. 1345 1346 // If the corresponding template argument is NULL or doesn't exist, it's 1347 // because we are performing instantiation from explicitly-specified 1348 // template arguments in a function template class, but there were some 1349 // arguments left unspecified. 1350 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) { 1351 TemplateTypeParmTypeLoc NewTL 1352 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType()); 1353 NewTL.setNameLoc(TL.getNameLoc()); 1354 return TL.getType(); 1355 } 1356 1357 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); 1358 1359 if (T->isParameterPack()) { 1360 assert(Arg.getKind() == TemplateArgument::Pack && 1361 "Missing argument pack"); 1362 1363 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1364 // We have the template argument pack, but we're not expanding the 1365 // enclosing pack expansion yet. Just save the template argument 1366 // pack for later substitution. 1367 QualType Result 1368 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg); 1369 SubstTemplateTypeParmPackTypeLoc NewTL 1370 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result); 1371 NewTL.setNameLoc(TL.getNameLoc()); 1372 return Result; 1373 } 1374 1375 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1376 } 1377 1378 assert(Arg.getKind() == TemplateArgument::Type && 1379 "Template argument kind mismatch"); 1380 1381 QualType Replacement = Arg.getAsType(); 1382 1383 // TODO: only do this uniquing once, at the start of instantiation. 1384 QualType Result 1385 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement); 1386 SubstTemplateTypeParmTypeLoc NewTL 1387 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); 1388 NewTL.setNameLoc(TL.getNameLoc()); 1389 return Result; 1390 } 1391 1392 // The template type parameter comes from an inner template (e.g., 1393 // the template parameter list of a member template inside the 1394 // template we are instantiating). Create a new template type 1395 // parameter with the template "level" reduced by one. 1396 TemplateTypeParmDecl *NewTTPDecl = 0; 1397 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) 1398 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( 1399 TransformDecl(TL.getNameLoc(), OldTTPDecl)); 1400 1401 QualType Result 1402 = getSema().Context.getTemplateTypeParmType(T->getDepth() 1403 - TemplateArgs.getNumLevels(), 1404 T->getIndex(), 1405 T->isParameterPack(), 1406 NewTTPDecl); 1407 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 1408 NewTL.setNameLoc(TL.getNameLoc()); 1409 return Result; 1410 } 1411 1412 QualType 1413 TemplateInstantiator::TransformSubstTemplateTypeParmPackType( 1414 TypeLocBuilder &TLB, 1415 SubstTemplateTypeParmPackTypeLoc TL) { 1416 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1417 // We aren't expanding the parameter pack, so just return ourselves. 1418 SubstTemplateTypeParmPackTypeLoc NewTL 1419 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType()); 1420 NewTL.setNameLoc(TL.getNameLoc()); 1421 return TL.getType(); 1422 } 1423 1424 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack(); 1425 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1426 QualType Result = Arg.getAsType(); 1427 1428 Result = getSema().Context.getSubstTemplateTypeParmType( 1429 TL.getTypePtr()->getReplacedParameter(), 1430 Result); 1431 SubstTemplateTypeParmTypeLoc NewTL 1432 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); 1433 NewTL.setNameLoc(TL.getNameLoc()); 1434 return Result; 1435 } 1436 1437 /// \brief Perform substitution on the type T with a given set of template 1438 /// arguments. 1439 /// 1440 /// This routine substitutes the given template arguments into the 1441 /// type T and produces the instantiated type. 1442 /// 1443 /// \param T the type into which the template arguments will be 1444 /// substituted. If this type is not dependent, it will be returned 1445 /// immediately. 1446 /// 1447 /// \param Args the template arguments that will be 1448 /// substituted for the top-level template parameters within T. 1449 /// 1450 /// \param Loc the location in the source code where this substitution 1451 /// is being performed. It will typically be the location of the 1452 /// declarator (if we're instantiating the type of some declaration) 1453 /// or the location of the type in the source code (if, e.g., we're 1454 /// instantiating the type of a cast expression). 1455 /// 1456 /// \param Entity the name of the entity associated with a declaration 1457 /// being instantiated (if any). May be empty to indicate that there 1458 /// is no such entity (if, e.g., this is a type that occurs as part of 1459 /// a cast expression) or that the entity has no name (e.g., an 1460 /// unnamed function parameter). 1461 /// 1462 /// \returns If the instantiation succeeds, the instantiated 1463 /// type. Otherwise, produces diagnostics and returns a NULL type. 1464 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, 1465 const MultiLevelTemplateArgumentList &Args, 1466 SourceLocation Loc, 1467 DeclarationName Entity) { 1468 assert(!ActiveTemplateInstantiations.empty() && 1469 "Cannot perform an instantiation without some context on the " 1470 "instantiation stack"); 1471 1472 if (!T->getType()->isInstantiationDependentType() && 1473 !T->getType()->isVariablyModifiedType()) 1474 return T; 1475 1476 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 1477 return Instantiator.TransformType(T); 1478 } 1479 1480 TypeSourceInfo *Sema::SubstType(TypeLoc TL, 1481 const MultiLevelTemplateArgumentList &Args, 1482 SourceLocation Loc, 1483 DeclarationName Entity) { 1484 assert(!ActiveTemplateInstantiations.empty() && 1485 "Cannot perform an instantiation without some context on the " 1486 "instantiation stack"); 1487 1488 if (TL.getType().isNull()) 1489 return 0; 1490 1491 if (!TL.getType()->isInstantiationDependentType() && 1492 !TL.getType()->isVariablyModifiedType()) { 1493 // FIXME: Make a copy of the TypeLoc data here, so that we can 1494 // return a new TypeSourceInfo. Inefficient! 1495 TypeLocBuilder TLB; 1496 TLB.pushFullCopy(TL); 1497 return TLB.getTypeSourceInfo(Context, TL.getType()); 1498 } 1499 1500 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 1501 TypeLocBuilder TLB; 1502 TLB.reserve(TL.getFullDataSize()); 1503 QualType Result = Instantiator.TransformType(TLB, TL); 1504 if (Result.isNull()) 1505 return 0; 1506 1507 return TLB.getTypeSourceInfo(Context, Result); 1508 } 1509 1510 /// Deprecated form of the above. 1511 QualType Sema::SubstType(QualType T, 1512 const MultiLevelTemplateArgumentList &TemplateArgs, 1513 SourceLocation Loc, DeclarationName Entity) { 1514 assert(!ActiveTemplateInstantiations.empty() && 1515 "Cannot perform an instantiation without some context on the " 1516 "instantiation stack"); 1517 1518 // If T is not a dependent type or a variably-modified type, there 1519 // is nothing to do. 1520 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) 1521 return T; 1522 1523 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 1524 return Instantiator.TransformType(T); 1525 } 1526 1527 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { 1528 if (T->getType()->isInstantiationDependentType() || 1529 T->getType()->isVariablyModifiedType()) 1530 return true; 1531 1532 TypeLoc TL = T->getTypeLoc().IgnoreParens(); 1533 if (!TL.getAs<FunctionProtoTypeLoc>()) 1534 return false; 1535 1536 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>(); 1537 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) { 1538 ParmVarDecl *P = FP.getParam(I); 1539 1540 // This must be synthesized from a typedef. 1541 if (!P) continue; 1542 1543 // The parameter's type as written might be dependent even if the 1544 // decayed type was not dependent. 1545 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo()) 1546 if (TSInfo->getType()->isInstantiationDependentType()) 1547 return true; 1548 1549 // TODO: currently we always rebuild expressions. When we 1550 // properly get lazier about this, we should use the same 1551 // logic to avoid rebuilding prototypes here. 1552 if (P->hasDefaultArg()) 1553 return true; 1554 } 1555 1556 return false; 1557 } 1558 1559 /// A form of SubstType intended specifically for instantiating the 1560 /// type of a FunctionDecl. Its purpose is solely to force the 1561 /// instantiation of default-argument expressions. 1562 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T, 1563 const MultiLevelTemplateArgumentList &Args, 1564 SourceLocation Loc, 1565 DeclarationName Entity, 1566 CXXRecordDecl *ThisContext, 1567 unsigned ThisTypeQuals) { 1568 assert(!ActiveTemplateInstantiations.empty() && 1569 "Cannot perform an instantiation without some context on the " 1570 "instantiation stack"); 1571 1572 if (!NeedsInstantiationAsFunctionType(T)) 1573 return T; 1574 1575 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 1576 1577 TypeLocBuilder TLB; 1578 1579 TypeLoc TL = T->getTypeLoc(); 1580 TLB.reserve(TL.getFullDataSize()); 1581 1582 QualType Result; 1583 1584 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) { 1585 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext, 1586 ThisTypeQuals); 1587 } else { 1588 Result = Instantiator.TransformType(TLB, TL); 1589 } 1590 if (Result.isNull()) 1591 return 0; 1592 1593 return TLB.getTypeSourceInfo(Context, Result); 1594 } 1595 1596 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, 1597 const MultiLevelTemplateArgumentList &TemplateArgs, 1598 int indexAdjustment, 1599 Optional<unsigned> NumExpansions, 1600 bool ExpectParameterPack) { 1601 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); 1602 TypeSourceInfo *NewDI = 0; 1603 1604 TypeLoc OldTL = OldDI->getTypeLoc(); 1605 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { 1606 1607 // We have a function parameter pack. Substitute into the pattern of the 1608 // expansion. 1609 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, 1610 OldParm->getLocation(), OldParm->getDeclName()); 1611 if (!NewDI) 1612 return 0; 1613 1614 if (NewDI->getType()->containsUnexpandedParameterPack()) { 1615 // We still have unexpanded parameter packs, which means that 1616 // our function parameter is still a function parameter pack. 1617 // Therefore, make its type a pack expansion type. 1618 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(), 1619 NumExpansions); 1620 } else if (ExpectParameterPack) { 1621 // We expected to get a parameter pack but didn't (because the type 1622 // itself is not a pack expansion type), so complain. This can occur when 1623 // the substitution goes through an alias template that "loses" the 1624 // pack expansion. 1625 Diag(OldParm->getLocation(), 1626 diag::err_function_parameter_pack_without_parameter_packs) 1627 << NewDI->getType(); 1628 return 0; 1629 } 1630 } else { 1631 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), 1632 OldParm->getDeclName()); 1633 } 1634 1635 if (!NewDI) 1636 return 0; 1637 1638 if (NewDI->getType()->isVoidType()) { 1639 Diag(OldParm->getLocation(), diag::err_param_with_void_type); 1640 return 0; 1641 } 1642 1643 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(), 1644 OldParm->getInnerLocStart(), 1645 OldParm->getLocation(), 1646 OldParm->getIdentifier(), 1647 NewDI->getType(), NewDI, 1648 OldParm->getStorageClass()); 1649 if (!NewParm) 1650 return 0; 1651 1652 // Mark the (new) default argument as uninstantiated (if any). 1653 if (OldParm->hasUninstantiatedDefaultArg()) { 1654 Expr *Arg = OldParm->getUninstantiatedDefaultArg(); 1655 NewParm->setUninstantiatedDefaultArg(Arg); 1656 } else if (OldParm->hasUnparsedDefaultArg()) { 1657 NewParm->setUnparsedDefaultArg(); 1658 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm); 1659 } else if (Expr *Arg = OldParm->getDefaultArg()) 1660 // FIXME: if we non-lazily instantiated non-dependent default args for 1661 // non-dependent parameter types we could remove a bunch of duplicate 1662 // conversion warnings for such arguments. 1663 NewParm->setUninstantiatedDefaultArg(Arg); 1664 1665 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); 1666 1667 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { 1668 // Add the new parameter to the instantiated parameter pack. 1669 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); 1670 } else { 1671 // Introduce an Old -> New mapping 1672 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); 1673 } 1674 1675 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext 1676 // can be anything, is this right ? 1677 NewParm->setDeclContext(CurContext); 1678 1679 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(), 1680 OldParm->getFunctionScopeIndex() + indexAdjustment); 1681 1682 InstantiateAttrs(TemplateArgs, OldParm, NewParm); 1683 1684 return NewParm; 1685 } 1686 1687 /// \brief Substitute the given template arguments into the given set of 1688 /// parameters, producing the set of parameter types that would be generated 1689 /// from such a substitution. 1690 bool Sema::SubstParmTypes(SourceLocation Loc, 1691 ParmVarDecl **Params, unsigned NumParams, 1692 const MultiLevelTemplateArgumentList &TemplateArgs, 1693 SmallVectorImpl<QualType> &ParamTypes, 1694 SmallVectorImpl<ParmVarDecl *> *OutParams) { 1695 assert(!ActiveTemplateInstantiations.empty() && 1696 "Cannot perform an instantiation without some context on the " 1697 "instantiation stack"); 1698 1699 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 1700 DeclarationName()); 1701 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0, 1702 ParamTypes, OutParams); 1703 } 1704 1705 /// \brief Perform substitution on the base class specifiers of the 1706 /// given class template specialization. 1707 /// 1708 /// Produces a diagnostic and returns true on error, returns false and 1709 /// attaches the instantiated base classes to the class template 1710 /// specialization if successful. 1711 bool 1712 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 1713 CXXRecordDecl *Pattern, 1714 const MultiLevelTemplateArgumentList &TemplateArgs) { 1715 bool Invalid = false; 1716 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 1717 for (const auto Base : Pattern->bases()) { 1718 if (!Base.getType()->isDependentType()) { 1719 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) { 1720 if (RD->isInvalidDecl()) 1721 Instantiation->setInvalidDecl(); 1722 } 1723 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base)); 1724 continue; 1725 } 1726 1727 SourceLocation EllipsisLoc; 1728 TypeSourceInfo *BaseTypeLoc; 1729 if (Base.isPackExpansion()) { 1730 // This is a pack expansion. See whether we should expand it now, or 1731 // wait until later. 1732 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1733 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(), 1734 Unexpanded); 1735 bool ShouldExpand = false; 1736 bool RetainExpansion = false; 1737 Optional<unsigned> NumExpansions; 1738 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), 1739 Base.getSourceRange(), 1740 Unexpanded, 1741 TemplateArgs, ShouldExpand, 1742 RetainExpansion, 1743 NumExpansions)) { 1744 Invalid = true; 1745 continue; 1746 } 1747 1748 // If we should expand this pack expansion now, do so. 1749 if (ShouldExpand) { 1750 for (unsigned I = 0; I != *NumExpansions; ++I) { 1751 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 1752 1753 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), 1754 TemplateArgs, 1755 Base.getSourceRange().getBegin(), 1756 DeclarationName()); 1757 if (!BaseTypeLoc) { 1758 Invalid = true; 1759 continue; 1760 } 1761 1762 if (CXXBaseSpecifier *InstantiatedBase 1763 = CheckBaseSpecifier(Instantiation, 1764 Base.getSourceRange(), 1765 Base.isVirtual(), 1766 Base.getAccessSpecifierAsWritten(), 1767 BaseTypeLoc, 1768 SourceLocation())) 1769 InstantiatedBases.push_back(InstantiatedBase); 1770 else 1771 Invalid = true; 1772 } 1773 1774 continue; 1775 } 1776 1777 // The resulting base specifier will (still) be a pack expansion. 1778 EllipsisLoc = Base.getEllipsisLoc(); 1779 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); 1780 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), 1781 TemplateArgs, 1782 Base.getSourceRange().getBegin(), 1783 DeclarationName()); 1784 } else { 1785 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), 1786 TemplateArgs, 1787 Base.getSourceRange().getBegin(), 1788 DeclarationName()); 1789 } 1790 1791 if (!BaseTypeLoc) { 1792 Invalid = true; 1793 continue; 1794 } 1795 1796 if (CXXBaseSpecifier *InstantiatedBase 1797 = CheckBaseSpecifier(Instantiation, 1798 Base.getSourceRange(), 1799 Base.isVirtual(), 1800 Base.getAccessSpecifierAsWritten(), 1801 BaseTypeLoc, 1802 EllipsisLoc)) 1803 InstantiatedBases.push_back(InstantiatedBase); 1804 else 1805 Invalid = true; 1806 } 1807 1808 if (!Invalid && 1809 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 1810 InstantiatedBases.size())) 1811 Invalid = true; 1812 1813 return Invalid; 1814 } 1815 1816 // Defined via #include from SemaTemplateInstantiateDecl.cpp 1817 namespace clang { 1818 namespace sema { 1819 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, 1820 const MultiLevelTemplateArgumentList &TemplateArgs); 1821 } 1822 } 1823 1824 /// Determine whether we would be unable to instantiate this template (because 1825 /// it either has no definition, or is in the process of being instantiated). 1826 static bool DiagnoseUninstantiableTemplate(Sema &S, 1827 SourceLocation PointOfInstantiation, 1828 TagDecl *Instantiation, 1829 bool InstantiatedFromMember, 1830 TagDecl *Pattern, 1831 TagDecl *PatternDef, 1832 TemplateSpecializationKind TSK, 1833 bool Complain = true) { 1834 if (PatternDef && !PatternDef->isBeingDefined()) 1835 return false; 1836 1837 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) { 1838 // Say nothing 1839 } else if (PatternDef) { 1840 assert(PatternDef->isBeingDefined()); 1841 S.Diag(PointOfInstantiation, 1842 diag::err_template_instantiate_within_definition) 1843 << (TSK != TSK_ImplicitInstantiation) 1844 << S.Context.getTypeDeclType(Instantiation); 1845 // Not much point in noting the template declaration here, since 1846 // we're lexically inside it. 1847 Instantiation->setInvalidDecl(); 1848 } else if (InstantiatedFromMember) { 1849 S.Diag(PointOfInstantiation, 1850 diag::err_implicit_instantiate_member_undefined) 1851 << S.Context.getTypeDeclType(Instantiation); 1852 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here); 1853 } else { 1854 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 1855 << (TSK != TSK_ImplicitInstantiation) 1856 << S.Context.getTypeDeclType(Instantiation); 1857 S.Diag(Pattern->getLocation(), diag::note_template_decl_here); 1858 } 1859 1860 // In general, Instantiation isn't marked invalid to get more than one 1861 // error for multiple undefined instantiations. But the code that does 1862 // explicit declaration -> explicit definition conversion can't handle 1863 // invalid declarations, so mark as invalid in that case. 1864 if (TSK == TSK_ExplicitInstantiationDeclaration) 1865 Instantiation->setInvalidDecl(); 1866 return true; 1867 } 1868 1869 /// \brief Instantiate the definition of a class from a given pattern. 1870 /// 1871 /// \param PointOfInstantiation The point of instantiation within the 1872 /// source code. 1873 /// 1874 /// \param Instantiation is the declaration whose definition is being 1875 /// instantiated. This will be either a class template specialization 1876 /// or a member class of a class template specialization. 1877 /// 1878 /// \param Pattern is the pattern from which the instantiation 1879 /// occurs. This will be either the declaration of a class template or 1880 /// the declaration of a member class of a class template. 1881 /// 1882 /// \param TemplateArgs The template arguments to be substituted into 1883 /// the pattern. 1884 /// 1885 /// \param TSK the kind of implicit or explicit instantiation to perform. 1886 /// 1887 /// \param Complain whether to complain if the class cannot be instantiated due 1888 /// to the lack of a definition. 1889 /// 1890 /// \returns true if an error occurred, false otherwise. 1891 bool 1892 Sema::InstantiateClass(SourceLocation PointOfInstantiation, 1893 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 1894 const MultiLevelTemplateArgumentList &TemplateArgs, 1895 TemplateSpecializationKind TSK, 1896 bool Complain) { 1897 CXXRecordDecl *PatternDef 1898 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 1899 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation, 1900 Instantiation->getInstantiatedFromMemberClass(), 1901 Pattern, PatternDef, TSK, Complain)) 1902 return true; 1903 Pattern = PatternDef; 1904 1905 // \brief Record the point of instantiation. 1906 if (MemberSpecializationInfo *MSInfo 1907 = Instantiation->getMemberSpecializationInfo()) { 1908 MSInfo->setTemplateSpecializationKind(TSK); 1909 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1910 } else if (ClassTemplateSpecializationDecl *Spec 1911 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { 1912 Spec->setTemplateSpecializationKind(TSK); 1913 Spec->setPointOfInstantiation(PointOfInstantiation); 1914 } 1915 1916 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 1917 if (Inst.isInvalid()) 1918 return true; 1919 1920 // Enter the scope of this instantiation. We don't use 1921 // PushDeclContext because we don't have a scope. 1922 ContextRAII SavedContext(*this, Instantiation); 1923 EnterExpressionEvaluationContext EvalContext(*this, 1924 Sema::PotentiallyEvaluated); 1925 1926 // If this is an instantiation of a local class, merge this local 1927 // instantiation scope with the enclosing scope. Otherwise, every 1928 // instantiation of a class has its own local instantiation scope. 1929 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 1930 LocalInstantiationScope Scope(*this, MergeWithParentScope); 1931 1932 // Pull attributes from the pattern onto the instantiation. 1933 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 1934 1935 // Start the definition of this instantiation. 1936 Instantiation->startDefinition(); 1937 1938 // The instantiation is visible here, even if it was first declared in an 1939 // unimported module. 1940 Instantiation->setHidden(false); 1941 1942 // FIXME: This loses the as-written tag kind for an explicit instantiation. 1943 Instantiation->setTagKind(Pattern->getTagKind()); 1944 1945 // Do substitution on the base class specifiers. 1946 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 1947 Instantiation->setInvalidDecl(); 1948 1949 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 1950 SmallVector<Decl*, 4> Fields; 1951 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4> 1952 FieldsWithMemberInitializers; 1953 // Delay instantiation of late parsed attributes. 1954 LateInstantiatedAttrVec LateAttrs; 1955 Instantiator.enableLateAttributeInstantiation(&LateAttrs); 1956 1957 for (auto *Member : Pattern->decls()) { 1958 // Don't instantiate members not belonging in this semantic context. 1959 // e.g. for: 1960 // @code 1961 // template <int i> class A { 1962 // class B *g; 1963 // }; 1964 // @endcode 1965 // 'class B' has the template as lexical context but semantically it is 1966 // introduced in namespace scope. 1967 if (Member->getDeclContext() != Pattern) 1968 continue; 1969 1970 if (Member->isInvalidDecl()) { 1971 Instantiation->setInvalidDecl(); 1972 continue; 1973 } 1974 1975 Decl *NewMember = Instantiator.Visit(Member); 1976 if (NewMember) { 1977 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) { 1978 Fields.push_back(Field); 1979 FieldDecl *OldField = cast<FieldDecl>(Member); 1980 if (OldField->getInClassInitializer()) 1981 FieldsWithMemberInitializers.push_back(std::make_pair(OldField, 1982 Field)); 1983 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) { 1984 // C++11 [temp.inst]p1: The implicit instantiation of a class template 1985 // specialization causes the implicit instantiation of the definitions 1986 // of unscoped member enumerations. 1987 // Record a point of instantiation for this implicit instantiation. 1988 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && 1989 Enum->isCompleteDefinition()) { 1990 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); 1991 assert(MSInfo && "no spec info for member enum specialization"); 1992 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); 1993 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1994 } 1995 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) { 1996 if (SA->isFailed()) { 1997 // A static_assert failed. Bail out; instantiating this 1998 // class is probably not meaningful. 1999 Instantiation->setInvalidDecl(); 2000 break; 2001 } 2002 } 2003 2004 if (NewMember->isInvalidDecl()) 2005 Instantiation->setInvalidDecl(); 2006 } else { 2007 // FIXME: Eventually, a NULL return will mean that one of the 2008 // instantiations was a semantic disaster, and we'll want to mark the 2009 // declaration invalid. 2010 // For now, we expect to skip some members that we can't yet handle. 2011 } 2012 } 2013 2014 // Finish checking fields. 2015 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields, 2016 SourceLocation(), SourceLocation(), 0); 2017 CheckCompletedCXXClass(Instantiation); 2018 2019 // Attach any in-class member initializers now the class is complete. 2020 // FIXME: We are supposed to defer instantiating these until they are needed. 2021 if (!FieldsWithMemberInitializers.empty()) { 2022 // C++11 [expr.prim.general]p4: 2023 // Otherwise, if a member-declarator declares a non-static data member 2024 // (9.2) of a class X, the expression this is a prvalue of type "pointer 2025 // to X" within the optional brace-or-equal-initializer. It shall not 2026 // appear elsewhere in the member-declarator. 2027 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0); 2028 2029 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) { 2030 FieldDecl *OldField = FieldsWithMemberInitializers[I].first; 2031 FieldDecl *NewField = FieldsWithMemberInitializers[I].second; 2032 Expr *OldInit = OldField->getInClassInitializer(); 2033 2034 ActOnStartCXXInClassMemberInitializer(); 2035 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs, 2036 /*CXXDirectInit=*/false); 2037 Expr *Init = NewInit.take(); 2038 assert((!Init || !isa<ParenListExpr>(Init)) && 2039 "call-style init in class"); 2040 ActOnFinishCXXInClassMemberInitializer(NewField, Init->getLocStart(), 2041 Init); 2042 } 2043 } 2044 // Instantiate late parsed attributes, and attach them to their decls. 2045 // See Sema::InstantiateAttrs 2046 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(), 2047 E = LateAttrs.end(); I != E; ++I) { 2048 assert(CurrentInstantiationScope == Instantiator.getStartingScope()); 2049 CurrentInstantiationScope = I->Scope; 2050 2051 // Allow 'this' within late-parsed attributes. 2052 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl); 2053 CXXRecordDecl *ThisContext = 2054 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 2055 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0, 2056 ND && ND->isCXXInstanceMember()); 2057 2058 Attr *NewAttr = 2059 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs); 2060 I->NewDecl->addAttr(NewAttr); 2061 LocalInstantiationScope::deleteScopes(I->Scope, 2062 Instantiator.getStartingScope()); 2063 } 2064 Instantiator.disableLateAttributeInstantiation(); 2065 LateAttrs.clear(); 2066 2067 ActOnFinishDelayedMemberInitializers(Instantiation); 2068 2069 // FIXME: We should do something similar for explicit instantiations so they 2070 // end up in the right module. 2071 if (TSK == TSK_ImplicitInstantiation) { 2072 Instantiation->setLocation(Pattern->getLocation()); 2073 Instantiation->setLocStart(Pattern->getInnerLocStart()); 2074 Instantiation->setRBraceLoc(Pattern->getRBraceLoc()); 2075 } 2076 2077 if (!Instantiation->isInvalidDecl()) { 2078 // Perform any dependent diagnostics from the pattern. 2079 PerformDependentDiagnostics(Pattern, TemplateArgs); 2080 2081 // Instantiate any out-of-line class template partial 2082 // specializations now. 2083 for (TemplateDeclInstantiator::delayed_partial_spec_iterator 2084 P = Instantiator.delayed_partial_spec_begin(), 2085 PEnd = Instantiator.delayed_partial_spec_end(); 2086 P != PEnd; ++P) { 2087 if (!Instantiator.InstantiateClassTemplatePartialSpecialization( 2088 P->first, P->second)) { 2089 Instantiation->setInvalidDecl(); 2090 break; 2091 } 2092 } 2093 2094 // Instantiate any out-of-line variable template partial 2095 // specializations now. 2096 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator 2097 P = Instantiator.delayed_var_partial_spec_begin(), 2098 PEnd = Instantiator.delayed_var_partial_spec_end(); 2099 P != PEnd; ++P) { 2100 if (!Instantiator.InstantiateVarTemplatePartialSpecialization( 2101 P->first, P->second)) { 2102 Instantiation->setInvalidDecl(); 2103 break; 2104 } 2105 } 2106 } 2107 2108 // Exit the scope of this instantiation. 2109 SavedContext.pop(); 2110 2111 if (!Instantiation->isInvalidDecl()) { 2112 Consumer.HandleTagDeclDefinition(Instantiation); 2113 2114 // Always emit the vtable for an explicit instantiation definition 2115 // of a polymorphic class template specialization. 2116 if (TSK == TSK_ExplicitInstantiationDefinition) 2117 MarkVTableUsed(PointOfInstantiation, Instantiation, true); 2118 } 2119 2120 return Instantiation->isInvalidDecl(); 2121 } 2122 2123 /// \brief Instantiate the definition of an enum from a given pattern. 2124 /// 2125 /// \param PointOfInstantiation The point of instantiation within the 2126 /// source code. 2127 /// \param Instantiation is the declaration whose definition is being 2128 /// instantiated. This will be a member enumeration of a class 2129 /// temploid specialization, or a local enumeration within a 2130 /// function temploid specialization. 2131 /// \param Pattern The templated declaration from which the instantiation 2132 /// occurs. 2133 /// \param TemplateArgs The template arguments to be substituted into 2134 /// the pattern. 2135 /// \param TSK The kind of implicit or explicit instantiation to perform. 2136 /// 2137 /// \return \c true if an error occurred, \c false otherwise. 2138 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, 2139 EnumDecl *Instantiation, EnumDecl *Pattern, 2140 const MultiLevelTemplateArgumentList &TemplateArgs, 2141 TemplateSpecializationKind TSK) { 2142 EnumDecl *PatternDef = Pattern->getDefinition(); 2143 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation, 2144 Instantiation->getInstantiatedFromMemberEnum(), 2145 Pattern, PatternDef, TSK,/*Complain*/true)) 2146 return true; 2147 Pattern = PatternDef; 2148 2149 // Record the point of instantiation. 2150 if (MemberSpecializationInfo *MSInfo 2151 = Instantiation->getMemberSpecializationInfo()) { 2152 MSInfo->setTemplateSpecializationKind(TSK); 2153 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2154 } 2155 2156 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 2157 if (Inst.isInvalid()) 2158 return true; 2159 2160 // The instantiation is visible here, even if it was first declared in an 2161 // unimported module. 2162 Instantiation->setHidden(false); 2163 2164 // Enter the scope of this instantiation. We don't use 2165 // PushDeclContext because we don't have a scope. 2166 ContextRAII SavedContext(*this, Instantiation); 2167 EnterExpressionEvaluationContext EvalContext(*this, 2168 Sema::PotentiallyEvaluated); 2169 2170 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); 2171 2172 // Pull attributes from the pattern onto the instantiation. 2173 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 2174 2175 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 2176 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern); 2177 2178 // Exit the scope of this instantiation. 2179 SavedContext.pop(); 2180 2181 return Instantiation->isInvalidDecl(); 2182 } 2183 2184 namespace { 2185 /// \brief A partial specialization whose template arguments have matched 2186 /// a given template-id. 2187 struct PartialSpecMatchResult { 2188 ClassTemplatePartialSpecializationDecl *Partial; 2189 TemplateArgumentList *Args; 2190 }; 2191 } 2192 2193 bool Sema::InstantiateClassTemplateSpecialization( 2194 SourceLocation PointOfInstantiation, 2195 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2196 TemplateSpecializationKind TSK, bool Complain) { 2197 // Perform the actual instantiation on the canonical declaration. 2198 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 2199 ClassTemplateSpec->getCanonicalDecl()); 2200 2201 // Check whether we have already instantiated or specialized this class 2202 // template specialization. 2203 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) { 2204 if (ClassTemplateSpec->getSpecializationKind() == 2205 TSK_ExplicitInstantiationDeclaration && 2206 TSK == TSK_ExplicitInstantiationDefinition) { 2207 // An explicit instantiation definition follows an explicit instantiation 2208 // declaration (C++0x [temp.explicit]p10); go ahead and perform the 2209 // explicit instantiation. 2210 ClassTemplateSpec->setSpecializationKind(TSK); 2211 2212 // If this is an explicit instantiation definition, mark the 2213 // vtable as used. 2214 if (TSK == TSK_ExplicitInstantiationDefinition && 2215 !ClassTemplateSpec->isInvalidDecl()) 2216 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true); 2217 2218 return false; 2219 } 2220 2221 // We can only instantiate something that hasn't already been 2222 // instantiated or specialized. Fail without any diagnostics: our 2223 // caller will provide an error message. 2224 return true; 2225 } 2226 2227 if (ClassTemplateSpec->isInvalidDecl()) 2228 return true; 2229 2230 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 2231 CXXRecordDecl *Pattern = 0; 2232 2233 // C++ [temp.class.spec.match]p1: 2234 // When a class template is used in a context that requires an 2235 // instantiation of the class, it is necessary to determine 2236 // whether the instantiation is to be generated using the primary 2237 // template or one of the partial specializations. This is done by 2238 // matching the template arguments of the class template 2239 // specialization with the template argument lists of the partial 2240 // specializations. 2241 typedef PartialSpecMatchResult MatchResult; 2242 SmallVector<MatchResult, 4> Matched; 2243 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2244 Template->getPartialSpecializations(PartialSpecs); 2245 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); 2246 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2247 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 2248 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 2249 if (TemplateDeductionResult Result 2250 = DeduceTemplateArguments(Partial, 2251 ClassTemplateSpec->getTemplateArgs(), 2252 Info)) { 2253 // Store the failed-deduction information for use in diagnostics, later. 2254 // TODO: Actually use the failed-deduction info? 2255 FailedCandidates.addCandidate() 2256 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info)); 2257 (void)Result; 2258 } else { 2259 Matched.push_back(PartialSpecMatchResult()); 2260 Matched.back().Partial = Partial; 2261 Matched.back().Args = Info.take(); 2262 } 2263 } 2264 2265 // If we're dealing with a member template where the template parameters 2266 // have been instantiated, this provides the original template parameters 2267 // from which the member template's parameters were instantiated. 2268 2269 if (Matched.size() >= 1) { 2270 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); 2271 if (Matched.size() == 1) { 2272 // -- If exactly one matching specialization is found, the 2273 // instantiation is generated from that specialization. 2274 // We don't need to do anything for this. 2275 } else { 2276 // -- If more than one matching specialization is found, the 2277 // partial order rules (14.5.4.2) are used to determine 2278 // whether one of the specializations is more specialized 2279 // than the others. If none of the specializations is more 2280 // specialized than all of the other matching 2281 // specializations, then the use of the class template is 2282 // ambiguous and the program is ill-formed. 2283 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, 2284 PEnd = Matched.end(); 2285 P != PEnd; ++P) { 2286 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 2287 PointOfInstantiation) 2288 == P->Partial) 2289 Best = P; 2290 } 2291 2292 // Determine if the best partial specialization is more specialized than 2293 // the others. 2294 bool Ambiguous = false; 2295 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 2296 PEnd = Matched.end(); 2297 P != PEnd; ++P) { 2298 if (P != Best && 2299 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 2300 PointOfInstantiation) 2301 != Best->Partial) { 2302 Ambiguous = true; 2303 break; 2304 } 2305 } 2306 2307 if (Ambiguous) { 2308 // Partial ordering did not produce a clear winner. Complain. 2309 ClassTemplateSpec->setInvalidDecl(); 2310 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 2311 << ClassTemplateSpec; 2312 2313 // Print the matching partial specializations. 2314 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 2315 PEnd = Matched.end(); 2316 P != PEnd; ++P) 2317 Diag(P->Partial->getLocation(), diag::note_partial_spec_match) 2318 << getTemplateArgumentBindingsText( 2319 P->Partial->getTemplateParameters(), 2320 *P->Args); 2321 2322 return true; 2323 } 2324 } 2325 2326 // Instantiate using the best class template partial specialization. 2327 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial; 2328 while (OrigPartialSpec->getInstantiatedFromMember()) { 2329 // If we've found an explicit specialization of this class template, 2330 // stop here and use that as the pattern. 2331 if (OrigPartialSpec->isMemberSpecialization()) 2332 break; 2333 2334 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember(); 2335 } 2336 2337 Pattern = OrigPartialSpec; 2338 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args); 2339 } else { 2340 // -- If no matches are found, the instantiation is generated 2341 // from the primary template. 2342 ClassTemplateDecl *OrigTemplate = Template; 2343 while (OrigTemplate->getInstantiatedFromMemberTemplate()) { 2344 // If we've found an explicit specialization of this class template, 2345 // stop here and use that as the pattern. 2346 if (OrigTemplate->isMemberSpecialization()) 2347 break; 2348 2349 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 2350 } 2351 2352 Pattern = OrigTemplate->getTemplatedDecl(); 2353 } 2354 2355 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec, 2356 Pattern, 2357 getTemplateInstantiationArgs(ClassTemplateSpec), 2358 TSK, 2359 Complain); 2360 2361 return Result; 2362 } 2363 2364 /// \brief Instantiates the definitions of all of the member 2365 /// of the given class, which is an instantiation of a class template 2366 /// or a member class of a template. 2367 void 2368 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 2369 CXXRecordDecl *Instantiation, 2370 const MultiLevelTemplateArgumentList &TemplateArgs, 2371 TemplateSpecializationKind TSK) { 2372 assert( 2373 (TSK == TSK_ExplicitInstantiationDefinition || 2374 TSK == TSK_ExplicitInstantiationDeclaration || 2375 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && 2376 "Unexpected template specialization kind!"); 2377 for (auto *D : Instantiation->decls()) { 2378 bool SuppressNew = false; 2379 if (auto *Function = dyn_cast<FunctionDecl>(D)) { 2380 if (FunctionDecl *Pattern 2381 = Function->getInstantiatedFromMemberFunction()) { 2382 MemberSpecializationInfo *MSInfo 2383 = Function->getMemberSpecializationInfo(); 2384 assert(MSInfo && "No member specialization information?"); 2385 if (MSInfo->getTemplateSpecializationKind() 2386 == TSK_ExplicitSpecialization) 2387 continue; 2388 2389 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2390 Function, 2391 MSInfo->getTemplateSpecializationKind(), 2392 MSInfo->getPointOfInstantiation(), 2393 SuppressNew) || 2394 SuppressNew) 2395 continue; 2396 2397 if (Function->isDefined()) 2398 continue; 2399 2400 if (TSK == TSK_ExplicitInstantiationDefinition) { 2401 // C++0x [temp.explicit]p8: 2402 // An explicit instantiation definition that names a class template 2403 // specialization explicitly instantiates the class template 2404 // specialization and is only an explicit instantiation definition 2405 // of members whose definition is visible at the point of 2406 // instantiation. 2407 if (!Pattern->isDefined()) 2408 continue; 2409 2410 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2411 2412 InstantiateFunctionDefinition(PointOfInstantiation, Function); 2413 } else { 2414 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2415 if (TSK == TSK_ImplicitInstantiation) 2416 PendingLocalImplicitInstantiations.push_back( 2417 std::make_pair(Function, PointOfInstantiation)); 2418 } 2419 } 2420 } else if (auto *Var = dyn_cast<VarDecl>(D)) { 2421 if (isa<VarTemplateSpecializationDecl>(Var)) 2422 continue; 2423 2424 if (Var->isStaticDataMember()) { 2425 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 2426 assert(MSInfo && "No member specialization information?"); 2427 if (MSInfo->getTemplateSpecializationKind() 2428 == TSK_ExplicitSpecialization) 2429 continue; 2430 2431 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2432 Var, 2433 MSInfo->getTemplateSpecializationKind(), 2434 MSInfo->getPointOfInstantiation(), 2435 SuppressNew) || 2436 SuppressNew) 2437 continue; 2438 2439 if (TSK == TSK_ExplicitInstantiationDefinition) { 2440 // C++0x [temp.explicit]p8: 2441 // An explicit instantiation definition that names a class template 2442 // specialization explicitly instantiates the class template 2443 // specialization and is only an explicit instantiation definition 2444 // of members whose definition is visible at the point of 2445 // instantiation. 2446 if (!Var->getInstantiatedFromStaticDataMember() 2447 ->getOutOfLineDefinition()) 2448 continue; 2449 2450 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2451 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var); 2452 } else { 2453 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2454 } 2455 } 2456 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) { 2457 // Always skip the injected-class-name, along with any 2458 // redeclarations of nested classes, since both would cause us 2459 // to try to instantiate the members of a class twice. 2460 if (Record->isInjectedClassName() || Record->getPreviousDecl()) 2461 continue; 2462 2463 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 2464 assert(MSInfo && "No member specialization information?"); 2465 2466 if (MSInfo->getTemplateSpecializationKind() 2467 == TSK_ExplicitSpecialization) 2468 continue; 2469 2470 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2471 Record, 2472 MSInfo->getTemplateSpecializationKind(), 2473 MSInfo->getPointOfInstantiation(), 2474 SuppressNew) || 2475 SuppressNew) 2476 continue; 2477 2478 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 2479 assert(Pattern && "Missing instantiated-from-template information"); 2480 2481 if (!Record->getDefinition()) { 2482 if (!Pattern->getDefinition()) { 2483 // C++0x [temp.explicit]p8: 2484 // An explicit instantiation definition that names a class template 2485 // specialization explicitly instantiates the class template 2486 // specialization and is only an explicit instantiation definition 2487 // of members whose definition is visible at the point of 2488 // instantiation. 2489 if (TSK == TSK_ExplicitInstantiationDeclaration) { 2490 MSInfo->setTemplateSpecializationKind(TSK); 2491 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2492 } 2493 2494 continue; 2495 } 2496 2497 InstantiateClass(PointOfInstantiation, Record, Pattern, 2498 TemplateArgs, 2499 TSK); 2500 } else { 2501 if (TSK == TSK_ExplicitInstantiationDefinition && 2502 Record->getTemplateSpecializationKind() == 2503 TSK_ExplicitInstantiationDeclaration) { 2504 Record->setTemplateSpecializationKind(TSK); 2505 MarkVTableUsed(PointOfInstantiation, Record, true); 2506 } 2507 } 2508 2509 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 2510 if (Pattern) 2511 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 2512 TSK); 2513 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { 2514 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); 2515 assert(MSInfo && "No member specialization information?"); 2516 2517 if (MSInfo->getTemplateSpecializationKind() 2518 == TSK_ExplicitSpecialization) 2519 continue; 2520 2521 if (CheckSpecializationInstantiationRedecl( 2522 PointOfInstantiation, TSK, Enum, 2523 MSInfo->getTemplateSpecializationKind(), 2524 MSInfo->getPointOfInstantiation(), SuppressNew) || 2525 SuppressNew) 2526 continue; 2527 2528 if (Enum->getDefinition()) 2529 continue; 2530 2531 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum(); 2532 assert(Pattern && "Missing instantiated-from-template information"); 2533 2534 if (TSK == TSK_ExplicitInstantiationDefinition) { 2535 if (!Pattern->getDefinition()) 2536 continue; 2537 2538 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK); 2539 } else { 2540 MSInfo->setTemplateSpecializationKind(TSK); 2541 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2542 } 2543 } 2544 } 2545 } 2546 2547 /// \brief Instantiate the definitions of all of the members of the 2548 /// given class template specialization, which was named as part of an 2549 /// explicit instantiation. 2550 void 2551 Sema::InstantiateClassTemplateSpecializationMembers( 2552 SourceLocation PointOfInstantiation, 2553 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2554 TemplateSpecializationKind TSK) { 2555 // C++0x [temp.explicit]p7: 2556 // An explicit instantiation that names a class template 2557 // specialization is an explicit instantion of the same kind 2558 // (declaration or definition) of each of its members (not 2559 // including members inherited from base classes) that has not 2560 // been previously explicitly specialized in the translation unit 2561 // containing the explicit instantiation, except as described 2562 // below. 2563 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 2564 getTemplateInstantiationArgs(ClassTemplateSpec), 2565 TSK); 2566 } 2567 2568 StmtResult 2569 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 2570 if (!S) 2571 return Owned(S); 2572 2573 TemplateInstantiator Instantiator(*this, TemplateArgs, 2574 SourceLocation(), 2575 DeclarationName()); 2576 return Instantiator.TransformStmt(S); 2577 } 2578 2579 ExprResult 2580 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 2581 if (!E) 2582 return Owned(E); 2583 2584 TemplateInstantiator Instantiator(*this, TemplateArgs, 2585 SourceLocation(), 2586 DeclarationName()); 2587 return Instantiator.TransformExpr(E); 2588 } 2589 2590 ExprResult Sema::SubstInitializer(Expr *Init, 2591 const MultiLevelTemplateArgumentList &TemplateArgs, 2592 bool CXXDirectInit) { 2593 TemplateInstantiator Instantiator(*this, TemplateArgs, 2594 SourceLocation(), 2595 DeclarationName()); 2596 return Instantiator.TransformInitializer(Init, CXXDirectInit); 2597 } 2598 2599 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 2600 const MultiLevelTemplateArgumentList &TemplateArgs, 2601 SmallVectorImpl<Expr *> &Outputs) { 2602 if (NumExprs == 0) 2603 return false; 2604 2605 TemplateInstantiator Instantiator(*this, TemplateArgs, 2606 SourceLocation(), 2607 DeclarationName()); 2608 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs); 2609 } 2610 2611 NestedNameSpecifierLoc 2612 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 2613 const MultiLevelTemplateArgumentList &TemplateArgs) { 2614 if (!NNS) 2615 return NestedNameSpecifierLoc(); 2616 2617 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), 2618 DeclarationName()); 2619 return Instantiator.TransformNestedNameSpecifierLoc(NNS); 2620 } 2621 2622 /// \brief Do template substitution on declaration name info. 2623 DeclarationNameInfo 2624 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 2625 const MultiLevelTemplateArgumentList &TemplateArgs) { 2626 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), 2627 NameInfo.getName()); 2628 return Instantiator.TransformDeclarationNameInfo(NameInfo); 2629 } 2630 2631 TemplateName 2632 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, 2633 TemplateName Name, SourceLocation Loc, 2634 const MultiLevelTemplateArgumentList &TemplateArgs) { 2635 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 2636 DeclarationName()); 2637 CXXScopeSpec SS; 2638 SS.Adopt(QualifierLoc); 2639 return Instantiator.TransformTemplateName(SS, Name, Loc); 2640 } 2641 2642 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 2643 TemplateArgumentListInfo &Result, 2644 const MultiLevelTemplateArgumentList &TemplateArgs) { 2645 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 2646 DeclarationName()); 2647 2648 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result); 2649 } 2650 2651 2652 static const Decl* getCanonicalParmVarDecl(const Decl *D) { 2653 // When storing ParmVarDecls in the local instantiation scope, we always 2654 // want to use the ParmVarDecl from the canonical function declaration, 2655 // since the map is then valid for any redeclaration or definition of that 2656 // function. 2657 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) { 2658 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 2659 unsigned i = PV->getFunctionScopeIndex(); 2660 return FD->getCanonicalDecl()->getParamDecl(i); 2661 } 2662 } 2663 return D; 2664 } 2665 2666 2667 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * 2668 LocalInstantiationScope::findInstantiationOf(const Decl *D) { 2669 D = getCanonicalParmVarDecl(D); 2670 for (LocalInstantiationScope *Current = this; Current; 2671 Current = Current->Outer) { 2672 2673 // Check if we found something within this scope. 2674 const Decl *CheckD = D; 2675 do { 2676 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); 2677 if (Found != Current->LocalDecls.end()) 2678 return &Found->second; 2679 2680 // If this is a tag declaration, it's possible that we need to look for 2681 // a previous declaration. 2682 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) 2683 CheckD = Tag->getPreviousDecl(); 2684 else 2685 CheckD = 0; 2686 } while (CheckD); 2687 2688 // If we aren't combined with our outer scope, we're done. 2689 if (!Current->CombineWithOuterScope) 2690 break; 2691 } 2692 2693 // If we're performing a partial substitution during template argument 2694 // deduction, we may not have values for template parameters yet. 2695 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 2696 isa<TemplateTemplateParmDecl>(D)) 2697 return 0; 2698 2699 // If we didn't find the decl, then we either have a sema bug, or we have a 2700 // forward reference to a label declaration. Return null to indicate that 2701 // we have an uninstantiated label. 2702 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope"); 2703 return 0; 2704 } 2705 2706 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { 2707 D = getCanonicalParmVarDecl(D); 2708 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 2709 if (Stored.isNull()) 2710 Stored = Inst; 2711 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) 2712 Pack->push_back(Inst); 2713 else 2714 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local"); 2715 } 2716 2717 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 2718 Decl *Inst) { 2719 D = getCanonicalParmVarDecl(D); 2720 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>(); 2721 Pack->push_back(Inst); 2722 } 2723 2724 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { 2725 D = getCanonicalParmVarDecl(D); 2726 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 2727 assert(Stored.isNull() && "Already instantiated this local"); 2728 DeclArgumentPack *Pack = new DeclArgumentPack; 2729 Stored = Pack; 2730 ArgumentPacks.push_back(Pack); 2731 } 2732 2733 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 2734 const TemplateArgument *ExplicitArgs, 2735 unsigned NumExplicitArgs) { 2736 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && 2737 "Already have a partially-substituted pack"); 2738 assert((!PartiallySubstitutedPack 2739 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && 2740 "Wrong number of arguments in partially-substituted pack"); 2741 PartiallySubstitutedPack = Pack; 2742 ArgsInPartiallySubstitutedPack = ExplicitArgs; 2743 NumArgsInPartiallySubstitutedPack = NumExplicitArgs; 2744 } 2745 2746 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( 2747 const TemplateArgument **ExplicitArgs, 2748 unsigned *NumExplicitArgs) const { 2749 if (ExplicitArgs) 2750 *ExplicitArgs = 0; 2751 if (NumExplicitArgs) 2752 *NumExplicitArgs = 0; 2753 2754 for (const LocalInstantiationScope *Current = this; Current; 2755 Current = Current->Outer) { 2756 if (Current->PartiallySubstitutedPack) { 2757 if (ExplicitArgs) 2758 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; 2759 if (NumExplicitArgs) 2760 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; 2761 2762 return Current->PartiallySubstitutedPack; 2763 } 2764 2765 if (!Current->CombineWithOuterScope) 2766 break; 2767 } 2768 2769 return 0; 2770 } 2771