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