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