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