1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations. 10 // 11 //===----------------------------------------------------------------------===/ 12 #include "clang/Sema/SemaInternal.h" 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/DeclTemplate.h" 16 #include "clang/AST/DeclVisitor.h" 17 #include "clang/AST/DependentDiagnostic.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/TypeLoc.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "clang/Sema/Lookup.h" 23 #include "clang/Sema/PrettyDeclStackTrace.h" 24 #include "clang/Sema/Template.h" 25 26 using namespace clang; 27 28 static bool isDeclWithinFunction(const Decl *D) { 29 const DeclContext *DC = D->getDeclContext(); 30 if (DC->isFunctionOrMethod()) 31 return true; 32 33 if (DC->isRecord()) 34 return cast<CXXRecordDecl>(DC)->isLocalClass(); 35 36 return false; 37 } 38 39 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 40 DeclaratorDecl *NewDecl) { 41 if (!OldDecl->getQualifierLoc()) 42 return false; 43 44 NestedNameSpecifierLoc NewQualifierLoc 45 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 46 TemplateArgs); 47 48 if (!NewQualifierLoc) 49 return true; 50 51 NewDecl->setQualifierInfo(NewQualifierLoc); 52 return false; 53 } 54 55 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 56 TagDecl *NewDecl) { 57 if (!OldDecl->getQualifierLoc()) 58 return false; 59 60 NestedNameSpecifierLoc NewQualifierLoc 61 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 62 TemplateArgs); 63 64 if (!NewQualifierLoc) 65 return true; 66 67 NewDecl->setQualifierInfo(NewQualifierLoc); 68 return false; 69 } 70 71 // Include attribute instantiation code. 72 #include "clang/Sema/AttrTemplateInstantiate.inc" 73 74 static void instantiateDependentAlignedAttr( 75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { 77 if (Aligned->isAlignmentExpr()) { 78 // The alignment expression is a constant expression. 79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated); 80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs); 81 if (!Result.isInvalid()) 82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(), 83 Aligned->getSpellingListIndex(), IsPackExpansion); 84 } else { 85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 86 TemplateArgs, Aligned->getLocation(), 87 DeclarationName()); 88 if (Result) 89 S.AddAlignedAttr(Aligned->getLocation(), New, Result, 90 Aligned->getSpellingListIndex(), IsPackExpansion); 91 } 92 } 93 94 static void instantiateDependentAlignedAttr( 95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 96 const AlignedAttr *Aligned, Decl *New) { 97 if (!Aligned->isPackExpansion()) { 98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 99 return; 100 } 101 102 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 103 if (Aligned->isAlignmentExpr()) 104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 105 Unexpanded); 106 else 107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 108 Unexpanded); 109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 110 111 // Determine whether we can expand this attribute pack yet. 112 bool Expand = true, RetainExpansion = false; 113 Optional<unsigned> NumExpansions; 114 // FIXME: Use the actual location of the ellipsis. 115 SourceLocation EllipsisLoc = Aligned->getLocation(); 116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 117 Unexpanded, TemplateArgs, Expand, 118 RetainExpansion, NumExpansions)) 119 return; 120 121 if (!Expand) { 122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 124 } else { 125 for (unsigned I = 0; I != *NumExpansions; ++I) { 126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 128 } 129 } 130 } 131 132 static void instantiateDependentEnableIfAttr( 133 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 134 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) { 135 Expr *Cond = 0; 136 { 137 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 138 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs); 139 if (Result.isInvalid()) 140 return; 141 Cond = Result.takeAs<Expr>(); 142 } 143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) { 144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 145 if (Converted.isInvalid()) 146 return; 147 Cond = Converted.take(); 148 } 149 150 SmallVector<PartialDiagnosticAt, 8> Diags; 151 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() && 152 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl), 153 Diags)) { 154 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr); 155 for (int I = 0, N = Diags.size(); I != N; ++I) 156 S.Diag(Diags[I].first, Diags[I].second); 157 return; 158 } 159 160 EnableIfAttr *EIA = new (S.getASTContext()) 161 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond, 162 A->getMessage(), 163 A->getSpellingListIndex()); 164 New->addAttr(EIA); 165 } 166 167 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 168 const Decl *Tmpl, Decl *New, 169 LateInstantiatedAttrVec *LateAttrs, 170 LocalInstantiationScope *OuterMostScope) { 171 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end(); 172 i != e; ++i) { 173 const Attr *TmplAttr = *i; 174 175 // FIXME: This should be generalized to more than just the AlignedAttr. 176 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 177 if (Aligned && Aligned->isAlignmentDependent()) { 178 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 179 continue; 180 } 181 182 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr); 183 if (EnableIf && EnableIf->getCond()->isValueDependent()) { 184 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, 185 New); 186 continue; 187 } 188 189 assert(!TmplAttr->isPackExpansion()); 190 if (TmplAttr->isLateParsed() && LateAttrs) { 191 // Late parsed attributes must be instantiated and attached after the 192 // enclosing class has been instantiated. See Sema::InstantiateClass. 193 LocalInstantiationScope *Saved = 0; 194 if (CurrentInstantiationScope) 195 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 196 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 197 } else { 198 // Allow 'this' within late-parsed attributes. 199 NamedDecl *ND = dyn_cast<NamedDecl>(New); 200 CXXRecordDecl *ThisContext = 201 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 202 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0, 203 ND && ND->isCXXInstanceMember()); 204 205 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 206 *this, TemplateArgs); 207 if (NewAttr) 208 New->addAttr(NewAttr); 209 } 210 } 211 } 212 213 Decl * 214 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 215 llvm_unreachable("Translation units cannot be instantiated"); 216 } 217 218 Decl * 219 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 220 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 221 D->getIdentifier()); 222 Owner->addDecl(Inst); 223 return Inst; 224 } 225 226 Decl * 227 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 228 llvm_unreachable("Namespaces cannot be instantiated"); 229 } 230 231 Decl * 232 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 233 NamespaceAliasDecl *Inst 234 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 235 D->getNamespaceLoc(), 236 D->getAliasLoc(), 237 D->getIdentifier(), 238 D->getQualifierLoc(), 239 D->getTargetNameLoc(), 240 D->getNamespace()); 241 Owner->addDecl(Inst); 242 return Inst; 243 } 244 245 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 246 bool IsTypeAlias) { 247 bool Invalid = false; 248 TypeSourceInfo *DI = D->getTypeSourceInfo(); 249 if (DI->getType()->isInstantiationDependentType() || 250 DI->getType()->isVariablyModifiedType()) { 251 DI = SemaRef.SubstType(DI, TemplateArgs, 252 D->getLocation(), D->getDeclName()); 253 if (!DI) { 254 Invalid = true; 255 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 256 } 257 } else { 258 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 259 } 260 261 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 262 // libstdc++ relies upon this bug in its implementation of common_type. 263 // If we happen to be processing that implementation, fake up the g++ ?: 264 // semantics. See LWG issue 2141 for more information on the bug. 265 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 266 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 267 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 268 DT->isReferenceType() && 269 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 270 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 271 D->getIdentifier() && D->getIdentifier()->isStr("type") && 272 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart())) 273 // Fold it to the (non-reference) type which g++ would have produced. 274 DI = SemaRef.Context.getTrivialTypeSourceInfo( 275 DI->getType().getNonReferenceType()); 276 277 // Create the new typedef 278 TypedefNameDecl *Typedef; 279 if (IsTypeAlias) 280 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 281 D->getLocation(), D->getIdentifier(), DI); 282 else 283 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 284 D->getLocation(), D->getIdentifier(), DI); 285 if (Invalid) 286 Typedef->setInvalidDecl(); 287 288 // If the old typedef was the name for linkage purposes of an anonymous 289 // tag decl, re-establish that relationship for the new typedef. 290 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 291 TagDecl *oldTag = oldTagType->getDecl(); 292 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 293 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 294 assert(!newTag->hasNameForLinkage()); 295 newTag->setTypedefNameForAnonDecl(Typedef); 296 } 297 } 298 299 if (TypedefNameDecl *Prev = D->getPreviousDecl()) { 300 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 301 TemplateArgs); 302 if (!InstPrev) 303 return 0; 304 305 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 306 307 // If the typedef types are not identical, reject them. 308 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 309 310 Typedef->setPreviousDecl(InstPrevTypedef); 311 } 312 313 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 314 315 Typedef->setAccess(D->getAccess()); 316 317 return Typedef; 318 } 319 320 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 321 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 322 Owner->addDecl(Typedef); 323 return Typedef; 324 } 325 326 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 327 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 328 Owner->addDecl(Typedef); 329 return Typedef; 330 } 331 332 Decl * 333 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 334 // Create a local instantiation scope for this type alias template, which 335 // will contain the instantiations of the template parameters. 336 LocalInstantiationScope Scope(SemaRef); 337 338 TemplateParameterList *TempParams = D->getTemplateParameters(); 339 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 340 if (!InstParams) 341 return 0; 342 343 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 344 345 TypeAliasTemplateDecl *PrevAliasTemplate = 0; 346 if (Pattern->getPreviousDecl()) { 347 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 348 if (!Found.empty()) { 349 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front()); 350 } 351 } 352 353 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 354 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 355 if (!AliasInst) 356 return 0; 357 358 TypeAliasTemplateDecl *Inst 359 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 360 D->getDeclName(), InstParams, AliasInst); 361 if (PrevAliasTemplate) 362 Inst->setPreviousDecl(PrevAliasTemplate); 363 364 Inst->setAccess(D->getAccess()); 365 366 if (!PrevAliasTemplate) 367 Inst->setInstantiatedFromMemberTemplate(D); 368 369 Owner->addDecl(Inst); 370 371 return Inst; 372 } 373 374 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 375 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); 376 } 377 378 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, 379 bool InstantiatingVarTemplate) { 380 381 // If this is the variable for an anonymous struct or union, 382 // instantiate the anonymous struct/union type first. 383 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 384 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 385 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 386 return 0; 387 388 // Do substitution on the type of the declaration 389 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 390 TemplateArgs, 391 D->getTypeSpecStartLoc(), 392 D->getDeclName()); 393 if (!DI) 394 return 0; 395 396 if (DI->getType()->isFunctionType()) { 397 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 398 << D->isStaticDataMember() << DI->getType(); 399 return 0; 400 } 401 402 DeclContext *DC = Owner; 403 if (D->isLocalExternDecl()) 404 SemaRef.adjustContextForLocalExternDecl(DC); 405 406 // Build the instantiated declaration. 407 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 408 D->getLocation(), D->getIdentifier(), 409 DI->getType(), DI, D->getStorageClass()); 410 411 // In ARC, infer 'retaining' for variables of retainable type. 412 if (SemaRef.getLangOpts().ObjCAutoRefCount && 413 SemaRef.inferObjCARCLifetime(Var)) 414 Var->setInvalidDecl(); 415 416 // Substitute the nested name specifier, if any. 417 if (SubstQualifier(D, Var)) 418 return 0; 419 420 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 421 StartingScope, InstantiatingVarTemplate); 422 return Var; 423 } 424 425 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 426 AccessSpecDecl* AD 427 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 428 D->getAccessSpecifierLoc(), D->getColonLoc()); 429 Owner->addHiddenDecl(AD); 430 return AD; 431 } 432 433 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 434 bool Invalid = false; 435 TypeSourceInfo *DI = D->getTypeSourceInfo(); 436 if (DI->getType()->isInstantiationDependentType() || 437 DI->getType()->isVariablyModifiedType()) { 438 DI = SemaRef.SubstType(DI, TemplateArgs, 439 D->getLocation(), D->getDeclName()); 440 if (!DI) { 441 DI = D->getTypeSourceInfo(); 442 Invalid = true; 443 } else if (DI->getType()->isFunctionType()) { 444 // C++ [temp.arg.type]p3: 445 // If a declaration acquires a function type through a type 446 // dependent on a template-parameter and this causes a 447 // declaration that does not use the syntactic form of a 448 // function declarator to have function type, the program is 449 // ill-formed. 450 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 451 << DI->getType(); 452 Invalid = true; 453 } 454 } else { 455 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 456 } 457 458 Expr *BitWidth = D->getBitWidth(); 459 if (Invalid) 460 BitWidth = 0; 461 else if (BitWidth) { 462 // The bit-width expression is a constant expression. 463 EnterExpressionEvaluationContext Unevaluated(SemaRef, 464 Sema::ConstantEvaluated); 465 466 ExprResult InstantiatedBitWidth 467 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 468 if (InstantiatedBitWidth.isInvalid()) { 469 Invalid = true; 470 BitWidth = 0; 471 } else 472 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 473 } 474 475 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 476 DI->getType(), DI, 477 cast<RecordDecl>(Owner), 478 D->getLocation(), 479 D->isMutable(), 480 BitWidth, 481 D->getInClassInitStyle(), 482 D->getInnerLocStart(), 483 D->getAccess(), 484 0); 485 if (!Field) { 486 cast<Decl>(Owner)->setInvalidDecl(); 487 return 0; 488 } 489 490 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 491 492 if (Field->hasAttrs()) 493 SemaRef.CheckAlignasUnderalignment(Field); 494 495 if (Invalid) 496 Field->setInvalidDecl(); 497 498 if (!Field->getDeclName()) { 499 // Keep track of where this decl came from. 500 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 501 } 502 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 503 if (Parent->isAnonymousStructOrUnion() && 504 Parent->getRedeclContext()->isFunctionOrMethod()) 505 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 506 } 507 508 Field->setImplicit(D->isImplicit()); 509 Field->setAccess(D->getAccess()); 510 Owner->addDecl(Field); 511 512 return Field; 513 } 514 515 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { 516 bool Invalid = false; 517 TypeSourceInfo *DI = D->getTypeSourceInfo(); 518 519 if (DI->getType()->isVariablyModifiedType()) { 520 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) 521 << D; 522 Invalid = true; 523 } else if (DI->getType()->isInstantiationDependentType()) { 524 DI = SemaRef.SubstType(DI, TemplateArgs, 525 D->getLocation(), D->getDeclName()); 526 if (!DI) { 527 DI = D->getTypeSourceInfo(); 528 Invalid = true; 529 } else if (DI->getType()->isFunctionType()) { 530 // C++ [temp.arg.type]p3: 531 // If a declaration acquires a function type through a type 532 // dependent on a template-parameter and this causes a 533 // declaration that does not use the syntactic form of a 534 // function declarator to have function type, the program is 535 // ill-formed. 536 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 537 << DI->getType(); 538 Invalid = true; 539 } 540 } else { 541 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 542 } 543 544 MSPropertyDecl *Property = MSPropertyDecl::Create( 545 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(), 546 DI, D->getLocStart(), D->getGetterId(), D->getSetterId()); 547 548 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, 549 StartingScope); 550 551 if (Invalid) 552 Property->setInvalidDecl(); 553 554 Property->setAccess(D->getAccess()); 555 Owner->addDecl(Property); 556 557 return Property; 558 } 559 560 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 561 NamedDecl **NamedChain = 562 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 563 564 int i = 0; 565 for (auto *PI : D->chain()) { 566 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI, 567 TemplateArgs); 568 if (!Next) 569 return 0; 570 571 NamedChain[i++] = Next; 572 } 573 574 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 575 IndirectFieldDecl* IndirectField 576 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(), 577 D->getIdentifier(), T, 578 NamedChain, D->getChainingSize()); 579 580 581 IndirectField->setImplicit(D->isImplicit()); 582 IndirectField->setAccess(D->getAccess()); 583 Owner->addDecl(IndirectField); 584 return IndirectField; 585 } 586 587 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 588 // Handle friend type expressions by simply substituting template 589 // parameters into the pattern type and checking the result. 590 if (TypeSourceInfo *Ty = D->getFriendType()) { 591 TypeSourceInfo *InstTy; 592 // If this is an unsupported friend, don't bother substituting template 593 // arguments into it. The actual type referred to won't be used by any 594 // parts of Clang, and may not be valid for instantiating. Just use the 595 // same info for the instantiated friend. 596 if (D->isUnsupportedFriend()) { 597 InstTy = Ty; 598 } else { 599 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 600 D->getLocation(), DeclarationName()); 601 } 602 if (!InstTy) 603 return 0; 604 605 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(), 606 D->getFriendLoc(), InstTy); 607 if (!FD) 608 return 0; 609 610 FD->setAccess(AS_public); 611 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 612 Owner->addDecl(FD); 613 return FD; 614 } 615 616 NamedDecl *ND = D->getFriendDecl(); 617 assert(ND && "friend decl must be a decl or a type!"); 618 619 // All of the Visit implementations for the various potential friend 620 // declarations have to be carefully written to work for friend 621 // objects, with the most important detail being that the target 622 // decl should almost certainly not be placed in Owner. 623 Decl *NewND = Visit(ND); 624 if (!NewND) return 0; 625 626 FriendDecl *FD = 627 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 628 cast<NamedDecl>(NewND), D->getFriendLoc()); 629 FD->setAccess(AS_public); 630 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 631 Owner->addDecl(FD); 632 return FD; 633 } 634 635 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 636 Expr *AssertExpr = D->getAssertExpr(); 637 638 // The expression in a static assertion is a constant expression. 639 EnterExpressionEvaluationContext Unevaluated(SemaRef, 640 Sema::ConstantEvaluated); 641 642 ExprResult InstantiatedAssertExpr 643 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 644 if (InstantiatedAssertExpr.isInvalid()) 645 return 0; 646 647 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 648 InstantiatedAssertExpr.get(), 649 D->getMessage(), 650 D->getRParenLoc(), 651 D->isFailed()); 652 } 653 654 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 655 EnumDecl *PrevDecl = 0; 656 if (D->getPreviousDecl()) { 657 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 658 D->getPreviousDecl(), 659 TemplateArgs); 660 if (!Prev) return 0; 661 PrevDecl = cast<EnumDecl>(Prev); 662 } 663 664 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 665 D->getLocation(), D->getIdentifier(), 666 PrevDecl, D->isScoped(), 667 D->isScopedUsingClassTag(), D->isFixed()); 668 if (D->isFixed()) { 669 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 670 // If we have type source information for the underlying type, it means it 671 // has been explicitly set by the user. Perform substitution on it before 672 // moving on. 673 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 674 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 675 DeclarationName()); 676 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 677 Enum->setIntegerType(SemaRef.Context.IntTy); 678 else 679 Enum->setIntegerTypeSourceInfo(NewTI); 680 } else { 681 assert(!D->getIntegerType()->isDependentType() 682 && "Dependent type without type source info"); 683 Enum->setIntegerType(D->getIntegerType()); 684 } 685 } 686 687 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 688 689 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 690 Enum->setAccess(D->getAccess()); 691 // Forward the mangling number from the template to the instantiated decl. 692 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); 693 if (SubstQualifier(D, Enum)) return 0; 694 Owner->addDecl(Enum); 695 696 EnumDecl *Def = D->getDefinition(); 697 if (Def && Def != D) { 698 // If this is an out-of-line definition of an enum member template, check 699 // that the underlying types match in the instantiation of both 700 // declarations. 701 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 702 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 703 QualType DefnUnderlying = 704 SemaRef.SubstType(TI->getType(), TemplateArgs, 705 UnderlyingLoc, DeclarationName()); 706 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 707 DefnUnderlying, Enum); 708 } 709 } 710 711 // C++11 [temp.inst]p1: The implicit instantiation of a class template 712 // specialization causes the implicit instantiation of the declarations, but 713 // not the definitions of scoped member enumerations. 714 // 715 // DR1484 clarifies that enumeration definitions inside of a template 716 // declaration aren't considered entities that can be separately instantiated 717 // from the rest of the entity they are declared inside of. 718 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { 719 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 720 InstantiateEnumDefinition(Enum, Def); 721 } 722 723 return Enum; 724 } 725 726 void TemplateDeclInstantiator::InstantiateEnumDefinition( 727 EnumDecl *Enum, EnumDecl *Pattern) { 728 Enum->startDefinition(); 729 730 // Update the location to refer to the definition. 731 Enum->setLocation(Pattern->getLocation()); 732 733 SmallVector<Decl*, 4> Enumerators; 734 735 EnumConstantDecl *LastEnumConst = 0; 736 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(), 737 ECEnd = Pattern->enumerator_end(); 738 EC != ECEnd; ++EC) { 739 // The specified value for the enumerator. 740 ExprResult Value = SemaRef.Owned((Expr *)0); 741 if (Expr *UninstValue = EC->getInitExpr()) { 742 // The enumerator's value expression is a constant expression. 743 EnterExpressionEvaluationContext Unevaluated(SemaRef, 744 Sema::ConstantEvaluated); 745 746 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 747 } 748 749 // Drop the initial value and continue. 750 bool isInvalid = false; 751 if (Value.isInvalid()) { 752 Value = SemaRef.Owned((Expr *)0); 753 isInvalid = true; 754 } 755 756 EnumConstantDecl *EnumConst 757 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 758 EC->getLocation(), EC->getIdentifier(), 759 Value.get()); 760 761 if (isInvalid) { 762 if (EnumConst) 763 EnumConst->setInvalidDecl(); 764 Enum->setInvalidDecl(); 765 } 766 767 if (EnumConst) { 768 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst); 769 770 EnumConst->setAccess(Enum->getAccess()); 771 Enum->addDecl(EnumConst); 772 Enumerators.push_back(EnumConst); 773 LastEnumConst = EnumConst; 774 775 if (Pattern->getDeclContext()->isFunctionOrMethod() && 776 !Enum->isScoped()) { 777 // If the enumeration is within a function or method, record the enum 778 // constant as a local. 779 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 780 } 781 } 782 } 783 784 // FIXME: Fixup LBraceLoc 785 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), 786 Enum->getRBraceLoc(), Enum, 787 Enumerators, 788 0, 0); 789 } 790 791 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 792 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 793 } 794 795 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 796 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 797 798 // Create a local instantiation scope for this class template, which 799 // will contain the instantiations of the template parameters. 800 LocalInstantiationScope Scope(SemaRef); 801 TemplateParameterList *TempParams = D->getTemplateParameters(); 802 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 803 if (!InstParams) 804 return NULL; 805 806 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 807 808 // Instantiate the qualifier. We have to do this first in case 809 // we're a friend declaration, because if we are then we need to put 810 // the new declaration in the appropriate context. 811 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 812 if (QualifierLoc) { 813 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 814 TemplateArgs); 815 if (!QualifierLoc) 816 return 0; 817 } 818 819 CXXRecordDecl *PrevDecl = 0; 820 ClassTemplateDecl *PrevClassTemplate = 0; 821 822 if (!isFriend && Pattern->getPreviousDecl()) { 823 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 824 if (!Found.empty()) { 825 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front()); 826 if (PrevClassTemplate) 827 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 828 } 829 } 830 831 // If this isn't a friend, then it's a member template, in which 832 // case we just want to build the instantiation in the 833 // specialization. If it is a friend, we want to build it in 834 // the appropriate context. 835 DeclContext *DC = Owner; 836 if (isFriend) { 837 if (QualifierLoc) { 838 CXXScopeSpec SS; 839 SS.Adopt(QualifierLoc); 840 DC = SemaRef.computeDeclContext(SS); 841 if (!DC) return 0; 842 } else { 843 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 844 Pattern->getDeclContext(), 845 TemplateArgs); 846 } 847 848 // Look for a previous declaration of the template in the owning 849 // context. 850 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 851 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 852 SemaRef.LookupQualifiedName(R, DC); 853 854 if (R.isSingleResult()) { 855 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 856 if (PrevClassTemplate) 857 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 858 } 859 860 if (!PrevClassTemplate && QualifierLoc) { 861 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 862 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 863 << QualifierLoc.getSourceRange(); 864 return 0; 865 } 866 867 bool AdoptedPreviousTemplateParams = false; 868 if (PrevClassTemplate) { 869 bool Complain = true; 870 871 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 872 // template for struct std::tr1::__detail::_Map_base, where the 873 // template parameters of the friend declaration don't match the 874 // template parameters of the original declaration. In this one 875 // case, we don't complain about the ill-formed friend 876 // declaration. 877 if (isFriend && Pattern->getIdentifier() && 878 Pattern->getIdentifier()->isStr("_Map_base") && 879 DC->isNamespace() && 880 cast<NamespaceDecl>(DC)->getIdentifier() && 881 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 882 DeclContext *DCParent = DC->getParent(); 883 if (DCParent->isNamespace() && 884 cast<NamespaceDecl>(DCParent)->getIdentifier() && 885 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 886 DeclContext *DCParent2 = DCParent->getParent(); 887 if (DCParent2->isNamespace() && 888 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 889 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 890 DCParent2->getParent()->isTranslationUnit()) 891 Complain = false; 892 } 893 } 894 895 TemplateParameterList *PrevParams 896 = PrevClassTemplate->getTemplateParameters(); 897 898 // Make sure the parameter lists match. 899 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 900 Complain, 901 Sema::TPL_TemplateMatch)) { 902 if (Complain) 903 return 0; 904 905 AdoptedPreviousTemplateParams = true; 906 InstParams = PrevParams; 907 } 908 909 // Do some additional validation, then merge default arguments 910 // from the existing declarations. 911 if (!AdoptedPreviousTemplateParams && 912 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 913 Sema::TPC_ClassTemplate)) 914 return 0; 915 } 916 } 917 918 CXXRecordDecl *RecordInst 919 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 920 Pattern->getLocStart(), Pattern->getLocation(), 921 Pattern->getIdentifier(), PrevDecl, 922 /*DelayTypeCreation=*/true); 923 924 if (QualifierLoc) 925 RecordInst->setQualifierInfo(QualifierLoc); 926 927 ClassTemplateDecl *Inst 928 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 929 D->getIdentifier(), InstParams, RecordInst, 930 PrevClassTemplate); 931 RecordInst->setDescribedClassTemplate(Inst); 932 933 if (isFriend) { 934 if (PrevClassTemplate) 935 Inst->setAccess(PrevClassTemplate->getAccess()); 936 else 937 Inst->setAccess(D->getAccess()); 938 939 Inst->setObjectOfFriendDecl(); 940 // TODO: do we want to track the instantiation progeny of this 941 // friend target decl? 942 } else { 943 Inst->setAccess(D->getAccess()); 944 if (!PrevClassTemplate) 945 Inst->setInstantiatedFromMemberTemplate(D); 946 } 947 948 // Trigger creation of the type for the instantiation. 949 SemaRef.Context.getInjectedClassNameType(RecordInst, 950 Inst->getInjectedClassNameSpecialization()); 951 952 // Finish handling of friends. 953 if (isFriend) { 954 DC->makeDeclVisibleInContext(Inst); 955 Inst->setLexicalDeclContext(Owner); 956 RecordInst->setLexicalDeclContext(Owner); 957 return Inst; 958 } 959 960 if (D->isOutOfLine()) { 961 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 962 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 963 } 964 965 Owner->addDecl(Inst); 966 967 if (!PrevClassTemplate) { 968 // Queue up any out-of-line partial specializations of this member 969 // class template; the client will force their instantiation once 970 // the enclosing class has been instantiated. 971 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 972 D->getPartialSpecializations(PartialSpecs); 973 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 974 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 975 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 976 } 977 978 return Inst; 979 } 980 981 Decl * 982 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 983 ClassTemplatePartialSpecializationDecl *D) { 984 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 985 986 // Lookup the already-instantiated declaration in the instantiation 987 // of the class template and return that. 988 DeclContext::lookup_result Found 989 = Owner->lookup(ClassTemplate->getDeclName()); 990 if (Found.empty()) 991 return 0; 992 993 ClassTemplateDecl *InstClassTemplate 994 = dyn_cast<ClassTemplateDecl>(Found.front()); 995 if (!InstClassTemplate) 996 return 0; 997 998 if (ClassTemplatePartialSpecializationDecl *Result 999 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 1000 return Result; 1001 1002 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 1003 } 1004 1005 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { 1006 assert(D->getTemplatedDecl()->isStaticDataMember() && 1007 "Only static data member templates are allowed."); 1008 1009 // Create a local instantiation scope for this variable template, which 1010 // will contain the instantiations of the template parameters. 1011 LocalInstantiationScope Scope(SemaRef); 1012 TemplateParameterList *TempParams = D->getTemplateParameters(); 1013 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1014 if (!InstParams) 1015 return NULL; 1016 1017 VarDecl *Pattern = D->getTemplatedDecl(); 1018 VarTemplateDecl *PrevVarTemplate = 0; 1019 1020 if (Pattern->getPreviousDecl()) { 1021 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 1022 if (!Found.empty()) 1023 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1024 } 1025 1026 VarDecl *VarInst = 1027 cast_or_null<VarDecl>(VisitVarDecl(Pattern, 1028 /*InstantiatingVarTemplate=*/true)); 1029 1030 DeclContext *DC = Owner; 1031 1032 VarTemplateDecl *Inst = VarTemplateDecl::Create( 1033 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams, 1034 VarInst); 1035 VarInst->setDescribedVarTemplate(Inst); 1036 Inst->setPreviousDecl(PrevVarTemplate); 1037 1038 Inst->setAccess(D->getAccess()); 1039 if (!PrevVarTemplate) 1040 Inst->setInstantiatedFromMemberTemplate(D); 1041 1042 if (D->isOutOfLine()) { 1043 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1044 VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1045 } 1046 1047 Owner->addDecl(Inst); 1048 1049 if (!PrevVarTemplate) { 1050 // Queue up any out-of-line partial specializations of this member 1051 // variable template; the client will force their instantiation once 1052 // the enclosing class has been instantiated. 1053 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1054 D->getPartialSpecializations(PartialSpecs); 1055 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1056 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1057 OutOfLineVarPartialSpecs.push_back( 1058 std::make_pair(Inst, PartialSpecs[I])); 1059 } 1060 1061 return Inst; 1062 } 1063 1064 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( 1065 VarTemplatePartialSpecializationDecl *D) { 1066 assert(D->isStaticDataMember() && 1067 "Only static data member templates are allowed."); 1068 1069 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 1070 1071 // Lookup the already-instantiated declaration and return that. 1072 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName()); 1073 assert(!Found.empty() && "Instantiation found nothing?"); 1074 1075 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1076 assert(InstVarTemplate && "Instantiation did not find a variable template?"); 1077 1078 if (VarTemplatePartialSpecializationDecl *Result = 1079 InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) 1080 return Result; 1081 1082 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D); 1083 } 1084 1085 Decl * 1086 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 1087 // Create a local instantiation scope for this function template, which 1088 // will contain the instantiations of the template parameters and then get 1089 // merged with the local instantiation scope for the function template 1090 // itself. 1091 LocalInstantiationScope Scope(SemaRef); 1092 1093 TemplateParameterList *TempParams = D->getTemplateParameters(); 1094 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1095 if (!InstParams) 1096 return NULL; 1097 1098 FunctionDecl *Instantiated = 0; 1099 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 1100 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 1101 InstParams)); 1102 else 1103 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 1104 D->getTemplatedDecl(), 1105 InstParams)); 1106 1107 if (!Instantiated) 1108 return 0; 1109 1110 // Link the instantiated function template declaration to the function 1111 // template from which it was instantiated. 1112 FunctionTemplateDecl *InstTemplate 1113 = Instantiated->getDescribedFunctionTemplate(); 1114 InstTemplate->setAccess(D->getAccess()); 1115 assert(InstTemplate && 1116 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 1117 1118 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 1119 1120 // Link the instantiation back to the pattern *unless* this is a 1121 // non-definition friend declaration. 1122 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 1123 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 1124 InstTemplate->setInstantiatedFromMemberTemplate(D); 1125 1126 // Make declarations visible in the appropriate context. 1127 if (!isFriend) { 1128 Owner->addDecl(InstTemplate); 1129 } else if (InstTemplate->getDeclContext()->isRecord() && 1130 !D->getPreviousDecl()) { 1131 SemaRef.CheckFriendAccess(InstTemplate); 1132 } 1133 1134 return InstTemplate; 1135 } 1136 1137 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 1138 CXXRecordDecl *PrevDecl = 0; 1139 if (D->isInjectedClassName()) 1140 PrevDecl = cast<CXXRecordDecl>(Owner); 1141 else if (D->getPreviousDecl()) { 1142 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1143 D->getPreviousDecl(), 1144 TemplateArgs); 1145 if (!Prev) return 0; 1146 PrevDecl = cast<CXXRecordDecl>(Prev); 1147 } 1148 1149 CXXRecordDecl *Record 1150 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 1151 D->getLocStart(), D->getLocation(), 1152 D->getIdentifier(), PrevDecl); 1153 1154 // Substitute the nested name specifier, if any. 1155 if (SubstQualifier(D, Record)) 1156 return 0; 1157 1158 Record->setImplicit(D->isImplicit()); 1159 // FIXME: Check against AS_none is an ugly hack to work around the issue that 1160 // the tag decls introduced by friend class declarations don't have an access 1161 // specifier. Remove once this area of the code gets sorted out. 1162 if (D->getAccess() != AS_none) 1163 Record->setAccess(D->getAccess()); 1164 if (!D->isInjectedClassName()) 1165 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 1166 1167 // If the original function was part of a friend declaration, 1168 // inherit its namespace state. 1169 if (D->getFriendObjectKind()) 1170 Record->setObjectOfFriendDecl(); 1171 1172 // Make sure that anonymous structs and unions are recorded. 1173 if (D->isAnonymousStructOrUnion()) 1174 Record->setAnonymousStructOrUnion(true); 1175 1176 if (D->isLocalClass()) 1177 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1178 1179 // Forward the mangling number from the template to the instantiated decl. 1180 SemaRef.Context.setManglingNumber(Record, 1181 SemaRef.Context.getManglingNumber(D)); 1182 1183 Owner->addDecl(Record); 1184 1185 // DR1484 clarifies that the members of a local class are instantiated as part 1186 // of the instantiation of their enclosing entity. 1187 if (D->isCompleteDefinition() && D->isLocalClass()) { 1188 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs, 1189 TSK_ImplicitInstantiation, 1190 /*Complain=*/true); 1191 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs, 1192 TSK_ImplicitInstantiation); 1193 } 1194 return Record; 1195 } 1196 1197 /// \brief Adjust the given function type for an instantiation of the 1198 /// given declaration, to cope with modifications to the function's type that 1199 /// aren't reflected in the type-source information. 1200 /// 1201 /// \param D The declaration we're instantiating. 1202 /// \param TInfo The already-instantiated type. 1203 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, 1204 FunctionDecl *D, 1205 TypeSourceInfo *TInfo) { 1206 const FunctionProtoType *OrigFunc 1207 = D->getType()->castAs<FunctionProtoType>(); 1208 const FunctionProtoType *NewFunc 1209 = TInfo->getType()->castAs<FunctionProtoType>(); 1210 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) 1211 return TInfo->getType(); 1212 1213 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); 1214 NewEPI.ExtInfo = OrigFunc->getExtInfo(); 1215 return Context.getFunctionType(NewFunc->getReturnType(), 1216 NewFunc->getParamTypes(), NewEPI); 1217 } 1218 1219 /// Normal class members are of more specific types and therefore 1220 /// don't make it here. This function serves two purposes: 1221 /// 1) instantiating function templates 1222 /// 2) substituting friend declarations 1223 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1224 TemplateParameterList *TemplateParams) { 1225 // Check whether there is already a function template specialization for 1226 // this declaration. 1227 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1228 if (FunctionTemplate && !TemplateParams) { 1229 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1230 1231 void *InsertPos = 0; 1232 FunctionDecl *SpecFunc 1233 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(), 1234 InsertPos); 1235 1236 // If we already have a function template specialization, return it. 1237 if (SpecFunc) 1238 return SpecFunc; 1239 } 1240 1241 bool isFriend; 1242 if (FunctionTemplate) 1243 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1244 else 1245 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1246 1247 bool MergeWithParentScope = (TemplateParams != 0) || 1248 Owner->isFunctionOrMethod() || 1249 !(isa<Decl>(Owner) && 1250 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1251 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1252 1253 SmallVector<ParmVarDecl *, 4> Params; 1254 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1255 if (!TInfo) 1256 return 0; 1257 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1258 1259 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1260 if (QualifierLoc) { 1261 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1262 TemplateArgs); 1263 if (!QualifierLoc) 1264 return 0; 1265 } 1266 1267 // If we're instantiating a local function declaration, put the result 1268 // in the enclosing namespace; otherwise we need to find the instantiated 1269 // context. 1270 DeclContext *DC; 1271 if (D->isLocalExternDecl()) { 1272 DC = Owner; 1273 SemaRef.adjustContextForLocalExternDecl(DC); 1274 } else if (isFriend && QualifierLoc) { 1275 CXXScopeSpec SS; 1276 SS.Adopt(QualifierLoc); 1277 DC = SemaRef.computeDeclContext(SS); 1278 if (!DC) return 0; 1279 } else { 1280 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1281 TemplateArgs); 1282 } 1283 1284 FunctionDecl *Function = 1285 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 1286 D->getNameInfo(), T, TInfo, 1287 D->getCanonicalDecl()->getStorageClass(), 1288 D->isInlineSpecified(), D->hasWrittenPrototype(), 1289 D->isConstexpr()); 1290 Function->setRangeEnd(D->getSourceRange().getEnd()); 1291 1292 if (D->isInlined()) 1293 Function->setImplicitlyInline(); 1294 1295 if (QualifierLoc) 1296 Function->setQualifierInfo(QualifierLoc); 1297 1298 if (D->isLocalExternDecl()) 1299 Function->setLocalExternDecl(); 1300 1301 DeclContext *LexicalDC = Owner; 1302 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 1303 assert(D->getDeclContext()->isFileContext()); 1304 LexicalDC = D->getDeclContext(); 1305 } 1306 1307 Function->setLexicalDeclContext(LexicalDC); 1308 1309 // Attach the parameters 1310 for (unsigned P = 0; P < Params.size(); ++P) 1311 if (Params[P]) 1312 Params[P]->setOwningFunction(Function); 1313 Function->setParams(Params); 1314 1315 SourceLocation InstantiateAtPOI; 1316 if (TemplateParams) { 1317 // Our resulting instantiation is actually a function template, since we 1318 // are substituting only the outer template parameters. For example, given 1319 // 1320 // template<typename T> 1321 // struct X { 1322 // template<typename U> friend void f(T, U); 1323 // }; 1324 // 1325 // X<int> x; 1326 // 1327 // We are instantiating the friend function template "f" within X<int>, 1328 // which means substituting int for T, but leaving "f" as a friend function 1329 // template. 1330 // Build the function template itself. 1331 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1332 Function->getLocation(), 1333 Function->getDeclName(), 1334 TemplateParams, Function); 1335 Function->setDescribedFunctionTemplate(FunctionTemplate); 1336 1337 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1338 1339 if (isFriend && D->isThisDeclarationADefinition()) { 1340 // TODO: should we remember this connection regardless of whether 1341 // the friend declaration provided a body? 1342 FunctionTemplate->setInstantiatedFromMemberTemplate( 1343 D->getDescribedFunctionTemplate()); 1344 } 1345 } else if (FunctionTemplate) { 1346 // Record this function template specialization. 1347 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1348 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1349 TemplateArgumentList::CreateCopy(SemaRef.Context, 1350 Innermost.begin(), 1351 Innermost.size()), 1352 /*InsertPos=*/0); 1353 } else if (isFriend) { 1354 // Note, we need this connection even if the friend doesn't have a body. 1355 // Its body may exist but not have been attached yet due to deferred 1356 // parsing. 1357 // FIXME: It might be cleaner to set this when attaching the body to the 1358 // friend function declaration, however that would require finding all the 1359 // instantiations and modifying them. 1360 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1361 } 1362 1363 if (InitFunctionInstantiation(Function, D)) 1364 Function->setInvalidDecl(); 1365 1366 bool isExplicitSpecialization = false; 1367 1368 LookupResult Previous( 1369 SemaRef, Function->getDeclName(), SourceLocation(), 1370 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 1371 : Sema::LookupOrdinaryName, 1372 Sema::ForRedeclaration); 1373 1374 if (DependentFunctionTemplateSpecializationInfo *Info 1375 = D->getDependentSpecializationInfo()) { 1376 assert(isFriend && "non-friend has dependent specialization info?"); 1377 1378 // This needs to be set now for future sanity. 1379 Function->setObjectOfFriendDecl(); 1380 1381 // Instantiate the explicit template arguments. 1382 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1383 Info->getRAngleLoc()); 1384 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1385 ExplicitArgs, TemplateArgs)) 1386 return 0; 1387 1388 // Map the candidate templates to their instantiations. 1389 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1390 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1391 Info->getTemplate(I), 1392 TemplateArgs); 1393 if (!Temp) return 0; 1394 1395 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1396 } 1397 1398 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1399 &ExplicitArgs, 1400 Previous)) 1401 Function->setInvalidDecl(); 1402 1403 isExplicitSpecialization = true; 1404 1405 } else if (TemplateParams || !FunctionTemplate) { 1406 // Look only into the namespace where the friend would be declared to 1407 // find a previous declaration. This is the innermost enclosing namespace, 1408 // as described in ActOnFriendFunctionDecl. 1409 SemaRef.LookupQualifiedName(Previous, DC); 1410 1411 // In C++, the previous declaration we find might be a tag type 1412 // (class or enum). In this case, the new declaration will hide the 1413 // tag type. Note that this does does not apply if we're declaring a 1414 // typedef (C++ [dcl.typedef]p4). 1415 if (Previous.isSingleTagDecl()) 1416 Previous.clear(); 1417 } 1418 1419 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1420 isExplicitSpecialization); 1421 1422 NamedDecl *PrincipalDecl = (TemplateParams 1423 ? cast<NamedDecl>(FunctionTemplate) 1424 : Function); 1425 1426 // If the original function was part of a friend declaration, 1427 // inherit its namespace state and add it to the owner. 1428 if (isFriend) { 1429 PrincipalDecl->setObjectOfFriendDecl(); 1430 DC->makeDeclVisibleInContext(PrincipalDecl); 1431 1432 bool QueuedInstantiation = false; 1433 1434 // C++11 [temp.friend]p4 (DR329): 1435 // When a function is defined in a friend function declaration in a class 1436 // template, the function is instantiated when the function is odr-used. 1437 // The same restrictions on multiple declarations and definitions that 1438 // apply to non-template function declarations and definitions also apply 1439 // to these implicit definitions. 1440 if (D->isThisDeclarationADefinition()) { 1441 // Check for a function body. 1442 const FunctionDecl *Definition = 0; 1443 if (Function->isDefined(Definition) && 1444 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1445 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1446 << Function->getDeclName(); 1447 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1448 } 1449 // Check for redefinitions due to other instantiations of this or 1450 // a similar friend function. 1451 else for (auto R : Function->redecls()) { 1452 if (R == Function) 1453 continue; 1454 1455 // If some prior declaration of this function has been used, we need 1456 // to instantiate its definition. 1457 if (!QueuedInstantiation && R->isUsed(false)) { 1458 if (MemberSpecializationInfo *MSInfo = 1459 Function->getMemberSpecializationInfo()) { 1460 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1461 SourceLocation Loc = R->getLocation(); // FIXME 1462 MSInfo->setPointOfInstantiation(Loc); 1463 SemaRef.PendingLocalImplicitInstantiations.push_back( 1464 std::make_pair(Function, Loc)); 1465 QueuedInstantiation = true; 1466 } 1467 } 1468 } 1469 1470 // If some prior declaration of this function was a friend with an 1471 // uninstantiated definition, reject it. 1472 if (R->getFriendObjectKind()) { 1473 if (const FunctionDecl *RPattern = 1474 R->getTemplateInstantiationPattern()) { 1475 if (RPattern->isDefined(RPattern)) { 1476 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1477 << Function->getDeclName(); 1478 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 1479 break; 1480 } 1481 } 1482 } 1483 } 1484 } 1485 } 1486 1487 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 1488 DC->makeDeclVisibleInContext(PrincipalDecl); 1489 1490 if (Function->isOverloadedOperator() && !DC->isRecord() && 1491 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1492 PrincipalDecl->setNonMemberOperator(); 1493 1494 assert(!D->isDefaulted() && "only methods should be defaulted"); 1495 return Function; 1496 } 1497 1498 Decl * 1499 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1500 TemplateParameterList *TemplateParams, 1501 bool IsClassScopeSpecialization) { 1502 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1503 if (FunctionTemplate && !TemplateParams) { 1504 // We are creating a function template specialization from a function 1505 // template. Check whether there is already a function template 1506 // specialization for this particular set of template arguments. 1507 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1508 1509 void *InsertPos = 0; 1510 FunctionDecl *SpecFunc 1511 = FunctionTemplate->findSpecialization(Innermost.begin(), 1512 Innermost.size(), 1513 InsertPos); 1514 1515 // If we already have a function template specialization, return it. 1516 if (SpecFunc) 1517 return SpecFunc; 1518 } 1519 1520 bool isFriend; 1521 if (FunctionTemplate) 1522 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1523 else 1524 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1525 1526 bool MergeWithParentScope = (TemplateParams != 0) || 1527 !(isa<Decl>(Owner) && 1528 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1529 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1530 1531 // Instantiate enclosing template arguments for friends. 1532 SmallVector<TemplateParameterList *, 4> TempParamLists; 1533 unsigned NumTempParamLists = 0; 1534 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 1535 TempParamLists.set_size(NumTempParamLists); 1536 for (unsigned I = 0; I != NumTempParamLists; ++I) { 1537 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 1538 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1539 if (!InstParams) 1540 return NULL; 1541 TempParamLists[I] = InstParams; 1542 } 1543 } 1544 1545 SmallVector<ParmVarDecl *, 4> Params; 1546 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1547 if (!TInfo) 1548 return 0; 1549 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1550 1551 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1552 if (QualifierLoc) { 1553 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1554 TemplateArgs); 1555 if (!QualifierLoc) 1556 return 0; 1557 } 1558 1559 DeclContext *DC = Owner; 1560 if (isFriend) { 1561 if (QualifierLoc) { 1562 CXXScopeSpec SS; 1563 SS.Adopt(QualifierLoc); 1564 DC = SemaRef.computeDeclContext(SS); 1565 1566 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 1567 return 0; 1568 } else { 1569 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1570 D->getDeclContext(), 1571 TemplateArgs); 1572 } 1573 if (!DC) return 0; 1574 } 1575 1576 // Build the instantiated method declaration. 1577 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1578 CXXMethodDecl *Method = 0; 1579 1580 SourceLocation StartLoc = D->getInnerLocStart(); 1581 DeclarationNameInfo NameInfo 1582 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1583 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1584 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1585 StartLoc, NameInfo, T, TInfo, 1586 Constructor->isExplicit(), 1587 Constructor->isInlineSpecified(), 1588 false, Constructor->isConstexpr()); 1589 1590 // Claim that the instantiation of a constructor or constructor template 1591 // inherits the same constructor that the template does. 1592 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>( 1593 Constructor->getInheritedConstructor())) { 1594 // If we're instantiating a specialization of a function template, our 1595 // "inherited constructor" will actually itself be a function template. 1596 // Instantiate a declaration of it, too. 1597 if (FunctionTemplate) { 1598 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() && 1599 !Inh->getParent()->isDependentContext() && 1600 "inheriting constructor template in dependent context?"); 1601 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(), 1602 Inh); 1603 if (Inst.isInvalid()) 1604 return 0; 1605 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext()); 1606 LocalInstantiationScope LocalScope(SemaRef); 1607 1608 // Use the same template arguments that we deduced for the inheriting 1609 // constructor. There's no way they could be deduced differently. 1610 MultiLevelTemplateArgumentList InheritedArgs; 1611 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost()); 1612 Inh = cast_or_null<CXXConstructorDecl>( 1613 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs)); 1614 if (!Inh) 1615 return 0; 1616 } 1617 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh); 1618 } 1619 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1620 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1621 StartLoc, NameInfo, T, TInfo, 1622 Destructor->isInlineSpecified(), 1623 false); 1624 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1625 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1626 StartLoc, NameInfo, T, TInfo, 1627 Conversion->isInlineSpecified(), 1628 Conversion->isExplicit(), 1629 Conversion->isConstexpr(), 1630 Conversion->getLocEnd()); 1631 } else { 1632 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 1633 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 1634 StartLoc, NameInfo, T, TInfo, 1635 SC, D->isInlineSpecified(), 1636 D->isConstexpr(), D->getLocEnd()); 1637 } 1638 1639 if (D->isInlined()) 1640 Method->setImplicitlyInline(); 1641 1642 if (QualifierLoc) 1643 Method->setQualifierInfo(QualifierLoc); 1644 1645 if (TemplateParams) { 1646 // Our resulting instantiation is actually a function template, since we 1647 // are substituting only the outer template parameters. For example, given 1648 // 1649 // template<typename T> 1650 // struct X { 1651 // template<typename U> void f(T, U); 1652 // }; 1653 // 1654 // X<int> x; 1655 // 1656 // We are instantiating the member template "f" within X<int>, which means 1657 // substituting int for T, but leaving "f" as a member function template. 1658 // Build the function template itself. 1659 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1660 Method->getLocation(), 1661 Method->getDeclName(), 1662 TemplateParams, Method); 1663 if (isFriend) { 1664 FunctionTemplate->setLexicalDeclContext(Owner); 1665 FunctionTemplate->setObjectOfFriendDecl(); 1666 } else if (D->isOutOfLine()) 1667 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1668 Method->setDescribedFunctionTemplate(FunctionTemplate); 1669 } else if (FunctionTemplate) { 1670 // Record this function template specialization. 1671 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1672 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1673 TemplateArgumentList::CreateCopy(SemaRef.Context, 1674 Innermost.begin(), 1675 Innermost.size()), 1676 /*InsertPos=*/0); 1677 } else if (!isFriend) { 1678 // Record that this is an instantiation of a member function. 1679 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1680 } 1681 1682 // If we are instantiating a member function defined 1683 // out-of-line, the instantiation will have the same lexical 1684 // context (which will be a namespace scope) as the template. 1685 if (isFriend) { 1686 if (NumTempParamLists) 1687 Method->setTemplateParameterListsInfo(SemaRef.Context, 1688 NumTempParamLists, 1689 TempParamLists.data()); 1690 1691 Method->setLexicalDeclContext(Owner); 1692 Method->setObjectOfFriendDecl(); 1693 } else if (D->isOutOfLine()) 1694 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1695 1696 // Attach the parameters 1697 for (unsigned P = 0; P < Params.size(); ++P) 1698 Params[P]->setOwningFunction(Method); 1699 Method->setParams(Params); 1700 1701 if (InitMethodInstantiation(Method, D)) 1702 Method->setInvalidDecl(); 1703 1704 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 1705 Sema::ForRedeclaration); 1706 1707 if (!FunctionTemplate || TemplateParams || isFriend) { 1708 SemaRef.LookupQualifiedName(Previous, Record); 1709 1710 // In C++, the previous declaration we find might be a tag type 1711 // (class or enum). In this case, the new declaration will hide the 1712 // tag type. Note that this does does not apply if we're declaring a 1713 // typedef (C++ [dcl.typedef]p4). 1714 if (Previous.isSingleTagDecl()) 1715 Previous.clear(); 1716 } 1717 1718 if (!IsClassScopeSpecialization) 1719 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false); 1720 1721 if (D->isPure()) 1722 SemaRef.CheckPureMethod(Method, SourceRange()); 1723 1724 // Propagate access. For a non-friend declaration, the access is 1725 // whatever we're propagating from. For a friend, it should be the 1726 // previous declaration we just found. 1727 if (isFriend && Method->getPreviousDecl()) 1728 Method->setAccess(Method->getPreviousDecl()->getAccess()); 1729 else 1730 Method->setAccess(D->getAccess()); 1731 if (FunctionTemplate) 1732 FunctionTemplate->setAccess(Method->getAccess()); 1733 1734 SemaRef.CheckOverrideControl(Method); 1735 1736 // If a function is defined as defaulted or deleted, mark it as such now. 1737 if (D->isExplicitlyDefaulted()) 1738 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 1739 if (D->isDeletedAsWritten()) 1740 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 1741 1742 // If there's a function template, let our caller handle it. 1743 if (FunctionTemplate) { 1744 // do nothing 1745 1746 // Don't hide a (potentially) valid declaration with an invalid one. 1747 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1748 // do nothing 1749 1750 // Otherwise, check access to friends and make them visible. 1751 } else if (isFriend) { 1752 // We only need to re-check access for methods which we didn't 1753 // manage to match during parsing. 1754 if (!D->getPreviousDecl()) 1755 SemaRef.CheckFriendAccess(Method); 1756 1757 Record->makeDeclVisibleInContext(Method); 1758 1759 // Otherwise, add the declaration. We don't need to do this for 1760 // class-scope specializations because we'll have matched them with 1761 // the appropriate template. 1762 } else if (!IsClassScopeSpecialization) { 1763 Owner->addDecl(Method); 1764 } 1765 1766 return Method; 1767 } 1768 1769 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1770 return VisitCXXMethodDecl(D); 1771 } 1772 1773 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1774 return VisitCXXMethodDecl(D); 1775 } 1776 1777 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1778 return VisitCXXMethodDecl(D); 1779 } 1780 1781 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1782 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 1783 /*ExpectParameterPack=*/ false); 1784 } 1785 1786 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1787 TemplateTypeParmDecl *D) { 1788 // TODO: don't always clone when decls are refcounted. 1789 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 1790 1791 TemplateTypeParmDecl *Inst = 1792 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 1793 D->getLocStart(), D->getLocation(), 1794 D->getDepth() - TemplateArgs.getNumLevels(), 1795 D->getIndex(), D->getIdentifier(), 1796 D->wasDeclaredWithTypename(), 1797 D->isParameterPack()); 1798 Inst->setAccess(AS_public); 1799 1800 if (D->hasDefaultArgument()) { 1801 TypeSourceInfo *InstantiatedDefaultArg = 1802 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 1803 D->getDefaultArgumentLoc(), D->getDeclName()); 1804 if (InstantiatedDefaultArg) 1805 Inst->setDefaultArgument(InstantiatedDefaultArg, false); 1806 } 1807 1808 // Introduce this template parameter's instantiation into the instantiation 1809 // scope. 1810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1811 1812 return Inst; 1813 } 1814 1815 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1816 NonTypeTemplateParmDecl *D) { 1817 // Substitute into the type of the non-type template parameter. 1818 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 1819 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 1820 SmallVector<QualType, 4> ExpandedParameterPackTypes; 1821 bool IsExpandedParameterPack = false; 1822 TypeSourceInfo *DI; 1823 QualType T; 1824 bool Invalid = false; 1825 1826 if (D->isExpandedParameterPack()) { 1827 // The non-type template parameter pack is an already-expanded pack 1828 // expansion of types. Substitute into each of the expanded types. 1829 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 1830 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 1831 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 1832 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 1833 TemplateArgs, 1834 D->getLocation(), 1835 D->getDeclName()); 1836 if (!NewDI) 1837 return 0; 1838 1839 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1840 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 1841 D->getLocation()); 1842 if (NewT.isNull()) 1843 return 0; 1844 ExpandedParameterPackTypes.push_back(NewT); 1845 } 1846 1847 IsExpandedParameterPack = true; 1848 DI = D->getTypeSourceInfo(); 1849 T = DI->getType(); 1850 } else if (D->isPackExpansion()) { 1851 // The non-type template parameter pack's type is a pack expansion of types. 1852 // Determine whether we need to expand this parameter pack into separate 1853 // types. 1854 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 1855 TypeLoc Pattern = Expansion.getPatternLoc(); 1856 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1857 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1858 1859 // Determine whether the set of unexpanded parameter packs can and should 1860 // be expanded. 1861 bool Expand = true; 1862 bool RetainExpansion = false; 1863 Optional<unsigned> OrigNumExpansions 1864 = Expansion.getTypePtr()->getNumExpansions(); 1865 Optional<unsigned> NumExpansions = OrigNumExpansions; 1866 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 1867 Pattern.getSourceRange(), 1868 Unexpanded, 1869 TemplateArgs, 1870 Expand, RetainExpansion, 1871 NumExpansions)) 1872 return 0; 1873 1874 if (Expand) { 1875 for (unsigned I = 0; I != *NumExpansions; ++I) { 1876 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 1877 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 1878 D->getLocation(), 1879 D->getDeclName()); 1880 if (!NewDI) 1881 return 0; 1882 1883 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1884 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 1885 NewDI->getType(), 1886 D->getLocation()); 1887 if (NewT.isNull()) 1888 return 0; 1889 ExpandedParameterPackTypes.push_back(NewT); 1890 } 1891 1892 // Note that we have an expanded parameter pack. The "type" of this 1893 // expanded parameter pack is the original expansion type, but callers 1894 // will end up using the expanded parameter pack types for type-checking. 1895 IsExpandedParameterPack = true; 1896 DI = D->getTypeSourceInfo(); 1897 T = DI->getType(); 1898 } else { 1899 // We cannot fully expand the pack expansion now, so substitute into the 1900 // pattern and create a new pack expansion type. 1901 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 1902 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 1903 D->getLocation(), 1904 D->getDeclName()); 1905 if (!NewPattern) 1906 return 0; 1907 1908 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 1909 NumExpansions); 1910 if (!DI) 1911 return 0; 1912 1913 T = DI->getType(); 1914 } 1915 } else { 1916 // Simple case: substitution into a parameter that is not a parameter pack. 1917 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 1918 D->getLocation(), D->getDeclName()); 1919 if (!DI) 1920 return 0; 1921 1922 // Check that this type is acceptable for a non-type template parameter. 1923 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 1924 D->getLocation()); 1925 if (T.isNull()) { 1926 T = SemaRef.Context.IntTy; 1927 Invalid = true; 1928 } 1929 } 1930 1931 NonTypeTemplateParmDecl *Param; 1932 if (IsExpandedParameterPack) 1933 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1934 D->getInnerLocStart(), 1935 D->getLocation(), 1936 D->getDepth() - TemplateArgs.getNumLevels(), 1937 D->getPosition(), 1938 D->getIdentifier(), T, 1939 DI, 1940 ExpandedParameterPackTypes.data(), 1941 ExpandedParameterPackTypes.size(), 1942 ExpandedParameterPackTypesAsWritten.data()); 1943 else 1944 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1945 D->getInnerLocStart(), 1946 D->getLocation(), 1947 D->getDepth() - TemplateArgs.getNumLevels(), 1948 D->getPosition(), 1949 D->getIdentifier(), T, 1950 D->isParameterPack(), DI); 1951 1952 Param->setAccess(AS_public); 1953 if (Invalid) 1954 Param->setInvalidDecl(); 1955 1956 if (D->hasDefaultArgument()) { 1957 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 1958 if (!Value.isInvalid()) 1959 Param->setDefaultArgument(Value.get(), false); 1960 } 1961 1962 // Introduce this template parameter's instantiation into the instantiation 1963 // scope. 1964 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1965 return Param; 1966 } 1967 1968 static void collectUnexpandedParameterPacks( 1969 Sema &S, 1970 TemplateParameterList *Params, 1971 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 1972 for (TemplateParameterList::const_iterator I = Params->begin(), 1973 E = Params->end(); I != E; ++I) { 1974 if ((*I)->isTemplateParameterPack()) 1975 continue; 1976 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I)) 1977 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 1978 Unexpanded); 1979 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I)) 1980 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 1981 Unexpanded); 1982 } 1983 } 1984 1985 Decl * 1986 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1987 TemplateTemplateParmDecl *D) { 1988 // Instantiate the template parameter list of the template template parameter. 1989 TemplateParameterList *TempParams = D->getTemplateParameters(); 1990 TemplateParameterList *InstParams; 1991 SmallVector<TemplateParameterList*, 8> ExpandedParams; 1992 1993 bool IsExpandedParameterPack = false; 1994 1995 if (D->isExpandedParameterPack()) { 1996 // The template template parameter pack is an already-expanded pack 1997 // expansion of template parameters. Substitute into each of the expanded 1998 // parameters. 1999 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2000 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2001 I != N; ++I) { 2002 LocalInstantiationScope Scope(SemaRef); 2003 TemplateParameterList *Expansion = 2004 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2005 if (!Expansion) 2006 return 0; 2007 ExpandedParams.push_back(Expansion); 2008 } 2009 2010 IsExpandedParameterPack = true; 2011 InstParams = TempParams; 2012 } else if (D->isPackExpansion()) { 2013 // The template template parameter pack expands to a pack of template 2014 // template parameters. Determine whether we need to expand this parameter 2015 // pack into separate parameters. 2016 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2017 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 2018 Unexpanded); 2019 2020 // Determine whether the set of unexpanded parameter packs can and should 2021 // be expanded. 2022 bool Expand = true; 2023 bool RetainExpansion = false; 2024 Optional<unsigned> NumExpansions; 2025 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2026 TempParams->getSourceRange(), 2027 Unexpanded, 2028 TemplateArgs, 2029 Expand, RetainExpansion, 2030 NumExpansions)) 2031 return 0; 2032 2033 if (Expand) { 2034 for (unsigned I = 0; I != *NumExpansions; ++I) { 2035 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2036 LocalInstantiationScope Scope(SemaRef); 2037 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2038 if (!Expansion) 2039 return 0; 2040 ExpandedParams.push_back(Expansion); 2041 } 2042 2043 // Note that we have an expanded parameter pack. The "type" of this 2044 // expanded parameter pack is the original expansion type, but callers 2045 // will end up using the expanded parameter pack types for type-checking. 2046 IsExpandedParameterPack = true; 2047 InstParams = TempParams; 2048 } else { 2049 // We cannot fully expand the pack expansion now, so just substitute 2050 // into the pattern. 2051 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2052 2053 LocalInstantiationScope Scope(SemaRef); 2054 InstParams = SubstTemplateParams(TempParams); 2055 if (!InstParams) 2056 return 0; 2057 } 2058 } else { 2059 // Perform the actual substitution of template parameters within a new, 2060 // local instantiation scope. 2061 LocalInstantiationScope Scope(SemaRef); 2062 InstParams = SubstTemplateParams(TempParams); 2063 if (!InstParams) 2064 return 0; 2065 } 2066 2067 // Build the template template parameter. 2068 TemplateTemplateParmDecl *Param; 2069 if (IsExpandedParameterPack) 2070 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 2071 D->getLocation(), 2072 D->getDepth() - TemplateArgs.getNumLevels(), 2073 D->getPosition(), 2074 D->getIdentifier(), InstParams, 2075 ExpandedParams); 2076 else 2077 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 2078 D->getLocation(), 2079 D->getDepth() - TemplateArgs.getNumLevels(), 2080 D->getPosition(), 2081 D->isParameterPack(), 2082 D->getIdentifier(), InstParams); 2083 if (D->hasDefaultArgument()) { 2084 NestedNameSpecifierLoc QualifierLoc = 2085 D->getDefaultArgument().getTemplateQualifierLoc(); 2086 QualifierLoc = 2087 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2088 TemplateName TName = SemaRef.SubstTemplateName( 2089 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2090 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2091 if (!TName.isNull()) 2092 Param->setDefaultArgument( 2093 TemplateArgumentLoc(TemplateArgument(TName), 2094 D->getDefaultArgument().getTemplateQualifierLoc(), 2095 D->getDefaultArgument().getTemplateNameLoc()), 2096 false); 2097 } 2098 Param->setAccess(AS_public); 2099 2100 // Introduce this template parameter's instantiation into the instantiation 2101 // scope. 2102 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2103 2104 return Param; 2105 } 2106 2107 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2108 // Using directives are never dependent (and never contain any types or 2109 // expressions), so they require no explicit instantiation work. 2110 2111 UsingDirectiveDecl *Inst 2112 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2113 D->getNamespaceKeyLocation(), 2114 D->getQualifierLoc(), 2115 D->getIdentLocation(), 2116 D->getNominatedNamespace(), 2117 D->getCommonAncestor()); 2118 2119 // Add the using directive to its declaration context 2120 // only if this is not a function or method. 2121 if (!Owner->isFunctionOrMethod()) 2122 Owner->addDecl(Inst); 2123 2124 return Inst; 2125 } 2126 2127 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2128 2129 // The nested name specifier may be dependent, for example 2130 // template <typename T> struct t { 2131 // struct s1 { T f1(); }; 2132 // struct s2 : s1 { using s1::f1; }; 2133 // }; 2134 // template struct t<int>; 2135 // Here, in using s1::f1, s1 refers to t<T>::s1; 2136 // we need to substitute for t<int>::s1. 2137 NestedNameSpecifierLoc QualifierLoc 2138 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2139 TemplateArgs); 2140 if (!QualifierLoc) 2141 return 0; 2142 2143 // The name info is non-dependent, so no transformation 2144 // is required. 2145 DeclarationNameInfo NameInfo = D->getNameInfo(); 2146 2147 // We only need to do redeclaration lookups if we're in a class 2148 // scope (in fact, it's not really even possible in non-class 2149 // scopes). 2150 bool CheckRedeclaration = Owner->isRecord(); 2151 2152 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2153 Sema::ForRedeclaration); 2154 2155 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2156 D->getUsingLoc(), 2157 QualifierLoc, 2158 NameInfo, 2159 D->hasTypename()); 2160 2161 CXXScopeSpec SS; 2162 SS.Adopt(QualifierLoc); 2163 if (CheckRedeclaration) { 2164 Prev.setHideTags(false); 2165 SemaRef.LookupQualifiedName(Prev, Owner); 2166 2167 // Check for invalid redeclarations. 2168 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2169 D->hasTypename(), SS, 2170 D->getLocation(), Prev)) 2171 NewUD->setInvalidDecl(); 2172 2173 } 2174 2175 if (!NewUD->isInvalidDecl() && 2176 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, 2177 D->getLocation())) 2178 NewUD->setInvalidDecl(); 2179 2180 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2181 NewUD->setAccess(D->getAccess()); 2182 Owner->addDecl(NewUD); 2183 2184 // Don't process the shadow decls for an invalid decl. 2185 if (NewUD->isInvalidDecl()) 2186 return NewUD; 2187 2188 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 2189 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD)) 2190 NewUD->setInvalidDecl(); 2191 return NewUD; 2192 } 2193 2194 bool isFunctionScope = Owner->isFunctionOrMethod(); 2195 2196 // Process the shadow decls. 2197 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 2198 I != E; ++I) { 2199 UsingShadowDecl *Shadow = *I; 2200 NamedDecl *InstTarget = 2201 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2202 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs)); 2203 if (!InstTarget) 2204 return 0; 2205 2206 UsingShadowDecl *PrevDecl = 0; 2207 if (CheckRedeclaration) { 2208 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2209 continue; 2210 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) { 2211 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2212 Shadow->getLocation(), OldPrev, TemplateArgs)); 2213 } 2214 2215 UsingShadowDecl *InstShadow = 2216 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl); 2217 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2218 2219 if (isFunctionScope) 2220 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2221 } 2222 2223 return NewUD; 2224 } 2225 2226 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2227 // Ignore these; we handle them in bulk when processing the UsingDecl. 2228 return 0; 2229 } 2230 2231 Decl * TemplateDeclInstantiator 2232 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 2233 NestedNameSpecifierLoc QualifierLoc 2234 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2235 TemplateArgs); 2236 if (!QualifierLoc) 2237 return 0; 2238 2239 CXXScopeSpec SS; 2240 SS.Adopt(QualifierLoc); 2241 2242 // Since NameInfo refers to a typename, it cannot be a C++ special name. 2243 // Hence, no transformation is required for it. 2244 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 2245 NamedDecl *UD = 2246 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 2247 D->getUsingLoc(), SS, NameInfo, 0, 2248 /*instantiation*/ true, 2249 /*typename*/ true, D->getTypenameLoc()); 2250 if (UD) 2251 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 2252 2253 return UD; 2254 } 2255 2256 Decl * TemplateDeclInstantiator 2257 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 2258 NestedNameSpecifierLoc QualifierLoc 2259 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 2260 if (!QualifierLoc) 2261 return 0; 2262 2263 CXXScopeSpec SS; 2264 SS.Adopt(QualifierLoc); 2265 2266 DeclarationNameInfo NameInfo 2267 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2268 2269 NamedDecl *UD = 2270 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 2271 D->getUsingLoc(), SS, NameInfo, 0, 2272 /*instantiation*/ true, 2273 /*typename*/ false, SourceLocation()); 2274 if (UD) 2275 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 2276 2277 return UD; 2278 } 2279 2280 2281 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 2282 ClassScopeFunctionSpecializationDecl *Decl) { 2283 CXXMethodDecl *OldFD = Decl->getSpecialization(); 2284 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 2285 0, true)); 2286 2287 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName, 2288 Sema::ForRedeclaration); 2289 2290 TemplateArgumentListInfo TemplateArgs; 2291 TemplateArgumentListInfo* TemplateArgsPtr = 0; 2292 if (Decl->hasExplicitTemplateArgs()) { 2293 TemplateArgs = Decl->templateArgs(); 2294 TemplateArgsPtr = &TemplateArgs; 2295 } 2296 2297 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext); 2298 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr, 2299 Previous)) { 2300 NewFD->setInvalidDecl(); 2301 return NewFD; 2302 } 2303 2304 // Associate the specialization with the pattern. 2305 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl()); 2306 assert(Specialization && "Class scope Specialization is null"); 2307 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD); 2308 2309 return NewFD; 2310 } 2311 2312 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 2313 OMPThreadPrivateDecl *D) { 2314 SmallVector<Expr *, 5> Vars; 2315 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(), 2316 E = D->varlist_end(); 2317 I != E; ++I) { 2318 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take(); 2319 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 2320 Vars.push_back(Var); 2321 } 2322 2323 OMPThreadPrivateDecl *TD = 2324 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 2325 2326 TD->setAccess(AS_public); 2327 Owner->addDecl(TD); 2328 2329 return TD; 2330 } 2331 2332 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 2333 return VisitFunctionDecl(D, 0); 2334 } 2335 2336 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 2337 return VisitCXXMethodDecl(D, 0); 2338 } 2339 2340 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 2341 llvm_unreachable("There are only CXXRecordDecls in C++"); 2342 } 2343 2344 Decl * 2345 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 2346 ClassTemplateSpecializationDecl *D) { 2347 // As a MS extension, we permit class-scope explicit specialization 2348 // of member class templates. 2349 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 2350 assert(ClassTemplate->getDeclContext()->isRecord() && 2351 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 2352 "can only instantiate an explicit specialization " 2353 "for a member class template"); 2354 2355 // Lookup the already-instantiated declaration in the instantiation 2356 // of the class template. FIXME: Diagnose or assert if this fails? 2357 DeclContext::lookup_result Found 2358 = Owner->lookup(ClassTemplate->getDeclName()); 2359 if (Found.empty()) 2360 return 0; 2361 ClassTemplateDecl *InstClassTemplate 2362 = dyn_cast<ClassTemplateDecl>(Found.front()); 2363 if (!InstClassTemplate) 2364 return 0; 2365 2366 // Substitute into the template arguments of the class template explicit 2367 // specialization. 2368 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 2369 castAs<TemplateSpecializationTypeLoc>(); 2370 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 2371 Loc.getRAngleLoc()); 2372 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 2373 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 2374 ArgLocs.push_back(Loc.getArgLoc(I)); 2375 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 2376 InstTemplateArgs, TemplateArgs)) 2377 return 0; 2378 2379 // Check that the template argument list is well-formed for this 2380 // class template. 2381 SmallVector<TemplateArgument, 4> Converted; 2382 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 2383 D->getLocation(), 2384 InstTemplateArgs, 2385 false, 2386 Converted)) 2387 return 0; 2388 2389 // Figure out where to insert this class template explicit specialization 2390 // in the member template's set of class template explicit specializations. 2391 void *InsertPos = 0; 2392 ClassTemplateSpecializationDecl *PrevDecl = 2393 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(), 2394 InsertPos); 2395 2396 // Check whether we've already seen a conflicting instantiation of this 2397 // declaration (for instance, if there was a prior implicit instantiation). 2398 bool Ignored; 2399 if (PrevDecl && 2400 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 2401 D->getSpecializationKind(), 2402 PrevDecl, 2403 PrevDecl->getSpecializationKind(), 2404 PrevDecl->getPointOfInstantiation(), 2405 Ignored)) 2406 return 0; 2407 2408 // If PrevDecl was a definition and D is also a definition, diagnose. 2409 // This happens in cases like: 2410 // 2411 // template<typename T, typename U> 2412 // struct Outer { 2413 // template<typename X> struct Inner; 2414 // template<> struct Inner<T> {}; 2415 // template<> struct Inner<U> {}; 2416 // }; 2417 // 2418 // Outer<int, int> outer; // error: the explicit specializations of Inner 2419 // // have the same signature. 2420 if (PrevDecl && PrevDecl->getDefinition() && 2421 D->isThisDeclarationADefinition()) { 2422 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 2423 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 2424 diag::note_previous_definition); 2425 return 0; 2426 } 2427 2428 // Create the class template partial specialization declaration. 2429 ClassTemplateSpecializationDecl *InstD 2430 = ClassTemplateSpecializationDecl::Create(SemaRef.Context, 2431 D->getTagKind(), 2432 Owner, 2433 D->getLocStart(), 2434 D->getLocation(), 2435 InstClassTemplate, 2436 Converted.data(), 2437 Converted.size(), 2438 PrevDecl); 2439 2440 // Add this partial specialization to the set of class template partial 2441 // specializations. 2442 if (!PrevDecl) 2443 InstClassTemplate->AddSpecialization(InstD, InsertPos); 2444 2445 // Substitute the nested name specifier, if any. 2446 if (SubstQualifier(D, InstD)) 2447 return 0; 2448 2449 // Build the canonical type that describes the converted template 2450 // arguments of the class template explicit specialization. 2451 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 2452 TemplateName(InstClassTemplate), Converted.data(), Converted.size(), 2453 SemaRef.Context.getRecordType(InstD)); 2454 2455 // Build the fully-sugared type for this class template 2456 // specialization as the user wrote in the specialization 2457 // itself. This means that we'll pretty-print the type retrieved 2458 // from the specialization's declaration the way that the user 2459 // actually wrote the specialization, rather than formatting the 2460 // name based on the "canonical" representation used to store the 2461 // template arguments in the specialization. 2462 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 2463 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 2464 CanonType); 2465 2466 InstD->setAccess(D->getAccess()); 2467 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 2468 InstD->setSpecializationKind(D->getSpecializationKind()); 2469 InstD->setTypeAsWritten(WrittenTy); 2470 InstD->setExternLoc(D->getExternLoc()); 2471 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 2472 2473 Owner->addDecl(InstD); 2474 2475 // Instantiate the members of the class-scope explicit specialization eagerly. 2476 // We don't have support for lazy instantiation of an explicit specialization 2477 // yet, and MSVC eagerly instantiates in this case. 2478 if (D->isThisDeclarationADefinition() && 2479 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 2480 TSK_ImplicitInstantiation, 2481 /*Complain=*/true)) 2482 return 0; 2483 2484 return InstD; 2485 } 2486 2487 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 2488 VarTemplateSpecializationDecl *D) { 2489 2490 TemplateArgumentListInfo VarTemplateArgsInfo; 2491 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 2492 assert(VarTemplate && 2493 "A template specialization without specialized template?"); 2494 2495 // Substitute the current template arguments. 2496 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 2497 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 2498 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 2499 2500 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 2501 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 2502 return 0; 2503 2504 // Check that the template argument list is well-formed for this template. 2505 SmallVector<TemplateArgument, 4> Converted; 2506 if (SemaRef.CheckTemplateArgumentList( 2507 VarTemplate, VarTemplate->getLocStart(), 2508 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false, 2509 Converted)) 2510 return 0; 2511 2512 // Find the variable template specialization declaration that 2513 // corresponds to these arguments. 2514 void *InsertPos = 0; 2515 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization( 2516 Converted.data(), Converted.size(), InsertPos)) 2517 // If we already have a variable template specialization, return it. 2518 return VarSpec; 2519 2520 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos, 2521 VarTemplateArgsInfo, Converted); 2522 } 2523 2524 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 2525 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 2526 const TemplateArgumentListInfo &TemplateArgsInfo, 2527 llvm::ArrayRef<TemplateArgument> Converted) { 2528 2529 // If this is the variable for an anonymous struct or union, 2530 // instantiate the anonymous struct/union type first. 2531 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 2532 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 2533 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 2534 return 0; 2535 2536 // Do substitution on the type of the declaration 2537 TypeSourceInfo *DI = 2538 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2539 D->getTypeSpecStartLoc(), D->getDeclName()); 2540 if (!DI) 2541 return 0; 2542 2543 if (DI->getType()->isFunctionType()) { 2544 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 2545 << D->isStaticDataMember() << DI->getType(); 2546 return 0; 2547 } 2548 2549 // Build the instantiated declaration 2550 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 2551 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2552 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(), 2553 Converted.size()); 2554 Var->setTemplateArgsInfo(TemplateArgsInfo); 2555 if (InsertPos) 2556 VarTemplate->AddSpecialization(Var, InsertPos); 2557 2558 // Substitute the nested name specifier, if any. 2559 if (SubstQualifier(D, Var)) 2560 return 0; 2561 2562 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, 2563 Owner, StartingScope); 2564 2565 return Var; 2566 } 2567 2568 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 2569 llvm_unreachable("@defs is not supported in Objective-C++"); 2570 } 2571 2572 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 2573 // FIXME: We need to be able to instantiate FriendTemplateDecls. 2574 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 2575 DiagnosticsEngine::Error, 2576 "cannot instantiate %0 yet"); 2577 SemaRef.Diag(D->getLocation(), DiagID) 2578 << D->getDeclKindName(); 2579 2580 return 0; 2581 } 2582 2583 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 2584 llvm_unreachable("Unexpected decl"); 2585 } 2586 2587 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 2588 const MultiLevelTemplateArgumentList &TemplateArgs) { 2589 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 2590 if (D->isInvalidDecl()) 2591 return 0; 2592 2593 return Instantiator.Visit(D); 2594 } 2595 2596 /// \brief Instantiates a nested template parameter list in the current 2597 /// instantiation context. 2598 /// 2599 /// \param L The parameter list to instantiate 2600 /// 2601 /// \returns NULL if there was an error 2602 TemplateParameterList * 2603 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 2604 // Get errors for all the parameters before bailing out. 2605 bool Invalid = false; 2606 2607 unsigned N = L->size(); 2608 typedef SmallVector<NamedDecl *, 8> ParamVector; 2609 ParamVector Params; 2610 Params.reserve(N); 2611 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 2612 PI != PE; ++PI) { 2613 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 2614 Params.push_back(D); 2615 Invalid = Invalid || !D || D->isInvalidDecl(); 2616 } 2617 2618 // Clean up if we had an error. 2619 if (Invalid) 2620 return NULL; 2621 2622 TemplateParameterList *InstL 2623 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 2624 L->getLAngleLoc(), &Params.front(), N, 2625 L->getRAngleLoc()); 2626 return InstL; 2627 } 2628 2629 /// \brief Instantiate the declaration of a class template partial 2630 /// specialization. 2631 /// 2632 /// \param ClassTemplate the (instantiated) class template that is partially 2633 // specialized by the instantiation of \p PartialSpec. 2634 /// 2635 /// \param PartialSpec the (uninstantiated) class template partial 2636 /// specialization that we are instantiating. 2637 /// 2638 /// \returns The instantiated partial specialization, if successful; otherwise, 2639 /// NULL to indicate an error. 2640 ClassTemplatePartialSpecializationDecl * 2641 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 2642 ClassTemplateDecl *ClassTemplate, 2643 ClassTemplatePartialSpecializationDecl *PartialSpec) { 2644 // Create a local instantiation scope for this class template partial 2645 // specialization, which will contain the instantiations of the template 2646 // parameters. 2647 LocalInstantiationScope Scope(SemaRef); 2648 2649 // Substitute into the template parameters of the class template partial 2650 // specialization. 2651 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2652 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2653 if (!InstParams) 2654 return 0; 2655 2656 // Substitute into the template arguments of the class template partial 2657 // specialization. 2658 const ASTTemplateArgumentListInfo *TemplArgInfo 2659 = PartialSpec->getTemplateArgsAsWritten(); 2660 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 2661 TemplArgInfo->RAngleLoc); 2662 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 2663 TemplArgInfo->NumTemplateArgs, 2664 InstTemplateArgs, TemplateArgs)) 2665 return 0; 2666 2667 // Check that the template argument list is well-formed for this 2668 // class template. 2669 SmallVector<TemplateArgument, 4> Converted; 2670 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 2671 PartialSpec->getLocation(), 2672 InstTemplateArgs, 2673 false, 2674 Converted)) 2675 return 0; 2676 2677 // Figure out where to insert this class template partial specialization 2678 // in the member template's set of class template partial specializations. 2679 void *InsertPos = 0; 2680 ClassTemplateSpecializationDecl *PrevDecl 2681 = ClassTemplate->findPartialSpecialization(Converted.data(), 2682 Converted.size(), InsertPos); 2683 2684 // Build the canonical type that describes the converted template 2685 // arguments of the class template partial specialization. 2686 QualType CanonType 2687 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 2688 Converted.data(), 2689 Converted.size()); 2690 2691 // Build the fully-sugared type for this class template 2692 // specialization as the user wrote in the specialization 2693 // itself. This means that we'll pretty-print the type retrieved 2694 // from the specialization's declaration the way that the user 2695 // actually wrote the specialization, rather than formatting the 2696 // name based on the "canonical" representation used to store the 2697 // template arguments in the specialization. 2698 TypeSourceInfo *WrittenTy 2699 = SemaRef.Context.getTemplateSpecializationTypeInfo( 2700 TemplateName(ClassTemplate), 2701 PartialSpec->getLocation(), 2702 InstTemplateArgs, 2703 CanonType); 2704 2705 if (PrevDecl) { 2706 // We've already seen a partial specialization with the same template 2707 // parameters and template arguments. This can happen, for example, when 2708 // substituting the outer template arguments ends up causing two 2709 // class template partial specializations of a member class template 2710 // to have identical forms, e.g., 2711 // 2712 // template<typename T, typename U> 2713 // struct Outer { 2714 // template<typename X, typename Y> struct Inner; 2715 // template<typename Y> struct Inner<T, Y>; 2716 // template<typename Y> struct Inner<U, Y>; 2717 // }; 2718 // 2719 // Outer<int, int> outer; // error: the partial specializations of Inner 2720 // // have the same signature. 2721 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 2722 << WrittenTy->getType(); 2723 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 2724 << SemaRef.Context.getTypeDeclType(PrevDecl); 2725 return 0; 2726 } 2727 2728 2729 // Create the class template partial specialization declaration. 2730 ClassTemplatePartialSpecializationDecl *InstPartialSpec 2731 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 2732 PartialSpec->getTagKind(), 2733 Owner, 2734 PartialSpec->getLocStart(), 2735 PartialSpec->getLocation(), 2736 InstParams, 2737 ClassTemplate, 2738 Converted.data(), 2739 Converted.size(), 2740 InstTemplateArgs, 2741 CanonType, 2742 0); 2743 // Substitute the nested name specifier, if any. 2744 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2745 return 0; 2746 2747 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2748 InstPartialSpec->setTypeAsWritten(WrittenTy); 2749 2750 // Add this partial specialization to the set of class template partial 2751 // specializations. 2752 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0); 2753 return InstPartialSpec; 2754 } 2755 2756 /// \brief Instantiate the declaration of a variable template partial 2757 /// specialization. 2758 /// 2759 /// \param VarTemplate the (instantiated) variable template that is partially 2760 /// specialized by the instantiation of \p PartialSpec. 2761 /// 2762 /// \param PartialSpec the (uninstantiated) variable template partial 2763 /// specialization that we are instantiating. 2764 /// 2765 /// \returns The instantiated partial specialization, if successful; otherwise, 2766 /// NULL to indicate an error. 2767 VarTemplatePartialSpecializationDecl * 2768 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 2769 VarTemplateDecl *VarTemplate, 2770 VarTemplatePartialSpecializationDecl *PartialSpec) { 2771 // Create a local instantiation scope for this variable template partial 2772 // specialization, which will contain the instantiations of the template 2773 // parameters. 2774 LocalInstantiationScope Scope(SemaRef); 2775 2776 // Substitute into the template parameters of the variable template partial 2777 // specialization. 2778 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2779 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2780 if (!InstParams) 2781 return 0; 2782 2783 // Substitute into the template arguments of the variable template partial 2784 // specialization. 2785 const ASTTemplateArgumentListInfo *TemplArgInfo 2786 = PartialSpec->getTemplateArgsAsWritten(); 2787 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 2788 TemplArgInfo->RAngleLoc); 2789 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 2790 TemplArgInfo->NumTemplateArgs, 2791 InstTemplateArgs, TemplateArgs)) 2792 return 0; 2793 2794 // Check that the template argument list is well-formed for this 2795 // class template. 2796 SmallVector<TemplateArgument, 4> Converted; 2797 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 2798 InstTemplateArgs, false, Converted)) 2799 return 0; 2800 2801 // Figure out where to insert this variable template partial specialization 2802 // in the member template's set of variable template partial specializations. 2803 void *InsertPos = 0; 2804 VarTemplateSpecializationDecl *PrevDecl = 2805 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(), 2806 InsertPos); 2807 2808 // Build the canonical type that describes the converted template 2809 // arguments of the variable template partial specialization. 2810 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 2811 TemplateName(VarTemplate), Converted.data(), Converted.size()); 2812 2813 // Build the fully-sugared type for this variable template 2814 // specialization as the user wrote in the specialization 2815 // itself. This means that we'll pretty-print the type retrieved 2816 // from the specialization's declaration the way that the user 2817 // actually wrote the specialization, rather than formatting the 2818 // name based on the "canonical" representation used to store the 2819 // template arguments in the specialization. 2820 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 2821 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 2822 CanonType); 2823 2824 if (PrevDecl) { 2825 // We've already seen a partial specialization with the same template 2826 // parameters and template arguments. This can happen, for example, when 2827 // substituting the outer template arguments ends up causing two 2828 // variable template partial specializations of a member variable template 2829 // to have identical forms, e.g., 2830 // 2831 // template<typename T, typename U> 2832 // struct Outer { 2833 // template<typename X, typename Y> pair<X,Y> p; 2834 // template<typename Y> pair<T, Y> p; 2835 // template<typename Y> pair<U, Y> p; 2836 // }; 2837 // 2838 // Outer<int, int> outer; // error: the partial specializations of Inner 2839 // // have the same signature. 2840 SemaRef.Diag(PartialSpec->getLocation(), 2841 diag::err_var_partial_spec_redeclared) 2842 << WrittenTy->getType(); 2843 SemaRef.Diag(PrevDecl->getLocation(), 2844 diag::note_var_prev_partial_spec_here); 2845 return 0; 2846 } 2847 2848 // Do substitution on the type of the declaration 2849 TypeSourceInfo *DI = SemaRef.SubstType( 2850 PartialSpec->getTypeSourceInfo(), TemplateArgs, 2851 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 2852 if (!DI) 2853 return 0; 2854 2855 if (DI->getType()->isFunctionType()) { 2856 SemaRef.Diag(PartialSpec->getLocation(), 2857 diag::err_variable_instantiates_to_function) 2858 << PartialSpec->isStaticDataMember() << DI->getType(); 2859 return 0; 2860 } 2861 2862 // Create the variable template partial specialization declaration. 2863 VarTemplatePartialSpecializationDecl *InstPartialSpec = 2864 VarTemplatePartialSpecializationDecl::Create( 2865 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 2866 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 2867 DI, PartialSpec->getStorageClass(), Converted.data(), 2868 Converted.size(), InstTemplateArgs); 2869 2870 // Substitute the nested name specifier, if any. 2871 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2872 return 0; 2873 2874 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2875 InstPartialSpec->setTypeAsWritten(WrittenTy); 2876 2877 // Add this partial specialization to the set of variable template partial 2878 // specializations. The instantiation of the initializer is not necessary. 2879 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0); 2880 2881 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 2882 LateAttrs, Owner, StartingScope); 2883 2884 return InstPartialSpec; 2885 } 2886 2887 TypeSourceInfo* 2888 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 2889 SmallVectorImpl<ParmVarDecl *> &Params) { 2890 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 2891 assert(OldTInfo && "substituting function without type source info"); 2892 assert(Params.empty() && "parameter vector is non-empty at start"); 2893 2894 CXXRecordDecl *ThisContext = 0; 2895 unsigned ThisTypeQuals = 0; 2896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 2897 ThisContext = cast<CXXRecordDecl>(Owner); 2898 ThisTypeQuals = Method->getTypeQualifiers(); 2899 } 2900 2901 TypeSourceInfo *NewTInfo 2902 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 2903 D->getTypeSpecStartLoc(), 2904 D->getDeclName(), 2905 ThisContext, ThisTypeQuals); 2906 if (!NewTInfo) 2907 return 0; 2908 2909 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2910 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 2911 if (NewTInfo != OldTInfo) { 2912 // Get parameters from the new type info. 2913 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 2914 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 2915 unsigned NewIdx = 0; 2916 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 2917 OldIdx != NumOldParams; ++OldIdx) { 2918 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 2919 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 2920 2921 Optional<unsigned> NumArgumentsInExpansion; 2922 if (OldParam->isParameterPack()) 2923 NumArgumentsInExpansion = 2924 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 2925 TemplateArgs); 2926 if (!NumArgumentsInExpansion) { 2927 // Simple case: normal parameter, or a parameter pack that's 2928 // instantiated to a (still-dependent) parameter pack. 2929 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 2930 Params.push_back(NewParam); 2931 Scope->InstantiatedLocal(OldParam, NewParam); 2932 } else { 2933 // Parameter pack expansion: make the instantiation an argument pack. 2934 Scope->MakeInstantiatedLocalArgPack(OldParam); 2935 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 2936 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 2937 Params.push_back(NewParam); 2938 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 2939 } 2940 } 2941 } 2942 } else { 2943 // The function type itself was not dependent and therefore no 2944 // substitution occurred. However, we still need to instantiate 2945 // the function parameters themselves. 2946 const FunctionProtoType *OldProto = 2947 cast<FunctionProtoType>(OldProtoLoc.getType()); 2948 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 2949 ++i) { 2950 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 2951 if (!OldParam) { 2952 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 2953 D, D->getLocation(), OldProto->getParamType(i))); 2954 continue; 2955 } 2956 2957 ParmVarDecl *Parm = 2958 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 2959 if (!Parm) 2960 return 0; 2961 Params.push_back(Parm); 2962 } 2963 } 2964 } else { 2965 // If the type of this function, after ignoring parentheses, is not 2966 // *directly* a function type, then we're instantiating a function that 2967 // was declared via a typedef or with attributes, e.g., 2968 // 2969 // typedef int functype(int, int); 2970 // functype func; 2971 // int __cdecl meth(int, int); 2972 // 2973 // In this case, we'll just go instantiate the ParmVarDecls that we 2974 // synthesized in the method declaration. 2975 SmallVector<QualType, 4> ParamTypes; 2976 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 2977 D->getNumParams(), TemplateArgs, ParamTypes, 2978 &Params)) 2979 return 0; 2980 } 2981 2982 return NewTInfo; 2983 } 2984 2985 /// Introduce the instantiated function parameters into the local 2986 /// instantiation scope, and set the parameter names to those used 2987 /// in the template. 2988 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 2989 const FunctionDecl *PatternDecl, 2990 LocalInstantiationScope &Scope, 2991 const MultiLevelTemplateArgumentList &TemplateArgs) { 2992 unsigned FParamIdx = 0; 2993 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 2994 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 2995 if (!PatternParam->isParameterPack()) { 2996 // Simple case: not a parameter pack. 2997 assert(FParamIdx < Function->getNumParams()); 2998 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2999 FunctionParam->setDeclName(PatternParam->getDeclName()); 3000 Scope.InstantiatedLocal(PatternParam, FunctionParam); 3001 ++FParamIdx; 3002 continue; 3003 } 3004 3005 // Expand the parameter pack. 3006 Scope.MakeInstantiatedLocalArgPack(PatternParam); 3007 Optional<unsigned> NumArgumentsInExpansion 3008 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 3009 assert(NumArgumentsInExpansion && 3010 "should only be called when all template arguments are known"); 3011 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 3012 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3013 FunctionParam->setDeclName(PatternParam->getDeclName()); 3014 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 3015 ++FParamIdx; 3016 } 3017 } 3018 } 3019 3020 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New, 3021 const FunctionProtoType *Proto, 3022 const MultiLevelTemplateArgumentList &TemplateArgs) { 3023 assert(Proto->getExceptionSpecType() != EST_Uninstantiated); 3024 3025 // C++11 [expr.prim.general]p3: 3026 // If a declaration declares a member function or member function 3027 // template of a class X, the expression this is a prvalue of type 3028 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 3029 // and the end of the function-definition, member-declarator, or 3030 // declarator. 3031 CXXRecordDecl *ThisContext = 0; 3032 unsigned ThisTypeQuals = 0; 3033 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) { 3034 ThisContext = Method->getParent(); 3035 ThisTypeQuals = Method->getTypeQualifiers(); 3036 } 3037 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals, 3038 SemaRef.getLangOpts().CPlusPlus11); 3039 3040 // The function has an exception specification or a "noreturn" 3041 // attribute. Substitute into each of the exception types. 3042 SmallVector<QualType, 4> Exceptions; 3043 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 3044 // FIXME: Poor location information! 3045 if (const PackExpansionType *PackExpansion 3046 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) { 3047 // We have a pack expansion. Instantiate it. 3048 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 3049 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(), 3050 Unexpanded); 3051 assert(!Unexpanded.empty() && 3052 "Pack expansion without parameter packs?"); 3053 3054 bool Expand = false; 3055 bool RetainExpansion = false; 3056 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); 3057 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(), 3058 SourceRange(), 3059 Unexpanded, 3060 TemplateArgs, 3061 Expand, 3062 RetainExpansion, 3063 NumExpansions)) 3064 break; 3065 3066 if (!Expand) { 3067 // We can't expand this pack expansion into separate arguments yet; 3068 // just substitute into the pattern and create a new pack expansion 3069 // type. 3070 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 3071 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 3072 TemplateArgs, 3073 New->getLocation(), New->getDeclName()); 3074 if (T.isNull()) 3075 break; 3076 3077 T = SemaRef.Context.getPackExpansionType(T, NumExpansions); 3078 Exceptions.push_back(T); 3079 continue; 3080 } 3081 3082 // Substitute into the pack expansion pattern for each template 3083 bool Invalid = false; 3084 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) { 3085 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx); 3086 3087 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 3088 TemplateArgs, 3089 New->getLocation(), New->getDeclName()); 3090 if (T.isNull()) { 3091 Invalid = true; 3092 break; 3093 } 3094 3095 Exceptions.push_back(T); 3096 } 3097 3098 if (Invalid) 3099 break; 3100 3101 continue; 3102 } 3103 3104 QualType T 3105 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 3106 New->getLocation(), New->getDeclName()); 3107 if (T.isNull() || 3108 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 3109 continue; 3110 3111 Exceptions.push_back(T); 3112 } 3113 Expr *NoexceptExpr = 0; 3114 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) { 3115 EnterExpressionEvaluationContext Unevaluated(SemaRef, 3116 Sema::ConstantEvaluated); 3117 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs); 3118 if (E.isUsable()) 3119 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart()); 3120 3121 if (E.isUsable()) { 3122 NoexceptExpr = E.take(); 3123 if (!NoexceptExpr->isTypeDependent() && 3124 !NoexceptExpr->isValueDependent()) 3125 NoexceptExpr 3126 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr, 3127 0, diag::err_noexcept_needs_constant_expression, 3128 /*AllowFold*/ false).take(); 3129 } 3130 } 3131 3132 // Rebuild the function type 3133 const FunctionProtoType *NewProto 3134 = New->getType()->getAs<FunctionProtoType>(); 3135 assert(NewProto && "Template instantiation without function prototype?"); 3136 3137 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo(); 3138 EPI.ExceptionSpecType = Proto->getExceptionSpecType(); 3139 EPI.NumExceptions = Exceptions.size(); 3140 EPI.Exceptions = Exceptions.data(); 3141 EPI.NoexceptExpr = NoexceptExpr; 3142 3143 New->setType(SemaRef.Context.getFunctionType(NewProto->getReturnType(), 3144 NewProto->getParamTypes(), EPI)); 3145 } 3146 3147 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 3148 FunctionDecl *Decl) { 3149 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 3150 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 3151 return; 3152 3153 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 3154 InstantiatingTemplate::ExceptionSpecification()); 3155 if (Inst.isInvalid()) { 3156 // We hit the instantiation depth limit. Clear the exception specification 3157 // so that our callers don't have to cope with EST_Uninstantiated. 3158 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3159 EPI.ExceptionSpecType = EST_None; 3160 Decl->setType(Context.getFunctionType(Proto->getReturnType(), 3161 Proto->getParamTypes(), EPI)); 3162 return; 3163 } 3164 3165 // Enter the scope of this instantiation. We don't use 3166 // PushDeclContext because we don't have a scope. 3167 Sema::ContextRAII savedContext(*this, Decl); 3168 LocalInstantiationScope Scope(*this); 3169 3170 MultiLevelTemplateArgumentList TemplateArgs = 3171 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true); 3172 3173 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3174 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs); 3175 3176 ::InstantiateExceptionSpec(*this, Decl, 3177 Template->getType()->castAs<FunctionProtoType>(), 3178 TemplateArgs); 3179 } 3180 3181 /// \brief Initializes the common fields of an instantiation function 3182 /// declaration (New) from the corresponding fields of its template (Tmpl). 3183 /// 3184 /// \returns true if there was an error 3185 bool 3186 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3187 FunctionDecl *Tmpl) { 3188 if (Tmpl->isDeleted()) 3189 New->setDeletedAsWritten(); 3190 3191 // Forward the mangling number from the template to the instantiated decl. 3192 SemaRef.Context.setManglingNumber(New, 3193 SemaRef.Context.getManglingNumber(Tmpl)); 3194 3195 // If we are performing substituting explicitly-specified template arguments 3196 // or deduced template arguments into a function template and we reach this 3197 // point, we are now past the point where SFINAE applies and have committed 3198 // to keeping the new function template specialization. We therefore 3199 // convert the active template instantiation for the function template 3200 // into a template instantiation for this specific function template 3201 // specialization, which is not a SFINAE context, so that we diagnose any 3202 // further errors in the declaration itself. 3203 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 3204 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 3205 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3206 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3207 if (FunctionTemplateDecl *FunTmpl 3208 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3209 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3210 "Deduction from the wrong function template?"); 3211 (void) FunTmpl; 3212 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3213 ActiveInst.Entity = New; 3214 } 3215 } 3216 3217 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3218 assert(Proto && "Function template without prototype?"); 3219 3220 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3221 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3222 3223 // DR1330: In C++11, defer instantiation of a non-trivial 3224 // exception specification. 3225 if (SemaRef.getLangOpts().CPlusPlus11 && 3226 EPI.ExceptionSpecType != EST_None && 3227 EPI.ExceptionSpecType != EST_DynamicNone && 3228 EPI.ExceptionSpecType != EST_BasicNoexcept) { 3229 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3230 if (EPI.ExceptionSpecType == EST_Uninstantiated) 3231 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate; 3232 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3233 if (EPI.ExceptionSpecType == EST_Unevaluated) 3234 NewEST = EST_Unevaluated; 3235 3236 // Mark the function has having an uninstantiated exception specification. 3237 const FunctionProtoType *NewProto 3238 = New->getType()->getAs<FunctionProtoType>(); 3239 assert(NewProto && "Template instantiation without function prototype?"); 3240 EPI = NewProto->getExtProtoInfo(); 3241 EPI.ExceptionSpecType = NewEST; 3242 EPI.ExceptionSpecDecl = New; 3243 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate; 3244 New->setType(SemaRef.Context.getFunctionType( 3245 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 3246 } else { 3247 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs); 3248 } 3249 } 3250 3251 // Get the definition. Leaves the variable unchanged if undefined. 3252 const FunctionDecl *Definition = Tmpl; 3253 Tmpl->isDefined(Definition); 3254 3255 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 3256 LateAttrs, StartingScope); 3257 3258 return false; 3259 } 3260 3261 /// \brief Initializes common fields of an instantiated method 3262 /// declaration (New) from the corresponding fields of its template 3263 /// (Tmpl). 3264 /// 3265 /// \returns true if there was an error 3266 bool 3267 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 3268 CXXMethodDecl *Tmpl) { 3269 if (InitFunctionInstantiation(New, Tmpl)) 3270 return true; 3271 3272 New->setAccess(Tmpl->getAccess()); 3273 if (Tmpl->isVirtualAsWritten()) 3274 New->setVirtualAsWritten(true); 3275 3276 // FIXME: New needs a pointer to Tmpl 3277 return false; 3278 } 3279 3280 /// \brief Instantiate the definition of the given function from its 3281 /// template. 3282 /// 3283 /// \param PointOfInstantiation the point at which the instantiation was 3284 /// required. Note that this is not precisely a "point of instantiation" 3285 /// for the function, but it's close. 3286 /// 3287 /// \param Function the already-instantiated declaration of a 3288 /// function template specialization or member function of a class template 3289 /// specialization. 3290 /// 3291 /// \param Recursive if true, recursively instantiates any functions that 3292 /// are required by this instantiation. 3293 /// 3294 /// \param DefinitionRequired if true, then we are performing an explicit 3295 /// instantiation where the body of the function is required. Complain if 3296 /// there is no such body. 3297 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 3298 FunctionDecl *Function, 3299 bool Recursive, 3300 bool DefinitionRequired) { 3301 if (Function->isInvalidDecl() || Function->isDefined()) 3302 return; 3303 3304 // Never instantiate an explicit specialization except if it is a class scope 3305 // explicit specialization. 3306 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3307 !Function->getClassScopeSpecializationPattern()) 3308 return; 3309 3310 // Find the function body that we'll be substituting. 3311 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 3312 assert(PatternDecl && "instantiating a non-template"); 3313 3314 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 3315 assert(PatternDecl && "template definition is not a template"); 3316 if (!Pattern) { 3317 // Try to find a defaulted definition 3318 PatternDecl->isDefined(PatternDecl); 3319 } 3320 assert(PatternDecl && "template definition is not a template"); 3321 3322 // Postpone late parsed template instantiations. 3323 if (PatternDecl->isLateTemplateParsed() && 3324 !LateTemplateParser) { 3325 PendingInstantiations.push_back( 3326 std::make_pair(Function, PointOfInstantiation)); 3327 return; 3328 } 3329 3330 // Call the LateTemplateParser callback if there is a need to late parse 3331 // a templated function definition. 3332 if (!Pattern && PatternDecl->isLateTemplateParsed() && 3333 LateTemplateParser) { 3334 // FIXME: Optimize to allow individual templates to be deserialized. 3335 if (PatternDecl->isFromASTFile()) 3336 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 3337 3338 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl); 3339 assert(LPT && "missing LateParsedTemplate"); 3340 LateTemplateParser(OpaqueParser, *LPT); 3341 Pattern = PatternDecl->getBody(PatternDecl); 3342 } 3343 3344 if (!Pattern && !PatternDecl->isDefaulted()) { 3345 if (DefinitionRequired) { 3346 if (Function->getPrimaryTemplate()) 3347 Diag(PointOfInstantiation, 3348 diag::err_explicit_instantiation_undefined_func_template) 3349 << Function->getPrimaryTemplate(); 3350 else 3351 Diag(PointOfInstantiation, 3352 diag::err_explicit_instantiation_undefined_member) 3353 << 1 << Function->getDeclName() << Function->getDeclContext(); 3354 3355 if (PatternDecl) 3356 Diag(PatternDecl->getLocation(), 3357 diag::note_explicit_instantiation_here); 3358 Function->setInvalidDecl(); 3359 } else if (Function->getTemplateSpecializationKind() 3360 == TSK_ExplicitInstantiationDefinition) { 3361 PendingInstantiations.push_back( 3362 std::make_pair(Function, PointOfInstantiation)); 3363 } 3364 3365 return; 3366 } 3367 3368 // C++1y [temp.explicit]p10: 3369 // Except for inline functions, declarations with types deduced from their 3370 // initializer or return value, and class template specializations, other 3371 // explicit instantiation declarations have the effect of suppressing the 3372 // implicit instantiation of the entity to which they refer. 3373 if (Function->getTemplateSpecializationKind() == 3374 TSK_ExplicitInstantiationDeclaration && 3375 !PatternDecl->isInlined() && 3376 !PatternDecl->getReturnType()->getContainedAutoType()) 3377 return; 3378 3379 if (PatternDecl->isInlined()) 3380 Function->setImplicitlyInline(); 3381 3382 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 3383 if (Inst.isInvalid()) 3384 return; 3385 3386 // Copy the inner loc start from the pattern. 3387 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 3388 3389 // If we're performing recursive template instantiation, create our own 3390 // queue of pending implicit instantiations that we will instantiate later, 3391 // while we're still within our own instantiation context. 3392 SmallVector<VTableUse, 16> SavedVTableUses; 3393 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3394 SavePendingLocalImplicitInstantiationsRAII 3395 SavedPendingLocalImplicitInstantiations(*this); 3396 if (Recursive) { 3397 VTableUses.swap(SavedVTableUses); 3398 PendingInstantiations.swap(SavedPendingInstantiations); 3399 } 3400 3401 EnterExpressionEvaluationContext EvalContext(*this, 3402 Sema::PotentiallyEvaluated); 3403 3404 // Introduce a new scope where local variable instantiations will be 3405 // recorded, unless we're actually a member function within a local 3406 // class, in which case we need to merge our results with the parent 3407 // scope (of the enclosing function). 3408 bool MergeWithParentScope = false; 3409 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 3410 MergeWithParentScope = Rec->isLocalClass(); 3411 3412 LocalInstantiationScope Scope(*this, MergeWithParentScope); 3413 3414 if (PatternDecl->isDefaulted()) 3415 SetDeclDefaulted(Function, PatternDecl->getLocation()); 3416 else { 3417 ActOnStartOfFunctionDef(0, Function); 3418 3419 // Enter the scope of this instantiation. We don't use 3420 // PushDeclContext because we don't have a scope. 3421 Sema::ContextRAII savedContext(*this, Function); 3422 3423 MultiLevelTemplateArgumentList TemplateArgs = 3424 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 3425 3426 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 3427 TemplateArgs); 3428 3429 // If this is a constructor, instantiate the member initializers. 3430 if (const CXXConstructorDecl *Ctor = 3431 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 3432 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 3433 TemplateArgs); 3434 } 3435 3436 // Instantiate the function body. 3437 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 3438 3439 if (Body.isInvalid()) 3440 Function->setInvalidDecl(); 3441 3442 ActOnFinishFunctionBody(Function, Body.get(), 3443 /*IsInstantiation=*/true); 3444 3445 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 3446 3447 savedContext.pop(); 3448 } 3449 3450 DeclGroupRef DG(Function); 3451 Consumer.HandleTopLevelDecl(DG); 3452 3453 // This class may have local implicit instantiations that need to be 3454 // instantiation within this scope. 3455 PerformPendingInstantiations(/*LocalOnly=*/true); 3456 Scope.Exit(); 3457 3458 if (Recursive) { 3459 // Define any pending vtables. 3460 DefineUsedVTables(); 3461 3462 // Instantiate any pending implicit instantiations found during the 3463 // instantiation of this template. 3464 PerformPendingInstantiations(); 3465 3466 // Restore the set of pending vtables. 3467 assert(VTableUses.empty() && 3468 "VTableUses should be empty before it is discarded."); 3469 VTableUses.swap(SavedVTableUses); 3470 3471 // Restore the set of pending implicit instantiations. 3472 assert(PendingInstantiations.empty() && 3473 "PendingInstantiations should be empty before it is discarded."); 3474 PendingInstantiations.swap(SavedPendingInstantiations); 3475 } 3476 } 3477 3478 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 3479 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 3480 const TemplateArgumentList &TemplateArgList, 3481 const TemplateArgumentListInfo &TemplateArgsInfo, 3482 SmallVectorImpl<TemplateArgument> &Converted, 3483 SourceLocation PointOfInstantiation, void *InsertPos, 3484 LateInstantiatedAttrVec *LateAttrs, 3485 LocalInstantiationScope *StartingScope) { 3486 if (FromVar->isInvalidDecl()) 3487 return 0; 3488 3489 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 3490 if (Inst.isInvalid()) 3491 return 0; 3492 3493 MultiLevelTemplateArgumentList TemplateArgLists; 3494 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 3495 3496 // Instantiate the first declaration of the variable template: for a partial 3497 // specialization of a static data member template, the first declaration may 3498 // or may not be the declaration in the class; if it's in the class, we want 3499 // to instantiate a member in the class (a declaration), and if it's outside, 3500 // we want to instantiate a definition. 3501 // 3502 // If we're instantiating an explicitly-specialized member template or member 3503 // partial specialization, don't do this. The member specialization completely 3504 // replaces the original declaration in this case. 3505 bool IsMemberSpec = false; 3506 if (VarTemplatePartialSpecializationDecl *PartialSpec = 3507 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 3508 IsMemberSpec = PartialSpec->isMemberSpecialization(); 3509 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 3510 IsMemberSpec = FromTemplate->isMemberSpecialization(); 3511 if (!IsMemberSpec) 3512 FromVar = FromVar->getFirstDecl(); 3513 3514 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 3515 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 3516 MultiLevelList); 3517 3518 // TODO: Set LateAttrs and StartingScope ... 3519 3520 return cast_or_null<VarTemplateSpecializationDecl>( 3521 Instantiator.VisitVarTemplateSpecializationDecl( 3522 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 3523 } 3524 3525 /// \brief Instantiates a variable template specialization by completing it 3526 /// with appropriate type information and initializer. 3527 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 3528 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 3529 const MultiLevelTemplateArgumentList &TemplateArgs) { 3530 3531 // Do substitution on the type of the declaration 3532 TypeSourceInfo *DI = 3533 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 3534 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 3535 if (!DI) 3536 return 0; 3537 3538 // Update the type of this variable template specialization. 3539 VarSpec->setType(DI->getType()); 3540 3541 // Instantiate the initializer. 3542 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 3543 3544 return VarSpec; 3545 } 3546 3547 /// BuildVariableInstantiation - Used after a new variable has been created. 3548 /// Sets basic variable data and decides whether to postpone the 3549 /// variable instantiation. 3550 void Sema::BuildVariableInstantiation( 3551 VarDecl *NewVar, VarDecl *OldVar, 3552 const MultiLevelTemplateArgumentList &TemplateArgs, 3553 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 3554 LocalInstantiationScope *StartingScope, 3555 bool InstantiatingVarTemplate) { 3556 3557 // If we are instantiating a local extern declaration, the 3558 // instantiation belongs lexically to the containing function. 3559 // If we are instantiating a static data member defined 3560 // out-of-line, the instantiation will have the same lexical 3561 // context (which will be a namespace scope) as the template. 3562 if (OldVar->isLocalExternDecl()) { 3563 NewVar->setLocalExternDecl(); 3564 NewVar->setLexicalDeclContext(Owner); 3565 } else if (OldVar->isOutOfLine()) 3566 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 3567 NewVar->setTSCSpec(OldVar->getTSCSpec()); 3568 NewVar->setInitStyle(OldVar->getInitStyle()); 3569 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 3570 NewVar->setConstexpr(OldVar->isConstexpr()); 3571 NewVar->setInitCapture(OldVar->isInitCapture()); 3572 NewVar->setPreviousDeclInSameBlockScope( 3573 OldVar->isPreviousDeclInSameBlockScope()); 3574 NewVar->setAccess(OldVar->getAccess()); 3575 3576 if (!OldVar->isStaticDataMember()) { 3577 if (OldVar->isUsed(false)) 3578 NewVar->setIsUsed(); 3579 NewVar->setReferenced(OldVar->isReferenced()); 3580 } 3581 3582 // See if the old variable had a type-specifier that defined an anonymous tag. 3583 // If it did, mark the new variable as being the declarator for the new 3584 // anonymous tag. 3585 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) { 3586 TagDecl *OldTag = OldTagType->getDecl(); 3587 if (OldTag->getDeclaratorForAnonDecl() == OldVar) { 3588 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl(); 3589 assert(!NewTag->hasNameForLinkage() && 3590 !NewTag->hasDeclaratorForAnonDecl()); 3591 NewTag->setDeclaratorForAnonDecl(NewVar); 3592 } 3593 } 3594 3595 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 3596 3597 if (NewVar->hasAttrs()) 3598 CheckAlignasUnderalignment(NewVar); 3599 3600 LookupResult Previous( 3601 *this, NewVar->getDeclName(), NewVar->getLocation(), 3602 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 3603 : Sema::LookupOrdinaryName, 3604 Sema::ForRedeclaration); 3605 3606 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 3607 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 3608 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 3609 // We have a previous declaration. Use that one, so we merge with the 3610 // right type. 3611 if (NamedDecl *NewPrev = FindInstantiatedDecl( 3612 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 3613 Previous.addDecl(NewPrev); 3614 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 3615 OldVar->hasLinkage()) 3616 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 3617 CheckVariableDeclaration(NewVar, Previous); 3618 3619 if (!InstantiatingVarTemplate) { 3620 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 3621 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 3622 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 3623 } 3624 3625 if (!OldVar->isOutOfLine()) { 3626 if (NewVar->getDeclContext()->isFunctionOrMethod()) 3627 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 3628 } 3629 3630 // Link instantiations of static data members back to the template from 3631 // which they were instantiated. 3632 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate) 3633 NewVar->setInstantiationOfStaticDataMember(OldVar, 3634 TSK_ImplicitInstantiation); 3635 3636 // Forward the mangling number from the template to the instantiated decl. 3637 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 3638 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 3639 3640 // Delay instantiation of the initializer for variable templates until a 3641 // definition of the variable is needed. 3642 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate) 3643 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 3644 3645 // Diagnose unused local variables with dependent types, where the diagnostic 3646 // will have been deferred. 3647 if (!NewVar->isInvalidDecl() && 3648 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() && 3649 OldVar->getType()->isDependentType()) 3650 DiagnoseUnusedDecl(NewVar); 3651 } 3652 3653 /// \brief Instantiate the initializer of a variable. 3654 void Sema::InstantiateVariableInitializer( 3655 VarDecl *Var, VarDecl *OldVar, 3656 const MultiLevelTemplateArgumentList &TemplateArgs) { 3657 3658 if (Var->getAnyInitializer()) 3659 // We already have an initializer in the class. 3660 return; 3661 3662 if (OldVar->getInit()) { 3663 if (Var->isStaticDataMember() && !OldVar->isOutOfLine()) 3664 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar); 3665 else 3666 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar); 3667 3668 // Instantiate the initializer. 3669 ExprResult Init = 3670 SubstInitializer(OldVar->getInit(), TemplateArgs, 3671 OldVar->getInitStyle() == VarDecl::CallInit); 3672 if (!Init.isInvalid()) { 3673 bool TypeMayContainAuto = true; 3674 if (Init.get()) { 3675 bool DirectInit = OldVar->isDirectInit(); 3676 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto); 3677 } else 3678 ActOnUninitializedDecl(Var, TypeMayContainAuto); 3679 } else { 3680 // FIXME: Not too happy about invalidating the declaration 3681 // because of a bogus initializer. 3682 Var->setInvalidDecl(); 3683 } 3684 3685 PopExpressionEvaluationContext(); 3686 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 3687 !Var->isCXXForRangeDecl()) 3688 ActOnUninitializedDecl(Var, false); 3689 } 3690 3691 /// \brief Instantiate the definition of the given variable from its 3692 /// template. 3693 /// 3694 /// \param PointOfInstantiation the point at which the instantiation was 3695 /// required. Note that this is not precisely a "point of instantiation" 3696 /// for the function, but it's close. 3697 /// 3698 /// \param Var the already-instantiated declaration of a static member 3699 /// variable of a class template specialization. 3700 /// 3701 /// \param Recursive if true, recursively instantiates any functions that 3702 /// are required by this instantiation. 3703 /// 3704 /// \param DefinitionRequired if true, then we are performing an explicit 3705 /// instantiation where an out-of-line definition of the member variable 3706 /// is required. Complain if there is no such definition. 3707 void Sema::InstantiateStaticDataMemberDefinition( 3708 SourceLocation PointOfInstantiation, 3709 VarDecl *Var, 3710 bool Recursive, 3711 bool DefinitionRequired) { 3712 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive, 3713 DefinitionRequired); 3714 } 3715 3716 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 3717 VarDecl *Var, bool Recursive, 3718 bool DefinitionRequired) { 3719 if (Var->isInvalidDecl()) 3720 return; 3721 3722 VarTemplateSpecializationDecl *VarSpec = 3723 dyn_cast<VarTemplateSpecializationDecl>(Var); 3724 VarDecl *PatternDecl = 0, *Def = 0; 3725 MultiLevelTemplateArgumentList TemplateArgs = 3726 getTemplateInstantiationArgs(Var); 3727 3728 if (VarSpec) { 3729 // If this is a variable template specialization, make sure that it is 3730 // non-dependent, then find its instantiation pattern. 3731 bool InstantiationDependent = false; 3732 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 3733 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 3734 "Only instantiate variable template specializations that are " 3735 "not type-dependent"); 3736 (void)InstantiationDependent; 3737 3738 // Find the variable initialization that we'll be substituting. If the 3739 // pattern was instantiated from a member template, look back further to 3740 // find the real pattern. 3741 assert(VarSpec->getSpecializedTemplate() && 3742 "Specialization without specialized template?"); 3743 llvm::PointerUnion<VarTemplateDecl *, 3744 VarTemplatePartialSpecializationDecl *> PatternPtr = 3745 VarSpec->getSpecializedTemplateOrPartial(); 3746 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) { 3747 VarTemplatePartialSpecializationDecl *Tmpl = 3748 PatternPtr.get<VarTemplatePartialSpecializationDecl *>(); 3749 while (VarTemplatePartialSpecializationDecl *From = 3750 Tmpl->getInstantiatedFromMember()) { 3751 if (Tmpl->isMemberSpecialization()) 3752 break; 3753 3754 Tmpl = From; 3755 } 3756 PatternDecl = Tmpl; 3757 } else { 3758 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>(); 3759 while (VarTemplateDecl *From = 3760 Tmpl->getInstantiatedFromMemberTemplate()) { 3761 if (Tmpl->isMemberSpecialization()) 3762 break; 3763 3764 Tmpl = From; 3765 } 3766 PatternDecl = Tmpl->getTemplatedDecl(); 3767 } 3768 3769 // If this is a static data member template, there might be an 3770 // uninstantiated initializer on the declaration. If so, instantiate 3771 // it now. 3772 if (PatternDecl->isStaticDataMember() && 3773 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 3774 !Var->hasInit()) { 3775 // FIXME: Factor out the duplicated instantiation context setup/tear down 3776 // code here. 3777 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 3778 if (Inst.isInvalid()) 3779 return; 3780 3781 // If we're performing recursive template instantiation, create our own 3782 // queue of pending implicit instantiations that we will instantiate 3783 // later, while we're still within our own instantiation context. 3784 SmallVector<VTableUse, 16> SavedVTableUses; 3785 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3786 if (Recursive) { 3787 VTableUses.swap(SavedVTableUses); 3788 PendingInstantiations.swap(SavedPendingInstantiations); 3789 } 3790 3791 LocalInstantiationScope Local(*this); 3792 3793 // Enter the scope of this instantiation. We don't use 3794 // PushDeclContext because we don't have a scope. 3795 ContextRAII PreviousContext(*this, Var->getDeclContext()); 3796 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 3797 PreviousContext.pop(); 3798 3799 // FIXME: Need to inform the ASTConsumer that we instantiated the 3800 // initializer? 3801 3802 // This variable may have local implicit instantiations that need to be 3803 // instantiated within this scope. 3804 PerformPendingInstantiations(/*LocalOnly=*/true); 3805 3806 Local.Exit(); 3807 3808 if (Recursive) { 3809 // Define any newly required vtables. 3810 DefineUsedVTables(); 3811 3812 // Instantiate any pending implicit instantiations found during the 3813 // instantiation of this template. 3814 PerformPendingInstantiations(); 3815 3816 // Restore the set of pending vtables. 3817 assert(VTableUses.empty() && 3818 "VTableUses should be empty before it is discarded."); 3819 VTableUses.swap(SavedVTableUses); 3820 3821 // Restore the set of pending implicit instantiations. 3822 assert(PendingInstantiations.empty() && 3823 "PendingInstantiations should be empty before it is discarded."); 3824 PendingInstantiations.swap(SavedPendingInstantiations); 3825 } 3826 } 3827 3828 // Find actual definition 3829 Def = PatternDecl->getDefinition(getASTContext()); 3830 } else { 3831 // If this is a static data member, find its out-of-line definition. 3832 assert(Var->isStaticDataMember() && "not a static data member?"); 3833 PatternDecl = Var->getInstantiatedFromStaticDataMember(); 3834 3835 assert(PatternDecl && "data member was not instantiated from a template?"); 3836 assert(PatternDecl->isStaticDataMember() && "not a static data member?"); 3837 Def = PatternDecl->getOutOfLineDefinition(); 3838 } 3839 3840 // If we don't have a definition of the variable template, we won't perform 3841 // any instantiation. Rather, we rely on the user to instantiate this 3842 // definition (or provide a specialization for it) in another translation 3843 // unit. 3844 if (!Def) { 3845 if (DefinitionRequired) { 3846 if (VarSpec) 3847 Diag(PointOfInstantiation, 3848 diag::err_explicit_instantiation_undefined_var_template) << Var; 3849 else 3850 Diag(PointOfInstantiation, 3851 diag::err_explicit_instantiation_undefined_member) 3852 << 2 << Var->getDeclName() << Var->getDeclContext(); 3853 Diag(PatternDecl->getLocation(), 3854 diag::note_explicit_instantiation_here); 3855 if (VarSpec) 3856 Var->setInvalidDecl(); 3857 } else if (Var->getTemplateSpecializationKind() 3858 == TSK_ExplicitInstantiationDefinition) { 3859 PendingInstantiations.push_back( 3860 std::make_pair(Var, PointOfInstantiation)); 3861 } 3862 3863 return; 3864 } 3865 3866 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 3867 3868 // Never instantiate an explicit specialization. 3869 if (TSK == TSK_ExplicitSpecialization) 3870 return; 3871 3872 // C++11 [temp.explicit]p10: 3873 // Except for inline functions, [...] explicit instantiation declarations 3874 // have the effect of suppressing the implicit instantiation of the entity 3875 // to which they refer. 3876 if (TSK == TSK_ExplicitInstantiationDeclaration) 3877 return; 3878 3879 // Make sure to pass the instantiated variable to the consumer at the end. 3880 struct PassToConsumerRAII { 3881 ASTConsumer &Consumer; 3882 VarDecl *Var; 3883 3884 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 3885 : Consumer(Consumer), Var(Var) { } 3886 3887 ~PassToConsumerRAII() { 3888 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 3889 } 3890 } PassToConsumerRAII(Consumer, Var); 3891 3892 // If we already have a definition, we're done. 3893 if (VarDecl *Def = Var->getDefinition()) { 3894 // We may be explicitly instantiating something we've already implicitly 3895 // instantiated. 3896 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 3897 PointOfInstantiation); 3898 return; 3899 } 3900 3901 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 3902 if (Inst.isInvalid()) 3903 return; 3904 3905 // If we're performing recursive template instantiation, create our own 3906 // queue of pending implicit instantiations that we will instantiate later, 3907 // while we're still within our own instantiation context. 3908 SmallVector<VTableUse, 16> SavedVTableUses; 3909 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3910 SavePendingLocalImplicitInstantiationsRAII 3911 SavedPendingLocalImplicitInstantiations(*this); 3912 if (Recursive) { 3913 VTableUses.swap(SavedVTableUses); 3914 PendingInstantiations.swap(SavedPendingInstantiations); 3915 } 3916 3917 // Enter the scope of this instantiation. We don't use 3918 // PushDeclContext because we don't have a scope. 3919 ContextRAII PreviousContext(*this, Var->getDeclContext()); 3920 LocalInstantiationScope Local(*this); 3921 3922 VarDecl *OldVar = Var; 3923 if (!VarSpec) 3924 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 3925 TemplateArgs)); 3926 else if (Var->isStaticDataMember() && 3927 Var->getLexicalDeclContext()->isRecord()) { 3928 // We need to instantiate the definition of a static data member template, 3929 // and all we have is the in-class declaration of it. Instantiate a separate 3930 // declaration of the definition. 3931 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 3932 TemplateArgs); 3933 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 3934 VarSpec->getSpecializedTemplate(), Def, 0, 3935 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 3936 if (Var) { 3937 llvm::PointerUnion<VarTemplateDecl *, 3938 VarTemplatePartialSpecializationDecl *> PatternPtr = 3939 VarSpec->getSpecializedTemplateOrPartial(); 3940 if (VarTemplatePartialSpecializationDecl *Partial = 3941 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 3942 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 3943 Partial, &VarSpec->getTemplateInstantiationArgs()); 3944 3945 // Merge the definition with the declaration. 3946 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 3947 LookupOrdinaryName, ForRedeclaration); 3948 R.addDecl(OldVar); 3949 MergeVarDecl(Var, R); 3950 3951 // Attach the initializer. 3952 InstantiateVariableInitializer(Var, Def, TemplateArgs); 3953 } 3954 } else 3955 // Complete the existing variable's definition with an appropriately 3956 // substituted type and initializer. 3957 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 3958 3959 PreviousContext.pop(); 3960 3961 if (Var) { 3962 PassToConsumerRAII.Var = Var; 3963 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 3964 OldVar->getPointOfInstantiation()); 3965 } 3966 3967 // This variable may have local implicit instantiations that need to be 3968 // instantiated within this scope. 3969 PerformPendingInstantiations(/*LocalOnly=*/true); 3970 3971 Local.Exit(); 3972 3973 if (Recursive) { 3974 // Define any newly required vtables. 3975 DefineUsedVTables(); 3976 3977 // Instantiate any pending implicit instantiations found during the 3978 // instantiation of this template. 3979 PerformPendingInstantiations(); 3980 3981 // Restore the set of pending vtables. 3982 assert(VTableUses.empty() && 3983 "VTableUses should be empty before it is discarded."); 3984 VTableUses.swap(SavedVTableUses); 3985 3986 // Restore the set of pending implicit instantiations. 3987 assert(PendingInstantiations.empty() && 3988 "PendingInstantiations should be empty before it is discarded."); 3989 PendingInstantiations.swap(SavedPendingInstantiations); 3990 } 3991 } 3992 3993 void 3994 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 3995 const CXXConstructorDecl *Tmpl, 3996 const MultiLevelTemplateArgumentList &TemplateArgs) { 3997 3998 SmallVector<CXXCtorInitializer*, 4> NewInits; 3999 bool AnyErrors = Tmpl->isInvalidDecl(); 4000 4001 // Instantiate all the initializers. 4002 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 4003 InitsEnd = Tmpl->init_end(); 4004 Inits != InitsEnd; ++Inits) { 4005 CXXCtorInitializer *Init = *Inits; 4006 4007 // Only instantiate written initializers, let Sema re-construct implicit 4008 // ones. 4009 if (!Init->isWritten()) 4010 continue; 4011 4012 SourceLocation EllipsisLoc; 4013 4014 if (Init->isPackExpansion()) { 4015 // This is a pack expansion. We should expand it now. 4016 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 4017 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 4018 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 4019 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 4020 bool ShouldExpand = false; 4021 bool RetainExpansion = false; 4022 Optional<unsigned> NumExpansions; 4023 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 4024 BaseTL.getSourceRange(), 4025 Unexpanded, 4026 TemplateArgs, ShouldExpand, 4027 RetainExpansion, 4028 NumExpansions)) { 4029 AnyErrors = true; 4030 New->setInvalidDecl(); 4031 continue; 4032 } 4033 assert(ShouldExpand && "Partial instantiation of base initializer?"); 4034 4035 // Loop over all of the arguments in the argument pack(s), 4036 for (unsigned I = 0; I != *NumExpansions; ++I) { 4037 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 4038 4039 // Instantiate the initializer. 4040 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4041 /*CXXDirectInit=*/true); 4042 if (TempInit.isInvalid()) { 4043 AnyErrors = true; 4044 break; 4045 } 4046 4047 // Instantiate the base type. 4048 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 4049 TemplateArgs, 4050 Init->getSourceLocation(), 4051 New->getDeclName()); 4052 if (!BaseTInfo) { 4053 AnyErrors = true; 4054 break; 4055 } 4056 4057 // Build the initializer. 4058 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 4059 BaseTInfo, TempInit.take(), 4060 New->getParent(), 4061 SourceLocation()); 4062 if (NewInit.isInvalid()) { 4063 AnyErrors = true; 4064 break; 4065 } 4066 4067 NewInits.push_back(NewInit.get()); 4068 } 4069 4070 continue; 4071 } 4072 4073 // Instantiate the initializer. 4074 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4075 /*CXXDirectInit=*/true); 4076 if (TempInit.isInvalid()) { 4077 AnyErrors = true; 4078 continue; 4079 } 4080 4081 MemInitResult NewInit; 4082 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 4083 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 4084 TemplateArgs, 4085 Init->getSourceLocation(), 4086 New->getDeclName()); 4087 if (!TInfo) { 4088 AnyErrors = true; 4089 New->setInvalidDecl(); 4090 continue; 4091 } 4092 4093 if (Init->isBaseInitializer()) 4094 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(), 4095 New->getParent(), EllipsisLoc); 4096 else 4097 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(), 4098 cast<CXXRecordDecl>(CurContext->getParent())); 4099 } else if (Init->isMemberInitializer()) { 4100 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 4101 Init->getMemberLocation(), 4102 Init->getMember(), 4103 TemplateArgs)); 4104 if (!Member) { 4105 AnyErrors = true; 4106 New->setInvalidDecl(); 4107 continue; 4108 } 4109 4110 NewInit = BuildMemberInitializer(Member, TempInit.take(), 4111 Init->getSourceLocation()); 4112 } else if (Init->isIndirectMemberInitializer()) { 4113 IndirectFieldDecl *IndirectMember = 4114 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 4115 Init->getMemberLocation(), 4116 Init->getIndirectMember(), TemplateArgs)); 4117 4118 if (!IndirectMember) { 4119 AnyErrors = true; 4120 New->setInvalidDecl(); 4121 continue; 4122 } 4123 4124 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(), 4125 Init->getSourceLocation()); 4126 } 4127 4128 if (NewInit.isInvalid()) { 4129 AnyErrors = true; 4130 New->setInvalidDecl(); 4131 } else { 4132 NewInits.push_back(NewInit.get()); 4133 } 4134 } 4135 4136 // Assign all the initializers to the new constructor. 4137 ActOnMemInitializers(New, 4138 /*FIXME: ColonLoc */ 4139 SourceLocation(), 4140 NewInits, 4141 AnyErrors); 4142 } 4143 4144 // TODO: this could be templated if the various decl types used the 4145 // same method name. 4146 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 4147 ClassTemplateDecl *Instance) { 4148 Pattern = Pattern->getCanonicalDecl(); 4149 4150 do { 4151 Instance = Instance->getCanonicalDecl(); 4152 if (Pattern == Instance) return true; 4153 Instance = Instance->getInstantiatedFromMemberTemplate(); 4154 } while (Instance); 4155 4156 return false; 4157 } 4158 4159 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 4160 FunctionTemplateDecl *Instance) { 4161 Pattern = Pattern->getCanonicalDecl(); 4162 4163 do { 4164 Instance = Instance->getCanonicalDecl(); 4165 if (Pattern == Instance) return true; 4166 Instance = Instance->getInstantiatedFromMemberTemplate(); 4167 } while (Instance); 4168 4169 return false; 4170 } 4171 4172 static bool 4173 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 4174 ClassTemplatePartialSpecializationDecl *Instance) { 4175 Pattern 4176 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 4177 do { 4178 Instance = cast<ClassTemplatePartialSpecializationDecl>( 4179 Instance->getCanonicalDecl()); 4180 if (Pattern == Instance) 4181 return true; 4182 Instance = Instance->getInstantiatedFromMember(); 4183 } while (Instance); 4184 4185 return false; 4186 } 4187 4188 static bool isInstantiationOf(CXXRecordDecl *Pattern, 4189 CXXRecordDecl *Instance) { 4190 Pattern = Pattern->getCanonicalDecl(); 4191 4192 do { 4193 Instance = Instance->getCanonicalDecl(); 4194 if (Pattern == Instance) return true; 4195 Instance = Instance->getInstantiatedFromMemberClass(); 4196 } while (Instance); 4197 4198 return false; 4199 } 4200 4201 static bool isInstantiationOf(FunctionDecl *Pattern, 4202 FunctionDecl *Instance) { 4203 Pattern = Pattern->getCanonicalDecl(); 4204 4205 do { 4206 Instance = Instance->getCanonicalDecl(); 4207 if (Pattern == Instance) return true; 4208 Instance = Instance->getInstantiatedFromMemberFunction(); 4209 } while (Instance); 4210 4211 return false; 4212 } 4213 4214 static bool isInstantiationOf(EnumDecl *Pattern, 4215 EnumDecl *Instance) { 4216 Pattern = Pattern->getCanonicalDecl(); 4217 4218 do { 4219 Instance = Instance->getCanonicalDecl(); 4220 if (Pattern == Instance) return true; 4221 Instance = Instance->getInstantiatedFromMemberEnum(); 4222 } while (Instance); 4223 4224 return false; 4225 } 4226 4227 static bool isInstantiationOf(UsingShadowDecl *Pattern, 4228 UsingShadowDecl *Instance, 4229 ASTContext &C) { 4230 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 4231 } 4232 4233 static bool isInstantiationOf(UsingDecl *Pattern, 4234 UsingDecl *Instance, 4235 ASTContext &C) { 4236 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4237 } 4238 4239 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 4240 UsingDecl *Instance, 4241 ASTContext &C) { 4242 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4243 } 4244 4245 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 4246 UsingDecl *Instance, 4247 ASTContext &C) { 4248 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4249 } 4250 4251 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 4252 VarDecl *Instance) { 4253 assert(Instance->isStaticDataMember()); 4254 4255 Pattern = Pattern->getCanonicalDecl(); 4256 4257 do { 4258 Instance = Instance->getCanonicalDecl(); 4259 if (Pattern == Instance) return true; 4260 Instance = Instance->getInstantiatedFromStaticDataMember(); 4261 } while (Instance); 4262 4263 return false; 4264 } 4265 4266 // Other is the prospective instantiation 4267 // D is the prospective pattern 4268 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 4269 if (D->getKind() != Other->getKind()) { 4270 if (UnresolvedUsingTypenameDecl *UUD 4271 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4272 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4273 return isInstantiationOf(UUD, UD, Ctx); 4274 } 4275 } 4276 4277 if (UnresolvedUsingValueDecl *UUD 4278 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4279 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4280 return isInstantiationOf(UUD, UD, Ctx); 4281 } 4282 } 4283 4284 return false; 4285 } 4286 4287 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 4288 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 4289 4290 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 4291 return isInstantiationOf(cast<FunctionDecl>(D), Function); 4292 4293 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 4294 return isInstantiationOf(cast<EnumDecl>(D), Enum); 4295 4296 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 4297 if (Var->isStaticDataMember()) 4298 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 4299 4300 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 4301 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 4302 4303 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 4304 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 4305 4306 if (ClassTemplatePartialSpecializationDecl *PartialSpec 4307 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 4308 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 4309 PartialSpec); 4310 4311 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 4312 if (!Field->getDeclName()) { 4313 // This is an unnamed field. 4314 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 4315 cast<FieldDecl>(D); 4316 } 4317 } 4318 4319 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 4320 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 4321 4322 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 4323 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 4324 4325 return D->getDeclName() && isa<NamedDecl>(Other) && 4326 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 4327 } 4328 4329 template<typename ForwardIterator> 4330 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 4331 NamedDecl *D, 4332 ForwardIterator first, 4333 ForwardIterator last) { 4334 for (; first != last; ++first) 4335 if (isInstantiationOf(Ctx, D, *first)) 4336 return cast<NamedDecl>(*first); 4337 4338 return 0; 4339 } 4340 4341 /// \brief Finds the instantiation of the given declaration context 4342 /// within the current instantiation. 4343 /// 4344 /// \returns NULL if there was an error 4345 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 4346 const MultiLevelTemplateArgumentList &TemplateArgs) { 4347 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 4348 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 4349 return cast_or_null<DeclContext>(ID); 4350 } else return DC; 4351 } 4352 4353 /// \brief Find the instantiation of the given declaration within the 4354 /// current instantiation. 4355 /// 4356 /// This routine is intended to be used when \p D is a declaration 4357 /// referenced from within a template, that needs to mapped into the 4358 /// corresponding declaration within an instantiation. For example, 4359 /// given: 4360 /// 4361 /// \code 4362 /// template<typename T> 4363 /// struct X { 4364 /// enum Kind { 4365 /// KnownValue = sizeof(T) 4366 /// }; 4367 /// 4368 /// bool getKind() const { return KnownValue; } 4369 /// }; 4370 /// 4371 /// template struct X<int>; 4372 /// \endcode 4373 /// 4374 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 4375 /// \p EnumConstantDecl for \p KnownValue (which refers to 4376 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 4377 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 4378 /// this mapping from within the instantiation of <tt>X<int></tt>. 4379 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 4380 const MultiLevelTemplateArgumentList &TemplateArgs) { 4381 DeclContext *ParentDC = D->getDeclContext(); 4382 // FIXME: Parmeters of pointer to functions (y below) that are themselves 4383 // parameters (p below) can have their ParentDC set to the translation-unit 4384 // - thus we can not consistently check if the ParentDC of such a parameter 4385 // is Dependent or/and a FunctionOrMethod. 4386 // For e.g. this code, during Template argument deduction tries to 4387 // find an instantiated decl for (T y) when the ParentDC for y is 4388 // the translation unit. 4389 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 4390 // float baz(float(*)()) { return 0.0; } 4391 // Foo(baz); 4392 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 4393 // it gets here, always has a FunctionOrMethod as its ParentDC?? 4394 // For now: 4395 // - as long as we have a ParmVarDecl whose parent is non-dependent and 4396 // whose type is not instantiation dependent, do nothing to the decl 4397 // - otherwise find its instantiated decl. 4398 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 4399 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 4400 return D; 4401 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 4402 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 4403 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 4404 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 4405 // D is a local of some kind. Look into the map of local 4406 // declarations to their instantiations. 4407 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 4408 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 4409 = CurrentInstantiationScope->findInstantiationOf(D); 4410 4411 if (Found) { 4412 if (Decl *FD = Found->dyn_cast<Decl *>()) 4413 return cast<NamedDecl>(FD); 4414 4415 int PackIdx = ArgumentPackSubstitutionIndex; 4416 assert(PackIdx != -1 && "found declaration pack but not pack expanding"); 4417 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 4418 } 4419 4420 // If we're performing a partial substitution during template argument 4421 // deduction, we may not have values for template parameters yet. They 4422 // just map to themselves. 4423 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 4424 isa<TemplateTemplateParmDecl>(D)) 4425 return D; 4426 4427 if (D->isInvalidDecl()) 4428 return 0; 4429 4430 // If we didn't find the decl, then we must have a label decl that hasn't 4431 // been found yet. Lazily instantiate it and return it now. 4432 assert(isa<LabelDecl>(D)); 4433 4434 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 4435 assert(Inst && "Failed to instantiate label??"); 4436 4437 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 4438 return cast<LabelDecl>(Inst); 4439 } 4440 4441 // For variable template specializations, update those that are still 4442 // type-dependent. 4443 if (VarTemplateSpecializationDecl *VarSpec = 4444 dyn_cast<VarTemplateSpecializationDecl>(D)) { 4445 bool InstantiationDependent = false; 4446 const TemplateArgumentListInfo &VarTemplateArgs = 4447 VarSpec->getTemplateArgsInfo(); 4448 if (TemplateSpecializationType::anyDependentTemplateArguments( 4449 VarTemplateArgs, InstantiationDependent)) 4450 D = cast<NamedDecl>( 4451 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 4452 return D; 4453 } 4454 4455 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 4456 if (!Record->isDependentContext()) 4457 return D; 4458 4459 // Determine whether this record is the "templated" declaration describing 4460 // a class template or class template partial specialization. 4461 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 4462 if (ClassTemplate) 4463 ClassTemplate = ClassTemplate->getCanonicalDecl(); 4464 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4465 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 4466 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 4467 4468 // Walk the current context to find either the record or an instantiation of 4469 // it. 4470 DeclContext *DC = CurContext; 4471 while (!DC->isFileContext()) { 4472 // If we're performing substitution while we're inside the template 4473 // definition, we'll find our own context. We're done. 4474 if (DC->Equals(Record)) 4475 return Record; 4476 4477 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 4478 // Check whether we're in the process of instantiating a class template 4479 // specialization of the template we're mapping. 4480 if (ClassTemplateSpecializationDecl *InstSpec 4481 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 4482 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 4483 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 4484 return InstRecord; 4485 } 4486 4487 // Check whether we're in the process of instantiating a member class. 4488 if (isInstantiationOf(Record, InstRecord)) 4489 return InstRecord; 4490 } 4491 4492 // Move to the outer template scope. 4493 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 4494 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 4495 DC = FD->getLexicalDeclContext(); 4496 continue; 4497 } 4498 } 4499 4500 DC = DC->getParent(); 4501 } 4502 4503 // Fall through to deal with other dependent record types (e.g., 4504 // anonymous unions in class templates). 4505 } 4506 4507 if (!ParentDC->isDependentContext()) 4508 return D; 4509 4510 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 4511 if (!ParentDC) 4512 return 0; 4513 4514 if (ParentDC != D->getDeclContext()) { 4515 // We performed some kind of instantiation in the parent context, 4516 // so now we need to look into the instantiated parent context to 4517 // find the instantiation of the declaration D. 4518 4519 // If our context used to be dependent, we may need to instantiate 4520 // it before performing lookup into that context. 4521 bool IsBeingInstantiated = false; 4522 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 4523 if (!Spec->isDependentContext()) { 4524 QualType T = Context.getTypeDeclType(Spec); 4525 const RecordType *Tag = T->getAs<RecordType>(); 4526 assert(Tag && "type of non-dependent record is not a RecordType"); 4527 if (Tag->isBeingDefined()) 4528 IsBeingInstantiated = true; 4529 if (!Tag->isBeingDefined() && 4530 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 4531 return 0; 4532 4533 ParentDC = Tag->getDecl(); 4534 } 4535 } 4536 4537 NamedDecl *Result = 0; 4538 if (D->getDeclName()) { 4539 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 4540 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 4541 } else { 4542 // Since we don't have a name for the entity we're looking for, 4543 // our only option is to walk through all of the declarations to 4544 // find that name. This will occur in a few cases: 4545 // 4546 // - anonymous struct/union within a template 4547 // - unnamed class/struct/union/enum within a template 4548 // 4549 // FIXME: Find a better way to find these instantiations! 4550 Result = findInstantiationOf(Context, D, 4551 ParentDC->decls_begin(), 4552 ParentDC->decls_end()); 4553 } 4554 4555 if (!Result) { 4556 if (isa<UsingShadowDecl>(D)) { 4557 // UsingShadowDecls can instantiate to nothing because of using hiding. 4558 } else if (Diags.hasErrorOccurred()) { 4559 // We've already complained about something, so most likely this 4560 // declaration failed to instantiate. There's no point in complaining 4561 // further, since this is normal in invalid code. 4562 } else if (IsBeingInstantiated) { 4563 // The class in which this member exists is currently being 4564 // instantiated, and we haven't gotten around to instantiating this 4565 // member yet. This can happen when the code uses forward declarations 4566 // of member classes, and introduces ordering dependencies via 4567 // template instantiation. 4568 Diag(Loc, diag::err_member_not_yet_instantiated) 4569 << D->getDeclName() 4570 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 4571 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 4572 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 4573 // This enumeration constant was found when the template was defined, 4574 // but can't be found in the instantiation. This can happen if an 4575 // unscoped enumeration member is explicitly specialized. 4576 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 4577 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 4578 TemplateArgs)); 4579 assert(Spec->getTemplateSpecializationKind() == 4580 TSK_ExplicitSpecialization); 4581 Diag(Loc, diag::err_enumerator_does_not_exist) 4582 << D->getDeclName() 4583 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 4584 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 4585 << Context.getTypeDeclType(Spec); 4586 } else { 4587 // We should have found something, but didn't. 4588 llvm_unreachable("Unable to find instantiation of declaration!"); 4589 } 4590 } 4591 4592 D = Result; 4593 } 4594 4595 return D; 4596 } 4597 4598 /// \brief Performs template instantiation for all implicit template 4599 /// instantiations we have seen until this point. 4600 void Sema::PerformPendingInstantiations(bool LocalOnly) { 4601 // Load pending instantiations from the external source. 4602 if (!LocalOnly && ExternalSource) { 4603 SmallVector<PendingImplicitInstantiation, 4> Pending; 4604 ExternalSource->ReadPendingInstantiations(Pending); 4605 PendingInstantiations.insert(PendingInstantiations.begin(), 4606 Pending.begin(), Pending.end()); 4607 } 4608 4609 while (!PendingLocalImplicitInstantiations.empty() || 4610 (!LocalOnly && !PendingInstantiations.empty())) { 4611 PendingImplicitInstantiation Inst; 4612 4613 if (PendingLocalImplicitInstantiations.empty()) { 4614 Inst = PendingInstantiations.front(); 4615 PendingInstantiations.pop_front(); 4616 } else { 4617 Inst = PendingLocalImplicitInstantiations.front(); 4618 PendingLocalImplicitInstantiations.pop_front(); 4619 } 4620 4621 // Instantiate function definitions 4622 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 4623 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 4624 "instantiating function definition"); 4625 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 4626 TSK_ExplicitInstantiationDefinition; 4627 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 4628 DefinitionRequired); 4629 continue; 4630 } 4631 4632 // Instantiate variable definitions 4633 VarDecl *Var = cast<VarDecl>(Inst.first); 4634 4635 assert((Var->isStaticDataMember() || 4636 isa<VarTemplateSpecializationDecl>(Var)) && 4637 "Not a static data member, nor a variable template" 4638 " specialization?"); 4639 4640 // Don't try to instantiate declarations if the most recent redeclaration 4641 // is invalid. 4642 if (Var->getMostRecentDecl()->isInvalidDecl()) 4643 continue; 4644 4645 // Check if the most recent declaration has changed the specialization kind 4646 // and removed the need for implicit instantiation. 4647 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 4648 case TSK_Undeclared: 4649 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 4650 case TSK_ExplicitInstantiationDeclaration: 4651 case TSK_ExplicitSpecialization: 4652 continue; // No longer need to instantiate this type. 4653 case TSK_ExplicitInstantiationDefinition: 4654 // We only need an instantiation if the pending instantiation *is* the 4655 // explicit instantiation. 4656 if (Var != Var->getMostRecentDecl()) continue; 4657 case TSK_ImplicitInstantiation: 4658 break; 4659 } 4660 4661 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 4662 "instantiating variable definition"); 4663 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 4664 TSK_ExplicitInstantiationDefinition; 4665 4666 // Instantiate static data member definitions or variable template 4667 // specializations. 4668 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 4669 DefinitionRequired); 4670 } 4671 } 4672 4673 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 4674 const MultiLevelTemplateArgumentList &TemplateArgs) { 4675 for (auto DD : Pattern->ddiags()) { 4676 switch (DD->getKind()) { 4677 case DependentDiagnostic::Access: 4678 HandleDependentAccessCheck(*DD, TemplateArgs); 4679 break; 4680 } 4681 } 4682 } 4683