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