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