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