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