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