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