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