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/Sema/Lookup.h" 14 #include "clang/Sema/PrettyDeclStackTrace.h" 15 #include "clang/Sema/Template.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/DeclVisitor.h" 20 #include "clang/AST/DependentDiagnostic.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/TypeLoc.h" 24 #include "clang/Lex/Preprocessor.h" 25 26 using namespace clang; 27 28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 29 DeclaratorDecl *NewDecl) { 30 if (!OldDecl->getQualifierLoc()) 31 return false; 32 33 NestedNameSpecifierLoc NewQualifierLoc 34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 35 TemplateArgs); 36 37 if (!NewQualifierLoc) 38 return true; 39 40 NewDecl->setQualifierInfo(NewQualifierLoc); 41 return false; 42 } 43 44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 45 TagDecl *NewDecl) { 46 if (!OldDecl->getQualifierLoc()) 47 return false; 48 49 NestedNameSpecifierLoc NewQualifierLoc 50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 51 TemplateArgs); 52 53 if (!NewQualifierLoc) 54 return true; 55 56 NewDecl->setQualifierInfo(NewQualifierLoc); 57 return false; 58 } 59 60 // Include attribute instantiation code. 61 #include "clang/Sema/AttrTemplateInstantiate.inc" 62 63 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 64 const Decl *Tmpl, Decl *New, 65 LateInstantiatedAttrVec *LateAttrs, 66 LocalInstantiationScope *OuterMostScope) { 67 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end(); 68 i != e; ++i) { 69 const Attr *TmplAttr = *i; 70 71 // FIXME: This should be generalized to more than just the AlignedAttr. 72 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) { 73 if (Aligned->isAlignmentDependent()) { 74 if (Aligned->isAlignmentExpr()) { 75 // The alignment expression is a constant expression. 76 EnterExpressionEvaluationContext Unevaluated(*this, 77 Sema::ConstantEvaluated); 78 79 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(), 80 TemplateArgs); 81 if (!Result.isInvalid()) 82 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(), 83 Aligned->getIsMSDeclSpec()); 84 } else { 85 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(), 86 TemplateArgs, 87 Aligned->getLocation(), 88 DeclarationName()); 89 if (Result) 90 AddAlignedAttr(Aligned->getLocation(), New, Result, 91 Aligned->getIsMSDeclSpec()); 92 } 93 continue; 94 } 95 } 96 97 if (TmplAttr->isLateParsed() && LateAttrs) { 98 // Late parsed attributes must be instantiated and attached after the 99 // enclosing class has been instantiated. See Sema::InstantiateClass. 100 LocalInstantiationScope *Saved = 0; 101 if (CurrentInstantiationScope) 102 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 103 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 104 } else { 105 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 106 *this, TemplateArgs); 107 if (NewAttr) 108 New->addAttr(NewAttr); 109 } 110 } 111 } 112 113 Decl * 114 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 115 llvm_unreachable("Translation units cannot be instantiated"); 116 } 117 118 Decl * 119 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 120 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 121 D->getIdentifier()); 122 Owner->addDecl(Inst); 123 return Inst; 124 } 125 126 Decl * 127 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 128 llvm_unreachable("Namespaces cannot be instantiated"); 129 } 130 131 Decl * 132 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 133 NamespaceAliasDecl *Inst 134 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 135 D->getNamespaceLoc(), 136 D->getAliasLoc(), 137 D->getIdentifier(), 138 D->getQualifierLoc(), 139 D->getTargetNameLoc(), 140 D->getNamespace()); 141 Owner->addDecl(Inst); 142 return Inst; 143 } 144 145 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 146 bool IsTypeAlias) { 147 bool Invalid = false; 148 TypeSourceInfo *DI = D->getTypeSourceInfo(); 149 if (DI->getType()->isInstantiationDependentType() || 150 DI->getType()->isVariablyModifiedType()) { 151 DI = SemaRef.SubstType(DI, TemplateArgs, 152 D->getLocation(), D->getDeclName()); 153 if (!DI) { 154 Invalid = true; 155 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 156 } 157 } else { 158 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 159 } 160 161 // Create the new typedef 162 TypedefNameDecl *Typedef; 163 if (IsTypeAlias) 164 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 165 D->getLocation(), D->getIdentifier(), DI); 166 else 167 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 168 D->getLocation(), D->getIdentifier(), DI); 169 if (Invalid) 170 Typedef->setInvalidDecl(); 171 172 // If the old typedef was the name for linkage purposes of an anonymous 173 // tag decl, re-establish that relationship for the new typedef. 174 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 175 TagDecl *oldTag = oldTagType->getDecl(); 176 if (oldTag->getTypedefNameForAnonDecl() == D) { 177 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 178 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl()); 179 newTag->setTypedefNameForAnonDecl(Typedef); 180 } 181 } 182 183 if (TypedefNameDecl *Prev = D->getPreviousDecl()) { 184 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 185 TemplateArgs); 186 if (!InstPrev) 187 return 0; 188 189 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 190 191 // If the typedef types are not identical, reject them. 192 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 193 194 Typedef->setPreviousDeclaration(InstPrevTypedef); 195 } 196 197 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 198 199 Typedef->setAccess(D->getAccess()); 200 201 return Typedef; 202 } 203 204 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 205 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 206 Owner->addDecl(Typedef); 207 return Typedef; 208 } 209 210 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 211 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 212 Owner->addDecl(Typedef); 213 return Typedef; 214 } 215 216 Decl * 217 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 218 // Create a local instantiation scope for this type alias template, which 219 // will contain the instantiations of the template parameters. 220 LocalInstantiationScope Scope(SemaRef); 221 222 TemplateParameterList *TempParams = D->getTemplateParameters(); 223 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 224 if (!InstParams) 225 return 0; 226 227 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 228 229 TypeAliasTemplateDecl *PrevAliasTemplate = 0; 230 if (Pattern->getPreviousDecl()) { 231 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 232 if (Found.first != Found.second) { 233 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first); 234 } 235 } 236 237 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 238 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 239 if (!AliasInst) 240 return 0; 241 242 TypeAliasTemplateDecl *Inst 243 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 244 D->getDeclName(), InstParams, AliasInst); 245 if (PrevAliasTemplate) 246 Inst->setPreviousDeclaration(PrevAliasTemplate); 247 248 Inst->setAccess(D->getAccess()); 249 250 if (!PrevAliasTemplate) 251 Inst->setInstantiatedFromMemberTemplate(D); 252 253 Owner->addDecl(Inst); 254 255 return Inst; 256 } 257 258 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 259 // If this is the variable for an anonymous struct or union, 260 // instantiate the anonymous struct/union type first. 261 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 262 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 263 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 264 return 0; 265 266 // Do substitution on the type of the declaration 267 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 268 TemplateArgs, 269 D->getTypeSpecStartLoc(), 270 D->getDeclName()); 271 if (!DI) 272 return 0; 273 274 if (DI->getType()->isFunctionType()) { 275 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 276 << D->isStaticDataMember() << DI->getType(); 277 return 0; 278 } 279 280 // Build the instantiated declaration 281 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 282 D->getInnerLocStart(), 283 D->getLocation(), D->getIdentifier(), 284 DI->getType(), DI, 285 D->getStorageClass(), 286 D->getStorageClassAsWritten()); 287 Var->setThreadSpecified(D->isThreadSpecified()); 288 Var->setInitStyle(D->getInitStyle()); 289 Var->setCXXForRangeDecl(D->isCXXForRangeDecl()); 290 Var->setConstexpr(D->isConstexpr()); 291 292 // Substitute the nested name specifier, if any. 293 if (SubstQualifier(D, Var)) 294 return 0; 295 296 // If we are instantiating a static data member defined 297 // out-of-line, the instantiation will have the same lexical 298 // context (which will be a namespace scope) as the template. 299 if (D->isOutOfLine()) 300 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 301 302 Var->setAccess(D->getAccess()); 303 304 if (!D->isStaticDataMember()) { 305 Var->setUsed(D->isUsed(false)); 306 Var->setReferenced(D->isReferenced()); 307 } 308 309 // FIXME: In theory, we could have a previous declaration for variables that 310 // are not static data members. 311 // FIXME: having to fake up a LookupResult is dumb. 312 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 313 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 314 if (D->isStaticDataMember()) 315 SemaRef.LookupQualifiedName(Previous, Owner, false); 316 317 // In ARC, infer 'retaining' for variables of retainable type. 318 if (SemaRef.getLangOpts().ObjCAutoRefCount && 319 SemaRef.inferObjCARCLifetime(Var)) 320 Var->setInvalidDecl(); 321 322 SemaRef.CheckVariableDeclaration(Var, Previous); 323 324 if (D->isOutOfLine()) { 325 D->getLexicalDeclContext()->addDecl(Var); 326 Owner->makeDeclVisibleInContext(Var); 327 } else { 328 Owner->addDecl(Var); 329 if (Owner->isFunctionOrMethod()) 330 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var); 331 } 332 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope); 333 334 // Link instantiations of static data members back to the template from 335 // which they were instantiated. 336 if (Var->isStaticDataMember()) 337 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 338 TSK_ImplicitInstantiation); 339 340 if (Var->getAnyInitializer()) { 341 // We already have an initializer in the class. 342 } else if (D->getInit()) { 343 if (Var->isStaticDataMember() && !D->isOutOfLine()) 344 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D); 345 else 346 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D); 347 348 // Instantiate the initializer. 349 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs, 350 D->getInitStyle() == VarDecl::CallInit); 351 if (!Init.isInvalid()) { 352 bool TypeMayContainAuto = true; 353 if (Init.get()) { 354 bool DirectInit = D->isDirectInit(); 355 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit, 356 TypeMayContainAuto); 357 } else 358 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto); 359 } else { 360 // FIXME: Not too happy about invalidating the declaration 361 // because of a bogus initializer. 362 Var->setInvalidDecl(); 363 } 364 365 SemaRef.PopExpressionEvaluationContext(); 366 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 367 !Var->isCXXForRangeDecl()) 368 SemaRef.ActOnUninitializedDecl(Var, false); 369 370 // Diagnose unused local variables with dependent types, where the diagnostic 371 // will have been deferred. 372 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() && 373 D->getType()->isDependentType()) 374 SemaRef.DiagnoseUnusedDecl(Var); 375 376 return Var; 377 } 378 379 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 380 AccessSpecDecl* AD 381 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 382 D->getAccessSpecifierLoc(), D->getColonLoc()); 383 Owner->addHiddenDecl(AD); 384 return AD; 385 } 386 387 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 388 bool Invalid = false; 389 TypeSourceInfo *DI = D->getTypeSourceInfo(); 390 if (DI->getType()->isInstantiationDependentType() || 391 DI->getType()->isVariablyModifiedType()) { 392 DI = SemaRef.SubstType(DI, TemplateArgs, 393 D->getLocation(), D->getDeclName()); 394 if (!DI) { 395 DI = D->getTypeSourceInfo(); 396 Invalid = true; 397 } else if (DI->getType()->isFunctionType()) { 398 // C++ [temp.arg.type]p3: 399 // If a declaration acquires a function type through a type 400 // dependent on a template-parameter and this causes a 401 // declaration that does not use the syntactic form of a 402 // function declarator to have function type, the program is 403 // ill-formed. 404 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 405 << DI->getType(); 406 Invalid = true; 407 } 408 } else { 409 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 410 } 411 412 Expr *BitWidth = D->getBitWidth(); 413 if (Invalid) 414 BitWidth = 0; 415 else if (BitWidth) { 416 // The bit-width expression is a constant expression. 417 EnterExpressionEvaluationContext Unevaluated(SemaRef, 418 Sema::ConstantEvaluated); 419 420 ExprResult InstantiatedBitWidth 421 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 422 if (InstantiatedBitWidth.isInvalid()) { 423 Invalid = true; 424 BitWidth = 0; 425 } else 426 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 427 } 428 429 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 430 DI->getType(), DI, 431 cast<RecordDecl>(Owner), 432 D->getLocation(), 433 D->isMutable(), 434 BitWidth, 435 D->getInClassInitStyle(), 436 D->getInnerLocStart(), 437 D->getAccess(), 438 0); 439 if (!Field) { 440 cast<Decl>(Owner)->setInvalidDecl(); 441 return 0; 442 } 443 444 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 445 446 if (Invalid) 447 Field->setInvalidDecl(); 448 449 if (!Field->getDeclName()) { 450 // Keep track of where this decl came from. 451 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 452 } 453 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 454 if (Parent->isAnonymousStructOrUnion() && 455 Parent->getRedeclContext()->isFunctionOrMethod()) 456 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 457 } 458 459 Field->setImplicit(D->isImplicit()); 460 Field->setAccess(D->getAccess()); 461 Owner->addDecl(Field); 462 463 return Field; 464 } 465 466 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 467 NamedDecl **NamedChain = 468 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 469 470 int i = 0; 471 for (IndirectFieldDecl::chain_iterator PI = 472 D->chain_begin(), PE = D->chain_end(); 473 PI != PE; ++PI) { 474 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI, 475 TemplateArgs); 476 if (!Next) 477 return 0; 478 479 NamedChain[i++] = Next; 480 } 481 482 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 483 IndirectFieldDecl* IndirectField 484 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(), 485 D->getIdentifier(), T, 486 NamedChain, D->getChainingSize()); 487 488 489 IndirectField->setImplicit(D->isImplicit()); 490 IndirectField->setAccess(D->getAccess()); 491 Owner->addDecl(IndirectField); 492 return IndirectField; 493 } 494 495 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 496 // Handle friend type expressions by simply substituting template 497 // parameters into the pattern type and checking the result. 498 if (TypeSourceInfo *Ty = D->getFriendType()) { 499 TypeSourceInfo *InstTy; 500 // If this is an unsupported friend, don't bother substituting template 501 // arguments into it. The actual type referred to won't be used by any 502 // parts of Clang, and may not be valid for instantiating. Just use the 503 // same info for the instantiated friend. 504 if (D->isUnsupportedFriend()) { 505 InstTy = Ty; 506 } else { 507 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 508 D->getLocation(), DeclarationName()); 509 } 510 if (!InstTy) 511 return 0; 512 513 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(), 514 D->getFriendLoc(), InstTy); 515 if (!FD) 516 return 0; 517 518 FD->setAccess(AS_public); 519 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 520 Owner->addDecl(FD); 521 return FD; 522 } 523 524 NamedDecl *ND = D->getFriendDecl(); 525 assert(ND && "friend decl must be a decl or a type!"); 526 527 // All of the Visit implementations for the various potential friend 528 // declarations have to be carefully written to work for friend 529 // objects, with the most important detail being that the target 530 // decl should almost certainly not be placed in Owner. 531 Decl *NewND = Visit(ND); 532 if (!NewND) return 0; 533 534 FriendDecl *FD = 535 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 536 cast<NamedDecl>(NewND), D->getFriendLoc()); 537 FD->setAccess(AS_public); 538 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 539 Owner->addDecl(FD); 540 return FD; 541 } 542 543 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 544 Expr *AssertExpr = D->getAssertExpr(); 545 546 // The expression in a static assertion is a constant expression. 547 EnterExpressionEvaluationContext Unevaluated(SemaRef, 548 Sema::ConstantEvaluated); 549 550 ExprResult InstantiatedAssertExpr 551 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 552 if (InstantiatedAssertExpr.isInvalid()) 553 return 0; 554 555 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 556 InstantiatedAssertExpr.get(), 557 D->getMessage(), 558 D->getRParenLoc(), 559 D->isFailed()); 560 } 561 562 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 563 EnumDecl *PrevDecl = 0; 564 if (D->getPreviousDecl()) { 565 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 566 D->getPreviousDecl(), 567 TemplateArgs); 568 if (!Prev) return 0; 569 PrevDecl = cast<EnumDecl>(Prev); 570 } 571 572 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 573 D->getLocation(), D->getIdentifier(), 574 PrevDecl, D->isScoped(), 575 D->isScopedUsingClassTag(), D->isFixed()); 576 if (D->isFixed()) { 577 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 578 // If we have type source information for the underlying type, it means it 579 // has been explicitly set by the user. Perform substitution on it before 580 // moving on. 581 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 582 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 583 DeclarationName()); 584 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 585 Enum->setIntegerType(SemaRef.Context.IntTy); 586 else 587 Enum->setIntegerTypeSourceInfo(NewTI); 588 } else { 589 assert(!D->getIntegerType()->isDependentType() 590 && "Dependent type without type source info"); 591 Enum->setIntegerType(D->getIntegerType()); 592 } 593 } 594 595 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 596 597 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 598 Enum->setAccess(D->getAccess()); 599 if (SubstQualifier(D, Enum)) return 0; 600 Owner->addDecl(Enum); 601 602 EnumDecl *Def = D->getDefinition(); 603 if (Def && Def != D) { 604 // If this is an out-of-line definition of an enum member template, check 605 // that the underlying types match in the instantiation of both 606 // declarations. 607 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 608 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 609 QualType DefnUnderlying = 610 SemaRef.SubstType(TI->getType(), TemplateArgs, 611 UnderlyingLoc, DeclarationName()); 612 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 613 DefnUnderlying, Enum); 614 } 615 } 616 617 if (D->getDeclContext()->isFunctionOrMethod()) 618 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 619 620 // C++11 [temp.inst]p1: The implicit instantiation of a class template 621 // specialization causes the implicit instantiation of the declarations, but 622 // not the definitions of scoped member enumerations. 623 // FIXME: There appears to be no wording for what happens for an enum defined 624 // within a block scope, but we treat that much like a member template. Only 625 // instantiate the definition when visiting the definition in that case, since 626 // we will visit all redeclarations. 627 if (!Enum->isScoped() && Def && 628 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition())) 629 InstantiateEnumDefinition(Enum, Def); 630 631 return Enum; 632 } 633 634 void TemplateDeclInstantiator::InstantiateEnumDefinition( 635 EnumDecl *Enum, EnumDecl *Pattern) { 636 Enum->startDefinition(); 637 638 // Update the location to refer to the definition. 639 Enum->setLocation(Pattern->getLocation()); 640 641 SmallVector<Decl*, 4> Enumerators; 642 643 EnumConstantDecl *LastEnumConst = 0; 644 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(), 645 ECEnd = Pattern->enumerator_end(); 646 EC != ECEnd; ++EC) { 647 // The specified value for the enumerator. 648 ExprResult Value = SemaRef.Owned((Expr *)0); 649 if (Expr *UninstValue = EC->getInitExpr()) { 650 // The enumerator's value expression is a constant expression. 651 EnterExpressionEvaluationContext Unevaluated(SemaRef, 652 Sema::ConstantEvaluated); 653 654 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 655 } 656 657 // Drop the initial value and continue. 658 bool isInvalid = false; 659 if (Value.isInvalid()) { 660 Value = SemaRef.Owned((Expr *)0); 661 isInvalid = true; 662 } 663 664 EnumConstantDecl *EnumConst 665 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 666 EC->getLocation(), EC->getIdentifier(), 667 Value.get()); 668 669 if (isInvalid) { 670 if (EnumConst) 671 EnumConst->setInvalidDecl(); 672 Enum->setInvalidDecl(); 673 } 674 675 if (EnumConst) { 676 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst); 677 678 EnumConst->setAccess(Enum->getAccess()); 679 Enum->addDecl(EnumConst); 680 Enumerators.push_back(EnumConst); 681 LastEnumConst = EnumConst; 682 683 if (Pattern->getDeclContext()->isFunctionOrMethod() && 684 !Enum->isScoped()) { 685 // If the enumeration is within a function or method, record the enum 686 // constant as a local. 687 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 688 } 689 } 690 } 691 692 // FIXME: Fixup LBraceLoc 693 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), 694 Enum->getRBraceLoc(), Enum, 695 Enumerators.data(), Enumerators.size(), 696 0, 0); 697 } 698 699 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 700 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 701 } 702 703 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 704 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 705 706 // Create a local instantiation scope for this class template, which 707 // will contain the instantiations of the template parameters. 708 LocalInstantiationScope Scope(SemaRef); 709 TemplateParameterList *TempParams = D->getTemplateParameters(); 710 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 711 if (!InstParams) 712 return NULL; 713 714 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 715 716 // Instantiate the qualifier. We have to do this first in case 717 // we're a friend declaration, because if we are then we need to put 718 // the new declaration in the appropriate context. 719 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 720 if (QualifierLoc) { 721 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 722 TemplateArgs); 723 if (!QualifierLoc) 724 return 0; 725 } 726 727 CXXRecordDecl *PrevDecl = 0; 728 ClassTemplateDecl *PrevClassTemplate = 0; 729 730 if (!isFriend && Pattern->getPreviousDecl()) { 731 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 732 if (Found.first != Found.second) { 733 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first); 734 if (PrevClassTemplate) 735 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 736 } 737 } 738 739 // If this isn't a friend, then it's a member template, in which 740 // case we just want to build the instantiation in the 741 // specialization. If it is a friend, we want to build it in 742 // the appropriate context. 743 DeclContext *DC = Owner; 744 if (isFriend) { 745 if (QualifierLoc) { 746 CXXScopeSpec SS; 747 SS.Adopt(QualifierLoc); 748 DC = SemaRef.computeDeclContext(SS); 749 if (!DC) return 0; 750 } else { 751 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 752 Pattern->getDeclContext(), 753 TemplateArgs); 754 } 755 756 // Look for a previous declaration of the template in the owning 757 // context. 758 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 759 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 760 SemaRef.LookupQualifiedName(R, DC); 761 762 if (R.isSingleResult()) { 763 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 764 if (PrevClassTemplate) 765 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 766 } 767 768 if (!PrevClassTemplate && QualifierLoc) { 769 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 770 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 771 << QualifierLoc.getSourceRange(); 772 return 0; 773 } 774 775 bool AdoptedPreviousTemplateParams = false; 776 if (PrevClassTemplate) { 777 bool Complain = true; 778 779 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 780 // template for struct std::tr1::__detail::_Map_base, where the 781 // template parameters of the friend declaration don't match the 782 // template parameters of the original declaration. In this one 783 // case, we don't complain about the ill-formed friend 784 // declaration. 785 if (isFriend && Pattern->getIdentifier() && 786 Pattern->getIdentifier()->isStr("_Map_base") && 787 DC->isNamespace() && 788 cast<NamespaceDecl>(DC)->getIdentifier() && 789 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 790 DeclContext *DCParent = DC->getParent(); 791 if (DCParent->isNamespace() && 792 cast<NamespaceDecl>(DCParent)->getIdentifier() && 793 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 794 DeclContext *DCParent2 = DCParent->getParent(); 795 if (DCParent2->isNamespace() && 796 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 797 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 798 DCParent2->getParent()->isTranslationUnit()) 799 Complain = false; 800 } 801 } 802 803 TemplateParameterList *PrevParams 804 = PrevClassTemplate->getTemplateParameters(); 805 806 // Make sure the parameter lists match. 807 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 808 Complain, 809 Sema::TPL_TemplateMatch)) { 810 if (Complain) 811 return 0; 812 813 AdoptedPreviousTemplateParams = true; 814 InstParams = PrevParams; 815 } 816 817 // Do some additional validation, then merge default arguments 818 // from the existing declarations. 819 if (!AdoptedPreviousTemplateParams && 820 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 821 Sema::TPC_ClassTemplate)) 822 return 0; 823 } 824 } 825 826 CXXRecordDecl *RecordInst 827 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 828 Pattern->getLocStart(), Pattern->getLocation(), 829 Pattern->getIdentifier(), PrevDecl, 830 /*DelayTypeCreation=*/true); 831 832 if (QualifierLoc) 833 RecordInst->setQualifierInfo(QualifierLoc); 834 835 ClassTemplateDecl *Inst 836 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 837 D->getIdentifier(), InstParams, RecordInst, 838 PrevClassTemplate); 839 RecordInst->setDescribedClassTemplate(Inst); 840 841 if (isFriend) { 842 if (PrevClassTemplate) 843 Inst->setAccess(PrevClassTemplate->getAccess()); 844 else 845 Inst->setAccess(D->getAccess()); 846 847 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 848 // TODO: do we want to track the instantiation progeny of this 849 // friend target decl? 850 } else { 851 Inst->setAccess(D->getAccess()); 852 if (!PrevClassTemplate) 853 Inst->setInstantiatedFromMemberTemplate(D); 854 } 855 856 // Trigger creation of the type for the instantiation. 857 SemaRef.Context.getInjectedClassNameType(RecordInst, 858 Inst->getInjectedClassNameSpecialization()); 859 860 // Finish handling of friends. 861 if (isFriend) { 862 DC->makeDeclVisibleInContext(Inst); 863 Inst->setLexicalDeclContext(Owner); 864 RecordInst->setLexicalDeclContext(Owner); 865 return Inst; 866 } 867 868 if (D->isOutOfLine()) { 869 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 870 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 871 } 872 873 Owner->addDecl(Inst); 874 875 if (!PrevClassTemplate) { 876 // Queue up any out-of-line partial specializations of this member 877 // class template; the client will force their instantiation once 878 // the enclosing class has been instantiated. 879 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 880 D->getPartialSpecializations(PartialSpecs); 881 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 882 if (PartialSpecs[I]->isOutOfLine()) 883 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 884 } 885 886 return Inst; 887 } 888 889 Decl * 890 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 891 ClassTemplatePartialSpecializationDecl *D) { 892 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 893 894 // Lookup the already-instantiated declaration in the instantiation 895 // of the class template and return that. 896 DeclContext::lookup_result Found 897 = Owner->lookup(ClassTemplate->getDeclName()); 898 if (Found.first == Found.second) 899 return 0; 900 901 ClassTemplateDecl *InstClassTemplate 902 = dyn_cast<ClassTemplateDecl>(*Found.first); 903 if (!InstClassTemplate) 904 return 0; 905 906 if (ClassTemplatePartialSpecializationDecl *Result 907 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 908 return Result; 909 910 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 911 } 912 913 Decl * 914 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 915 // Create a local instantiation scope for this function template, which 916 // will contain the instantiations of the template parameters and then get 917 // merged with the local instantiation scope for the function template 918 // itself. 919 LocalInstantiationScope Scope(SemaRef); 920 921 TemplateParameterList *TempParams = D->getTemplateParameters(); 922 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 923 if (!InstParams) 924 return NULL; 925 926 FunctionDecl *Instantiated = 0; 927 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 928 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 929 InstParams)); 930 else 931 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 932 D->getTemplatedDecl(), 933 InstParams)); 934 935 if (!Instantiated) 936 return 0; 937 938 Instantiated->setAccess(D->getAccess()); 939 940 // Link the instantiated function template declaration to the function 941 // template from which it was instantiated. 942 FunctionTemplateDecl *InstTemplate 943 = Instantiated->getDescribedFunctionTemplate(); 944 InstTemplate->setAccess(D->getAccess()); 945 assert(InstTemplate && 946 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 947 948 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 949 950 // Link the instantiation back to the pattern *unless* this is a 951 // non-definition friend declaration. 952 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 953 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 954 InstTemplate->setInstantiatedFromMemberTemplate(D); 955 956 // Make declarations visible in the appropriate context. 957 if (!isFriend) 958 Owner->addDecl(InstTemplate); 959 960 return InstTemplate; 961 } 962 963 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 964 CXXRecordDecl *PrevDecl = 0; 965 if (D->isInjectedClassName()) 966 PrevDecl = cast<CXXRecordDecl>(Owner); 967 else if (D->getPreviousDecl()) { 968 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 969 D->getPreviousDecl(), 970 TemplateArgs); 971 if (!Prev) return 0; 972 PrevDecl = cast<CXXRecordDecl>(Prev); 973 } 974 975 CXXRecordDecl *Record 976 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 977 D->getLocStart(), D->getLocation(), 978 D->getIdentifier(), PrevDecl); 979 980 // Substitute the nested name specifier, if any. 981 if (SubstQualifier(D, Record)) 982 return 0; 983 984 Record->setImplicit(D->isImplicit()); 985 // FIXME: Check against AS_none is an ugly hack to work around the issue that 986 // the tag decls introduced by friend class declarations don't have an access 987 // specifier. Remove once this area of the code gets sorted out. 988 if (D->getAccess() != AS_none) 989 Record->setAccess(D->getAccess()); 990 if (!D->isInjectedClassName()) 991 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 992 993 // If the original function was part of a friend declaration, 994 // inherit its namespace state. 995 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 996 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 997 998 // Make sure that anonymous structs and unions are recorded. 999 if (D->isAnonymousStructOrUnion()) { 1000 Record->setAnonymousStructOrUnion(true); 1001 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod()) 1002 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1003 } 1004 1005 Owner->addDecl(Record); 1006 return Record; 1007 } 1008 1009 /// Normal class members are of more specific types and therefore 1010 /// don't make it here. This function serves two purposes: 1011 /// 1) instantiating function templates 1012 /// 2) substituting friend declarations 1013 /// FIXME: preserve function definitions in case #2 1014 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1015 TemplateParameterList *TemplateParams) { 1016 // Check whether there is already a function template specialization for 1017 // this declaration. 1018 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1019 if (FunctionTemplate && !TemplateParams) { 1020 std::pair<const TemplateArgument *, unsigned> Innermost 1021 = TemplateArgs.getInnermost(); 1022 1023 void *InsertPos = 0; 1024 FunctionDecl *SpecFunc 1025 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second, 1026 InsertPos); 1027 1028 // If we already have a function template specialization, return it. 1029 if (SpecFunc) 1030 return SpecFunc; 1031 } 1032 1033 bool isFriend; 1034 if (FunctionTemplate) 1035 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1036 else 1037 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1038 1039 bool MergeWithParentScope = (TemplateParams != 0) || 1040 Owner->isFunctionOrMethod() || 1041 !(isa<Decl>(Owner) && 1042 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1043 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1044 1045 SmallVector<ParmVarDecl *, 4> Params; 1046 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1047 if (!TInfo) 1048 return 0; 1049 QualType T = TInfo->getType(); 1050 1051 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1052 if (QualifierLoc) { 1053 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1054 TemplateArgs); 1055 if (!QualifierLoc) 1056 return 0; 1057 } 1058 1059 // If we're instantiating a local function declaration, put the result 1060 // in the owner; otherwise we need to find the instantiated context. 1061 DeclContext *DC; 1062 if (D->getDeclContext()->isFunctionOrMethod()) 1063 DC = Owner; 1064 else if (isFriend && QualifierLoc) { 1065 CXXScopeSpec SS; 1066 SS.Adopt(QualifierLoc); 1067 DC = SemaRef.computeDeclContext(SS); 1068 if (!DC) return 0; 1069 } else { 1070 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1071 TemplateArgs); 1072 } 1073 1074 FunctionDecl *Function = 1075 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 1076 D->getLocation(), D->getDeclName(), T, TInfo, 1077 D->getStorageClass(), D->getStorageClassAsWritten(), 1078 D->isInlineSpecified(), D->hasWrittenPrototype(), 1079 D->isConstexpr()); 1080 1081 if (QualifierLoc) 1082 Function->setQualifierInfo(QualifierLoc); 1083 1084 DeclContext *LexicalDC = Owner; 1085 if (!isFriend && D->isOutOfLine()) { 1086 assert(D->getDeclContext()->isFileContext()); 1087 LexicalDC = D->getDeclContext(); 1088 } 1089 1090 Function->setLexicalDeclContext(LexicalDC); 1091 1092 // Attach the parameters 1093 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) { 1094 // Adopt the already-instantiated parameters into our own context. 1095 for (unsigned P = 0; P < Params.size(); ++P) 1096 if (Params[P]) 1097 Params[P]->setOwningFunction(Function); 1098 } else { 1099 // Since we were instantiated via a typedef of a function type, create 1100 // new parameters. 1101 const FunctionProtoType *Proto 1102 = Function->getType()->getAs<FunctionProtoType>(); 1103 assert(Proto && "No function prototype in template instantiation?"); 1104 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(), 1105 AE = Proto->arg_type_end(); AI != AE; ++AI) { 1106 ParmVarDecl *Param 1107 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(), 1108 *AI); 1109 Param->setScopeInfo(0, Params.size()); 1110 Params.push_back(Param); 1111 } 1112 } 1113 Function->setParams(Params); 1114 1115 SourceLocation InstantiateAtPOI; 1116 if (TemplateParams) { 1117 // Our resulting instantiation is actually a function template, since we 1118 // are substituting only the outer template parameters. For example, given 1119 // 1120 // template<typename T> 1121 // struct X { 1122 // template<typename U> friend void f(T, U); 1123 // }; 1124 // 1125 // X<int> x; 1126 // 1127 // We are instantiating the friend function template "f" within X<int>, 1128 // which means substituting int for T, but leaving "f" as a friend function 1129 // template. 1130 // Build the function template itself. 1131 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1132 Function->getLocation(), 1133 Function->getDeclName(), 1134 TemplateParams, Function); 1135 Function->setDescribedFunctionTemplate(FunctionTemplate); 1136 1137 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1138 1139 if (isFriend && D->isThisDeclarationADefinition()) { 1140 // TODO: should we remember this connection regardless of whether 1141 // the friend declaration provided a body? 1142 FunctionTemplate->setInstantiatedFromMemberTemplate( 1143 D->getDescribedFunctionTemplate()); 1144 } 1145 } else if (FunctionTemplate) { 1146 // Record this function template specialization. 1147 std::pair<const TemplateArgument *, unsigned> Innermost 1148 = TemplateArgs.getInnermost(); 1149 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1150 TemplateArgumentList::CreateCopy(SemaRef.Context, 1151 Innermost.first, 1152 Innermost.second), 1153 /*InsertPos=*/0); 1154 } else if (isFriend) { 1155 // Note, we need this connection even if the friend doesn't have a body. 1156 // Its body may exist but not have been attached yet due to deferred 1157 // parsing. 1158 // FIXME: It might be cleaner to set this when attaching the body to the 1159 // friend function declaration, however that would require finding all the 1160 // instantiations and modifying them. 1161 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1162 } 1163 1164 if (InitFunctionInstantiation(Function, D)) 1165 Function->setInvalidDecl(); 1166 1167 bool isExplicitSpecialization = false; 1168 1169 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 1170 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1171 1172 if (DependentFunctionTemplateSpecializationInfo *Info 1173 = D->getDependentSpecializationInfo()) { 1174 assert(isFriend && "non-friend has dependent specialization info?"); 1175 1176 // This needs to be set now for future sanity. 1177 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 1178 1179 // Instantiate the explicit template arguments. 1180 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1181 Info->getRAngleLoc()); 1182 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1183 ExplicitArgs, TemplateArgs)) 1184 return 0; 1185 1186 // Map the candidate templates to their instantiations. 1187 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1188 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1189 Info->getTemplate(I), 1190 TemplateArgs); 1191 if (!Temp) return 0; 1192 1193 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1194 } 1195 1196 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1197 &ExplicitArgs, 1198 Previous)) 1199 Function->setInvalidDecl(); 1200 1201 isExplicitSpecialization = true; 1202 1203 } else if (TemplateParams || !FunctionTemplate) { 1204 // Look only into the namespace where the friend would be declared to 1205 // find a previous declaration. This is the innermost enclosing namespace, 1206 // as described in ActOnFriendFunctionDecl. 1207 SemaRef.LookupQualifiedName(Previous, DC); 1208 1209 // In C++, the previous declaration we find might be a tag type 1210 // (class or enum). In this case, the new declaration will hide the 1211 // tag type. Note that this does does not apply if we're declaring a 1212 // typedef (C++ [dcl.typedef]p4). 1213 if (Previous.isSingleTagDecl()) 1214 Previous.clear(); 1215 } 1216 1217 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1218 isExplicitSpecialization); 1219 1220 NamedDecl *PrincipalDecl = (TemplateParams 1221 ? cast<NamedDecl>(FunctionTemplate) 1222 : Function); 1223 1224 // If the original function was part of a friend declaration, 1225 // inherit its namespace state and add it to the owner. 1226 if (isFriend) { 1227 NamedDecl *PrevDecl; 1228 if (TemplateParams) 1229 PrevDecl = FunctionTemplate->getPreviousDecl(); 1230 else 1231 PrevDecl = Function->getPreviousDecl(); 1232 1233 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0); 1234 DC->makeDeclVisibleInContext(PrincipalDecl); 1235 1236 bool queuedInstantiation = false; 1237 1238 // C++98 [temp.friend]p5: When a function is defined in a friend function 1239 // declaration in a class template, the function is defined at each 1240 // instantiation of the class template. The function is defined even if it 1241 // is never used. 1242 // C++11 [temp.friend]p4: When a function is defined in a friend function 1243 // declaration in a class template, the function is instantiated when the 1244 // function is odr-used. 1245 // 1246 // If -Wc++98-compat is enabled, we go through the motions of checking for a 1247 // redefinition, but don't instantiate the function. 1248 if ((!SemaRef.getLangOpts().CPlusPlus0x || 1249 SemaRef.Diags.getDiagnosticLevel( 1250 diag::warn_cxx98_compat_friend_redefinition, 1251 Function->getLocation()) 1252 != DiagnosticsEngine::Ignored) && 1253 D->isThisDeclarationADefinition()) { 1254 // Check for a function body. 1255 const FunctionDecl *Definition = 0; 1256 if (Function->isDefined(Definition) && 1257 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1258 SemaRef.Diag(Function->getLocation(), 1259 SemaRef.getLangOpts().CPlusPlus0x ? 1260 diag::warn_cxx98_compat_friend_redefinition : 1261 diag::err_redefinition) << Function->getDeclName(); 1262 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1263 if (!SemaRef.getLangOpts().CPlusPlus0x) 1264 Function->setInvalidDecl(); 1265 } 1266 // Check for redefinitions due to other instantiations of this or 1267 // a similar friend function. 1268 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(), 1269 REnd = Function->redecls_end(); 1270 R != REnd; ++R) { 1271 if (*R == Function) 1272 continue; 1273 switch (R->getFriendObjectKind()) { 1274 case Decl::FOK_None: 1275 if (!SemaRef.getLangOpts().CPlusPlus0x && 1276 !queuedInstantiation && R->isUsed(false)) { 1277 if (MemberSpecializationInfo *MSInfo 1278 = Function->getMemberSpecializationInfo()) { 1279 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1280 SourceLocation Loc = R->getLocation(); // FIXME 1281 MSInfo->setPointOfInstantiation(Loc); 1282 SemaRef.PendingLocalImplicitInstantiations.push_back( 1283 std::make_pair(Function, Loc)); 1284 queuedInstantiation = true; 1285 } 1286 } 1287 } 1288 break; 1289 default: 1290 if (const FunctionDecl *RPattern 1291 = R->getTemplateInstantiationPattern()) 1292 if (RPattern->isDefined(RPattern)) { 1293 SemaRef.Diag(Function->getLocation(), 1294 SemaRef.getLangOpts().CPlusPlus0x ? 1295 diag::warn_cxx98_compat_friend_redefinition : 1296 diag::err_redefinition) 1297 << Function->getDeclName(); 1298 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 1299 if (!SemaRef.getLangOpts().CPlusPlus0x) 1300 Function->setInvalidDecl(); 1301 break; 1302 } 1303 } 1304 } 1305 } 1306 } 1307 1308 if (Function->isOverloadedOperator() && !DC->isRecord() && 1309 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1310 PrincipalDecl->setNonMemberOperator(); 1311 1312 assert(!D->isDefaulted() && "only methods should be defaulted"); 1313 return Function; 1314 } 1315 1316 Decl * 1317 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1318 TemplateParameterList *TemplateParams, 1319 bool IsClassScopeSpecialization) { 1320 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1321 if (FunctionTemplate && !TemplateParams) { 1322 // We are creating a function template specialization from a function 1323 // template. Check whether there is already a function template 1324 // specialization for this particular set of template arguments. 1325 std::pair<const TemplateArgument *, unsigned> Innermost 1326 = TemplateArgs.getInnermost(); 1327 1328 void *InsertPos = 0; 1329 FunctionDecl *SpecFunc 1330 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second, 1331 InsertPos); 1332 1333 // If we already have a function template specialization, return it. 1334 if (SpecFunc) 1335 return SpecFunc; 1336 } 1337 1338 bool isFriend; 1339 if (FunctionTemplate) 1340 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1341 else 1342 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1343 1344 bool MergeWithParentScope = (TemplateParams != 0) || 1345 !(isa<Decl>(Owner) && 1346 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1347 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1348 1349 // Instantiate enclosing template arguments for friends. 1350 SmallVector<TemplateParameterList *, 4> TempParamLists; 1351 unsigned NumTempParamLists = 0; 1352 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 1353 TempParamLists.set_size(NumTempParamLists); 1354 for (unsigned I = 0; I != NumTempParamLists; ++I) { 1355 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 1356 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1357 if (!InstParams) 1358 return NULL; 1359 TempParamLists[I] = InstParams; 1360 } 1361 } 1362 1363 SmallVector<ParmVarDecl *, 4> Params; 1364 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1365 if (!TInfo) 1366 return 0; 1367 QualType T = TInfo->getType(); 1368 1369 // \brief If the type of this function, after ignoring parentheses, 1370 // is not *directly* a function type, then we're instantiating a function 1371 // that was declared via a typedef, e.g., 1372 // 1373 // typedef int functype(int, int); 1374 // functype func; 1375 // 1376 // In this case, we'll just go instantiate the ParmVarDecls that we 1377 // synthesized in the method declaration. 1378 if (!isa<FunctionProtoType>(T.IgnoreParens())) { 1379 assert(!Params.size() && "Instantiating type could not yield parameters"); 1380 SmallVector<QualType, 4> ParamTypes; 1381 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 1382 D->getNumParams(), TemplateArgs, ParamTypes, 1383 &Params)) 1384 return 0; 1385 } 1386 1387 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1388 if (QualifierLoc) { 1389 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1390 TemplateArgs); 1391 if (!QualifierLoc) 1392 return 0; 1393 } 1394 1395 DeclContext *DC = Owner; 1396 if (isFriend) { 1397 if (QualifierLoc) { 1398 CXXScopeSpec SS; 1399 SS.Adopt(QualifierLoc); 1400 DC = SemaRef.computeDeclContext(SS); 1401 1402 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 1403 return 0; 1404 } else { 1405 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1406 D->getDeclContext(), 1407 TemplateArgs); 1408 } 1409 if (!DC) return 0; 1410 } 1411 1412 // Build the instantiated method declaration. 1413 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1414 CXXMethodDecl *Method = 0; 1415 1416 SourceLocation StartLoc = D->getInnerLocStart(); 1417 DeclarationNameInfo NameInfo 1418 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1419 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1420 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1421 StartLoc, NameInfo, T, TInfo, 1422 Constructor->isExplicit(), 1423 Constructor->isInlineSpecified(), 1424 false, Constructor->isConstexpr()); 1425 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1426 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1427 StartLoc, NameInfo, T, TInfo, 1428 Destructor->isInlineSpecified(), 1429 false); 1430 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1431 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1432 StartLoc, NameInfo, T, TInfo, 1433 Conversion->isInlineSpecified(), 1434 Conversion->isExplicit(), 1435 Conversion->isConstexpr(), 1436 Conversion->getLocEnd()); 1437 } else { 1438 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 1439 StartLoc, NameInfo, T, TInfo, 1440 D->isStatic(), 1441 D->getStorageClassAsWritten(), 1442 D->isInlineSpecified(), 1443 D->isConstexpr(), D->getLocEnd()); 1444 } 1445 1446 if (QualifierLoc) 1447 Method->setQualifierInfo(QualifierLoc); 1448 1449 if (TemplateParams) { 1450 // Our resulting instantiation is actually a function template, since we 1451 // are substituting only the outer template parameters. For example, given 1452 // 1453 // template<typename T> 1454 // struct X { 1455 // template<typename U> void f(T, U); 1456 // }; 1457 // 1458 // X<int> x; 1459 // 1460 // We are instantiating the member template "f" within X<int>, which means 1461 // substituting int for T, but leaving "f" as a member function template. 1462 // Build the function template itself. 1463 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1464 Method->getLocation(), 1465 Method->getDeclName(), 1466 TemplateParams, Method); 1467 if (isFriend) { 1468 FunctionTemplate->setLexicalDeclContext(Owner); 1469 FunctionTemplate->setObjectOfFriendDecl(true); 1470 } else if (D->isOutOfLine()) 1471 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1472 Method->setDescribedFunctionTemplate(FunctionTemplate); 1473 } else if (FunctionTemplate) { 1474 // Record this function template specialization. 1475 std::pair<const TemplateArgument *, unsigned> Innermost 1476 = TemplateArgs.getInnermost(); 1477 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1478 TemplateArgumentList::CreateCopy(SemaRef.Context, 1479 Innermost.first, 1480 Innermost.second), 1481 /*InsertPos=*/0); 1482 } else if (!isFriend) { 1483 // Record that this is an instantiation of a member function. 1484 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1485 } 1486 1487 // If we are instantiating a member function defined 1488 // out-of-line, the instantiation will have the same lexical 1489 // context (which will be a namespace scope) as the template. 1490 if (isFriend) { 1491 if (NumTempParamLists) 1492 Method->setTemplateParameterListsInfo(SemaRef.Context, 1493 NumTempParamLists, 1494 TempParamLists.data()); 1495 1496 Method->setLexicalDeclContext(Owner); 1497 Method->setObjectOfFriendDecl(true); 1498 } else if (D->isOutOfLine()) 1499 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1500 1501 // Attach the parameters 1502 for (unsigned P = 0; P < Params.size(); ++P) 1503 Params[P]->setOwningFunction(Method); 1504 Method->setParams(Params); 1505 1506 if (InitMethodInstantiation(Method, D)) 1507 Method->setInvalidDecl(); 1508 1509 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 1510 Sema::ForRedeclaration); 1511 1512 if (!FunctionTemplate || TemplateParams || isFriend) { 1513 SemaRef.LookupQualifiedName(Previous, Record); 1514 1515 // In C++, the previous declaration we find might be a tag type 1516 // (class or enum). In this case, the new declaration will hide the 1517 // tag type. Note that this does does not apply if we're declaring a 1518 // typedef (C++ [dcl.typedef]p4). 1519 if (Previous.isSingleTagDecl()) 1520 Previous.clear(); 1521 } 1522 1523 if (!IsClassScopeSpecialization) 1524 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false); 1525 1526 if (D->isPure()) 1527 SemaRef.CheckPureMethod(Method, SourceRange()); 1528 1529 Method->setAccess(D->getAccess()); 1530 1531 SemaRef.CheckOverrideControl(Method); 1532 1533 // If a function is defined as defaulted or deleted, mark it as such now. 1534 if (D->isDefaulted()) 1535 Method->setDefaulted(); 1536 if (D->isDeletedAsWritten()) 1537 Method->setDeletedAsWritten(); 1538 1539 if (FunctionTemplate) { 1540 // If there's a function template, let our caller handle it. 1541 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1542 // Don't hide a (potentially) valid declaration with an invalid one. 1543 } else { 1544 NamedDecl *DeclToAdd = (TemplateParams 1545 ? cast<NamedDecl>(FunctionTemplate) 1546 : Method); 1547 if (isFriend) 1548 Record->makeDeclVisibleInContext(DeclToAdd); 1549 else if (!IsClassScopeSpecialization) 1550 Owner->addDecl(DeclToAdd); 1551 } 1552 1553 if (D->isExplicitlyDefaulted()) { 1554 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 1555 } else { 1556 assert(!D->isDefaulted() && 1557 "should not implicitly default uninstantiated function"); 1558 } 1559 1560 return Method; 1561 } 1562 1563 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1564 return VisitCXXMethodDecl(D); 1565 } 1566 1567 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1568 return VisitCXXMethodDecl(D); 1569 } 1570 1571 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1572 return VisitCXXMethodDecl(D); 1573 } 1574 1575 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1576 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, 1577 llvm::Optional<unsigned>(), 1578 /*ExpectParameterPack=*/false); 1579 } 1580 1581 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1582 TemplateTypeParmDecl *D) { 1583 // TODO: don't always clone when decls are refcounted. 1584 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 1585 1586 TemplateTypeParmDecl *Inst = 1587 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 1588 D->getLocStart(), D->getLocation(), 1589 D->getDepth() - TemplateArgs.getNumLevels(), 1590 D->getIndex(), D->getIdentifier(), 1591 D->wasDeclaredWithTypename(), 1592 D->isParameterPack()); 1593 Inst->setAccess(AS_public); 1594 1595 if (D->hasDefaultArgument()) 1596 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1597 1598 // Introduce this template parameter's instantiation into the instantiation 1599 // scope. 1600 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1601 1602 return Inst; 1603 } 1604 1605 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1606 NonTypeTemplateParmDecl *D) { 1607 // Substitute into the type of the non-type template parameter. 1608 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 1609 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 1610 SmallVector<QualType, 4> ExpandedParameterPackTypes; 1611 bool IsExpandedParameterPack = false; 1612 TypeSourceInfo *DI; 1613 QualType T; 1614 bool Invalid = false; 1615 1616 if (D->isExpandedParameterPack()) { 1617 // The non-type template parameter pack is an already-expanded pack 1618 // expansion of types. Substitute into each of the expanded types. 1619 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 1620 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 1621 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 1622 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 1623 TemplateArgs, 1624 D->getLocation(), 1625 D->getDeclName()); 1626 if (!NewDI) 1627 return 0; 1628 1629 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1630 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 1631 D->getLocation()); 1632 if (NewT.isNull()) 1633 return 0; 1634 ExpandedParameterPackTypes.push_back(NewT); 1635 } 1636 1637 IsExpandedParameterPack = true; 1638 DI = D->getTypeSourceInfo(); 1639 T = DI->getType(); 1640 } else if (isa<PackExpansionTypeLoc>(TL)) { 1641 // The non-type template parameter pack's type is a pack expansion of types. 1642 // Determine whether we need to expand this parameter pack into separate 1643 // types. 1644 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL); 1645 TypeLoc Pattern = Expansion.getPatternLoc(); 1646 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1647 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1648 1649 // Determine whether the set of unexpanded parameter packs can and should 1650 // be expanded. 1651 bool Expand = true; 1652 bool RetainExpansion = false; 1653 llvm::Optional<unsigned> OrigNumExpansions 1654 = Expansion.getTypePtr()->getNumExpansions(); 1655 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions; 1656 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 1657 Pattern.getSourceRange(), 1658 Unexpanded, 1659 TemplateArgs, 1660 Expand, RetainExpansion, 1661 NumExpansions)) 1662 return 0; 1663 1664 if (Expand) { 1665 for (unsigned I = 0; I != *NumExpansions; ++I) { 1666 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 1667 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 1668 D->getLocation(), 1669 D->getDeclName()); 1670 if (!NewDI) 1671 return 0; 1672 1673 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1674 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 1675 NewDI->getType(), 1676 D->getLocation()); 1677 if (NewT.isNull()) 1678 return 0; 1679 ExpandedParameterPackTypes.push_back(NewT); 1680 } 1681 1682 // Note that we have an expanded parameter pack. The "type" of this 1683 // expanded parameter pack is the original expansion type, but callers 1684 // will end up using the expanded parameter pack types for type-checking. 1685 IsExpandedParameterPack = true; 1686 DI = D->getTypeSourceInfo(); 1687 T = DI->getType(); 1688 } else { 1689 // We cannot fully expand the pack expansion now, so substitute into the 1690 // pattern and create a new pack expansion type. 1691 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 1692 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 1693 D->getLocation(), 1694 D->getDeclName()); 1695 if (!NewPattern) 1696 return 0; 1697 1698 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 1699 NumExpansions); 1700 if (!DI) 1701 return 0; 1702 1703 T = DI->getType(); 1704 } 1705 } else { 1706 // Simple case: substitution into a parameter that is not a parameter pack. 1707 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 1708 D->getLocation(), D->getDeclName()); 1709 if (!DI) 1710 return 0; 1711 1712 // Check that this type is acceptable for a non-type template parameter. 1713 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 1714 D->getLocation()); 1715 if (T.isNull()) { 1716 T = SemaRef.Context.IntTy; 1717 Invalid = true; 1718 } 1719 } 1720 1721 NonTypeTemplateParmDecl *Param; 1722 if (IsExpandedParameterPack) 1723 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1724 D->getInnerLocStart(), 1725 D->getLocation(), 1726 D->getDepth() - TemplateArgs.getNumLevels(), 1727 D->getPosition(), 1728 D->getIdentifier(), T, 1729 DI, 1730 ExpandedParameterPackTypes.data(), 1731 ExpandedParameterPackTypes.size(), 1732 ExpandedParameterPackTypesAsWritten.data()); 1733 else 1734 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1735 D->getInnerLocStart(), 1736 D->getLocation(), 1737 D->getDepth() - TemplateArgs.getNumLevels(), 1738 D->getPosition(), 1739 D->getIdentifier(), T, 1740 D->isParameterPack(), DI); 1741 1742 Param->setAccess(AS_public); 1743 if (Invalid) 1744 Param->setInvalidDecl(); 1745 1746 Param->setDefaultArgument(D->getDefaultArgument(), false); 1747 1748 // Introduce this template parameter's instantiation into the instantiation 1749 // scope. 1750 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1751 return Param; 1752 } 1753 1754 Decl * 1755 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1756 TemplateTemplateParmDecl *D) { 1757 // Instantiate the template parameter list of the template template parameter. 1758 TemplateParameterList *TempParams = D->getTemplateParameters(); 1759 TemplateParameterList *InstParams; 1760 { 1761 // Perform the actual substitution of template parameters within a new, 1762 // local instantiation scope. 1763 LocalInstantiationScope Scope(SemaRef); 1764 InstParams = SubstTemplateParams(TempParams); 1765 if (!InstParams) 1766 return NULL; 1767 } 1768 1769 // Build the template template parameter. 1770 TemplateTemplateParmDecl *Param 1771 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1772 D->getDepth() - TemplateArgs.getNumLevels(), 1773 D->getPosition(), D->isParameterPack(), 1774 D->getIdentifier(), InstParams); 1775 Param->setDefaultArgument(D->getDefaultArgument(), false); 1776 Param->setAccess(AS_public); 1777 1778 // Introduce this template parameter's instantiation into the instantiation 1779 // scope. 1780 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1781 1782 return Param; 1783 } 1784 1785 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1786 // Using directives are never dependent (and never contain any types or 1787 // expressions), so they require no explicit instantiation work. 1788 1789 UsingDirectiveDecl *Inst 1790 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1791 D->getNamespaceKeyLocation(), 1792 D->getQualifierLoc(), 1793 D->getIdentLocation(), 1794 D->getNominatedNamespace(), 1795 D->getCommonAncestor()); 1796 Owner->addDecl(Inst); 1797 return Inst; 1798 } 1799 1800 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1801 1802 // The nested name specifier may be dependent, for example 1803 // template <typename T> struct t { 1804 // struct s1 { T f1(); }; 1805 // struct s2 : s1 { using s1::f1; }; 1806 // }; 1807 // template struct t<int>; 1808 // Here, in using s1::f1, s1 refers to t<T>::s1; 1809 // we need to substitute for t<int>::s1. 1810 NestedNameSpecifierLoc QualifierLoc 1811 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 1812 TemplateArgs); 1813 if (!QualifierLoc) 1814 return 0; 1815 1816 // The name info is non-dependent, so no transformation 1817 // is required. 1818 DeclarationNameInfo NameInfo = D->getNameInfo(); 1819 1820 // We only need to do redeclaration lookups if we're in a class 1821 // scope (in fact, it's not really even possible in non-class 1822 // scopes). 1823 bool CheckRedeclaration = Owner->isRecord(); 1824 1825 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 1826 Sema::ForRedeclaration); 1827 1828 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1829 D->getUsingLocation(), 1830 QualifierLoc, 1831 NameInfo, 1832 D->isTypeName()); 1833 1834 CXXScopeSpec SS; 1835 SS.Adopt(QualifierLoc); 1836 if (CheckRedeclaration) { 1837 Prev.setHideTags(false); 1838 SemaRef.LookupQualifiedName(Prev, Owner); 1839 1840 // Check for invalid redeclarations. 1841 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1842 D->isTypeName(), SS, 1843 D->getLocation(), Prev)) 1844 NewUD->setInvalidDecl(); 1845 1846 } 1847 1848 if (!NewUD->isInvalidDecl() && 1849 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1850 D->getLocation())) 1851 NewUD->setInvalidDecl(); 1852 1853 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1854 NewUD->setAccess(D->getAccess()); 1855 Owner->addDecl(NewUD); 1856 1857 // Don't process the shadow decls for an invalid decl. 1858 if (NewUD->isInvalidDecl()) 1859 return NewUD; 1860 1861 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 1862 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD)) 1863 NewUD->setInvalidDecl(); 1864 return NewUD; 1865 } 1866 1867 bool isFunctionScope = Owner->isFunctionOrMethod(); 1868 1869 // Process the shadow decls. 1870 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1871 I != E; ++I) { 1872 UsingShadowDecl *Shadow = *I; 1873 NamedDecl *InstTarget = 1874 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 1875 Shadow->getLocation(), 1876 Shadow->getTargetDecl(), 1877 TemplateArgs)); 1878 if (!InstTarget) 1879 return 0; 1880 1881 if (CheckRedeclaration && 1882 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1883 continue; 1884 1885 UsingShadowDecl *InstShadow 1886 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1887 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1888 1889 if (isFunctionScope) 1890 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1891 } 1892 1893 return NewUD; 1894 } 1895 1896 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1897 // Ignore these; we handle them in bulk when processing the UsingDecl. 1898 return 0; 1899 } 1900 1901 Decl * TemplateDeclInstantiator 1902 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1903 NestedNameSpecifierLoc QualifierLoc 1904 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 1905 TemplateArgs); 1906 if (!QualifierLoc) 1907 return 0; 1908 1909 CXXScopeSpec SS; 1910 SS.Adopt(QualifierLoc); 1911 1912 // Since NameInfo refers to a typename, it cannot be a C++ special name. 1913 // Hence, no tranformation is required for it. 1914 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 1915 NamedDecl *UD = 1916 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1917 D->getUsingLoc(), SS, NameInfo, 0, 1918 /*instantiation*/ true, 1919 /*typename*/ true, D->getTypenameLoc()); 1920 if (UD) 1921 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1922 1923 return UD; 1924 } 1925 1926 Decl * TemplateDeclInstantiator 1927 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1928 NestedNameSpecifierLoc QualifierLoc 1929 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 1930 if (!QualifierLoc) 1931 return 0; 1932 1933 CXXScopeSpec SS; 1934 SS.Adopt(QualifierLoc); 1935 1936 DeclarationNameInfo NameInfo 1937 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1938 1939 NamedDecl *UD = 1940 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1941 D->getUsingLoc(), SS, NameInfo, 0, 1942 /*instantiation*/ true, 1943 /*typename*/ false, SourceLocation()); 1944 if (UD) 1945 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1946 1947 return UD; 1948 } 1949 1950 1951 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 1952 ClassScopeFunctionSpecializationDecl *Decl) { 1953 CXXMethodDecl *OldFD = Decl->getSpecialization(); 1954 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 1955 0, true)); 1956 1957 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName, 1958 Sema::ForRedeclaration); 1959 1960 TemplateArgumentListInfo TemplateArgs; 1961 TemplateArgumentListInfo* TemplateArgsPtr = 0; 1962 if (Decl->hasExplicitTemplateArgs()) { 1963 TemplateArgs = Decl->templateArgs(); 1964 TemplateArgsPtr = &TemplateArgs; 1965 } 1966 1967 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext); 1968 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr, 1969 Previous)) { 1970 NewFD->setInvalidDecl(); 1971 return NewFD; 1972 } 1973 1974 // Associate the specialization with the pattern. 1975 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl()); 1976 assert(Specialization && "Class scope Specialization is null"); 1977 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD); 1978 1979 return NewFD; 1980 } 1981 1982 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1983 const MultiLevelTemplateArgumentList &TemplateArgs) { 1984 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1985 if (D->isInvalidDecl()) 1986 return 0; 1987 1988 return Instantiator.Visit(D); 1989 } 1990 1991 /// \brief Instantiates a nested template parameter list in the current 1992 /// instantiation context. 1993 /// 1994 /// \param L The parameter list to instantiate 1995 /// 1996 /// \returns NULL if there was an error 1997 TemplateParameterList * 1998 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1999 // Get errors for all the parameters before bailing out. 2000 bool Invalid = false; 2001 2002 unsigned N = L->size(); 2003 typedef SmallVector<NamedDecl *, 8> ParamVector; 2004 ParamVector Params; 2005 Params.reserve(N); 2006 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 2007 PI != PE; ++PI) { 2008 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 2009 Params.push_back(D); 2010 Invalid = Invalid || !D || D->isInvalidDecl(); 2011 } 2012 2013 // Clean up if we had an error. 2014 if (Invalid) 2015 return NULL; 2016 2017 TemplateParameterList *InstL 2018 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 2019 L->getLAngleLoc(), &Params.front(), N, 2020 L->getRAngleLoc()); 2021 return InstL; 2022 } 2023 2024 /// \brief Instantiate the declaration of a class template partial 2025 /// specialization. 2026 /// 2027 /// \param ClassTemplate the (instantiated) class template that is partially 2028 // specialized by the instantiation of \p PartialSpec. 2029 /// 2030 /// \param PartialSpec the (uninstantiated) class template partial 2031 /// specialization that we are instantiating. 2032 /// 2033 /// \returns The instantiated partial specialization, if successful; otherwise, 2034 /// NULL to indicate an error. 2035 ClassTemplatePartialSpecializationDecl * 2036 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 2037 ClassTemplateDecl *ClassTemplate, 2038 ClassTemplatePartialSpecializationDecl *PartialSpec) { 2039 // Create a local instantiation scope for this class template partial 2040 // specialization, which will contain the instantiations of the template 2041 // parameters. 2042 LocalInstantiationScope Scope(SemaRef); 2043 2044 // Substitute into the template parameters of the class template partial 2045 // specialization. 2046 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2047 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2048 if (!InstParams) 2049 return 0; 2050 2051 // Substitute into the template arguments of the class template partial 2052 // specialization. 2053 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 2054 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(), 2055 PartialSpec->getNumTemplateArgsAsWritten(), 2056 InstTemplateArgs, TemplateArgs)) 2057 return 0; 2058 2059 // Check that the template argument list is well-formed for this 2060 // class template. 2061 SmallVector<TemplateArgument, 4> Converted; 2062 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 2063 PartialSpec->getLocation(), 2064 InstTemplateArgs, 2065 false, 2066 Converted)) 2067 return 0; 2068 2069 // Figure out where to insert this class template partial specialization 2070 // in the member template's set of class template partial specializations. 2071 void *InsertPos = 0; 2072 ClassTemplateSpecializationDecl *PrevDecl 2073 = ClassTemplate->findPartialSpecialization(Converted.data(), 2074 Converted.size(), InsertPos); 2075 2076 // Build the canonical type that describes the converted template 2077 // arguments of the class template partial specialization. 2078 QualType CanonType 2079 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 2080 Converted.data(), 2081 Converted.size()); 2082 2083 // Build the fully-sugared type for this class template 2084 // specialization as the user wrote in the specialization 2085 // itself. This means that we'll pretty-print the type retrieved 2086 // from the specialization's declaration the way that the user 2087 // actually wrote the specialization, rather than formatting the 2088 // name based on the "canonical" representation used to store the 2089 // template arguments in the specialization. 2090 TypeSourceInfo *WrittenTy 2091 = SemaRef.Context.getTemplateSpecializationTypeInfo( 2092 TemplateName(ClassTemplate), 2093 PartialSpec->getLocation(), 2094 InstTemplateArgs, 2095 CanonType); 2096 2097 if (PrevDecl) { 2098 // We've already seen a partial specialization with the same template 2099 // parameters and template arguments. This can happen, for example, when 2100 // substituting the outer template arguments ends up causing two 2101 // class template partial specializations of a member class template 2102 // to have identical forms, e.g., 2103 // 2104 // template<typename T, typename U> 2105 // struct Outer { 2106 // template<typename X, typename Y> struct Inner; 2107 // template<typename Y> struct Inner<T, Y>; 2108 // template<typename Y> struct Inner<U, Y>; 2109 // }; 2110 // 2111 // Outer<int, int> outer; // error: the partial specializations of Inner 2112 // // have the same signature. 2113 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 2114 << WrittenTy->getType(); 2115 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 2116 << SemaRef.Context.getTypeDeclType(PrevDecl); 2117 return 0; 2118 } 2119 2120 2121 // Create the class template partial specialization declaration. 2122 ClassTemplatePartialSpecializationDecl *InstPartialSpec 2123 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 2124 PartialSpec->getTagKind(), 2125 Owner, 2126 PartialSpec->getLocStart(), 2127 PartialSpec->getLocation(), 2128 InstParams, 2129 ClassTemplate, 2130 Converted.data(), 2131 Converted.size(), 2132 InstTemplateArgs, 2133 CanonType, 2134 0, 2135 ClassTemplate->getNextPartialSpecSequenceNumber()); 2136 // Substitute the nested name specifier, if any. 2137 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2138 return 0; 2139 2140 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2141 InstPartialSpec->setTypeAsWritten(WrittenTy); 2142 2143 // Add this partial specialization to the set of class template partial 2144 // specializations. 2145 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0); 2146 return InstPartialSpec; 2147 } 2148 2149 TypeSourceInfo* 2150 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 2151 SmallVectorImpl<ParmVarDecl *> &Params) { 2152 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 2153 assert(OldTInfo && "substituting function without type source info"); 2154 assert(Params.empty() && "parameter vector is non-empty at start"); 2155 2156 CXXRecordDecl *ThisContext = 0; 2157 unsigned ThisTypeQuals = 0; 2158 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 2159 ThisContext = Method->getParent(); 2160 ThisTypeQuals = Method->getTypeQualifiers(); 2161 } 2162 2163 TypeSourceInfo *NewTInfo 2164 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 2165 D->getTypeSpecStartLoc(), 2166 D->getDeclName(), 2167 ThisContext, ThisTypeQuals); 2168 if (!NewTInfo) 2169 return 0; 2170 2171 if (NewTInfo != OldTInfo) { 2172 // Get parameters from the new type info. 2173 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2174 if (FunctionProtoTypeLoc *OldProtoLoc 2175 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 2176 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 2177 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 2178 assert(NewProtoLoc && "Missing prototype?"); 2179 unsigned NewIdx = 0; 2180 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs(); 2181 OldIdx != NumOldParams; ++OldIdx) { 2182 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx); 2183 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 2184 2185 llvm::Optional<unsigned> NumArgumentsInExpansion; 2186 if (OldParam->isParameterPack()) 2187 NumArgumentsInExpansion = 2188 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 2189 TemplateArgs); 2190 if (!NumArgumentsInExpansion) { 2191 // Simple case: normal parameter, or a parameter pack that's 2192 // instantiated to a (still-dependent) parameter pack. 2193 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++); 2194 Params.push_back(NewParam); 2195 Scope->InstantiatedLocal(OldParam, NewParam); 2196 } else { 2197 // Parameter pack expansion: make the instantiation an argument pack. 2198 Scope->MakeInstantiatedLocalArgPack(OldParam); 2199 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 2200 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++); 2201 Params.push_back(NewParam); 2202 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 2203 } 2204 } 2205 } 2206 } 2207 } else { 2208 // The function type itself was not dependent and therefore no 2209 // substitution occurred. However, we still need to instantiate 2210 // the function parameters themselves. 2211 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2212 if (FunctionProtoTypeLoc *OldProtoLoc 2213 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 2214 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 2215 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 2216 if (!Parm) 2217 return 0; 2218 Params.push_back(Parm); 2219 } 2220 } 2221 } 2222 return NewTInfo; 2223 } 2224 2225 /// Introduce the instantiated function parameters into the local 2226 /// instantiation scope, and set the parameter names to those used 2227 /// in the template. 2228 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 2229 const FunctionDecl *PatternDecl, 2230 LocalInstantiationScope &Scope, 2231 const MultiLevelTemplateArgumentList &TemplateArgs) { 2232 unsigned FParamIdx = 0; 2233 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 2234 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 2235 if (!PatternParam->isParameterPack()) { 2236 // Simple case: not a parameter pack. 2237 assert(FParamIdx < Function->getNumParams()); 2238 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2239 FunctionParam->setDeclName(PatternParam->getDeclName()); 2240 Scope.InstantiatedLocal(PatternParam, FunctionParam); 2241 ++FParamIdx; 2242 continue; 2243 } 2244 2245 // Expand the parameter pack. 2246 Scope.MakeInstantiatedLocalArgPack(PatternParam); 2247 llvm::Optional<unsigned> NumArgumentsInExpansion 2248 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 2249 assert(NumArgumentsInExpansion && 2250 "should only be called when all template arguments are known"); 2251 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 2252 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2253 FunctionParam->setDeclName(PatternParam->getDeclName()); 2254 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 2255 ++FParamIdx; 2256 } 2257 } 2258 } 2259 2260 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New, 2261 const FunctionProtoType *Proto, 2262 const MultiLevelTemplateArgumentList &TemplateArgs) { 2263 assert(Proto->getExceptionSpecType() != EST_Uninstantiated); 2264 2265 // C++11 [expr.prim.general]p3: 2266 // If a declaration declares a member function or member function 2267 // template of a class X, the expression this is a prvalue of type 2268 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 2269 // and the end of the function-definition, member-declarator, or 2270 // declarator. 2271 CXXRecordDecl *ThisContext = 0; 2272 unsigned ThisTypeQuals = 0; 2273 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) { 2274 ThisContext = Method->getParent(); 2275 ThisTypeQuals = Method->getTypeQualifiers(); 2276 } 2277 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals, 2278 SemaRef.getLangOpts().CPlusPlus0x); 2279 2280 // The function has an exception specification or a "noreturn" 2281 // attribute. Substitute into each of the exception types. 2282 SmallVector<QualType, 4> Exceptions; 2283 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 2284 // FIXME: Poor location information! 2285 if (const PackExpansionType *PackExpansion 2286 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) { 2287 // We have a pack expansion. Instantiate it. 2288 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2289 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(), 2290 Unexpanded); 2291 assert(!Unexpanded.empty() && 2292 "Pack expansion without parameter packs?"); 2293 2294 bool Expand = false; 2295 bool RetainExpansion = false; 2296 llvm::Optional<unsigned> NumExpansions 2297 = PackExpansion->getNumExpansions(); 2298 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(), 2299 SourceRange(), 2300 Unexpanded, 2301 TemplateArgs, 2302 Expand, 2303 RetainExpansion, 2304 NumExpansions)) 2305 break; 2306 2307 if (!Expand) { 2308 // We can't expand this pack expansion into separate arguments yet; 2309 // just substitute into the pattern and create a new pack expansion 2310 // type. 2311 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2312 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2313 TemplateArgs, 2314 New->getLocation(), New->getDeclName()); 2315 if (T.isNull()) 2316 break; 2317 2318 T = SemaRef.Context.getPackExpansionType(T, NumExpansions); 2319 Exceptions.push_back(T); 2320 continue; 2321 } 2322 2323 // Substitute into the pack expansion pattern for each template 2324 bool Invalid = false; 2325 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) { 2326 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx); 2327 2328 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2329 TemplateArgs, 2330 New->getLocation(), New->getDeclName()); 2331 if (T.isNull()) { 2332 Invalid = true; 2333 break; 2334 } 2335 2336 Exceptions.push_back(T); 2337 } 2338 2339 if (Invalid) 2340 break; 2341 2342 continue; 2343 } 2344 2345 QualType T 2346 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 2347 New->getLocation(), New->getDeclName()); 2348 if (T.isNull() || 2349 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 2350 continue; 2351 2352 Exceptions.push_back(T); 2353 } 2354 Expr *NoexceptExpr = 0; 2355 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) { 2356 EnterExpressionEvaluationContext Unevaluated(SemaRef, 2357 Sema::ConstantEvaluated); 2358 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs); 2359 if (E.isUsable()) 2360 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart()); 2361 2362 if (E.isUsable()) { 2363 NoexceptExpr = E.take(); 2364 if (!NoexceptExpr->isTypeDependent() && 2365 !NoexceptExpr->isValueDependent()) 2366 NoexceptExpr 2367 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr, 2368 0, diag::err_noexcept_needs_constant_expression, 2369 /*AllowFold*/ false).take(); 2370 } 2371 } 2372 2373 // Rebuild the function type 2374 const FunctionProtoType *NewProto 2375 = New->getType()->getAs<FunctionProtoType>(); 2376 assert(NewProto && "Template instantiation without function prototype?"); 2377 2378 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo(); 2379 EPI.ExceptionSpecType = Proto->getExceptionSpecType(); 2380 EPI.NumExceptions = Exceptions.size(); 2381 EPI.Exceptions = Exceptions.data(); 2382 EPI.NoexceptExpr = NoexceptExpr; 2383 2384 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 2385 NewProto->arg_type_begin(), 2386 NewProto->getNumArgs(), 2387 EPI)); 2388 } 2389 2390 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 2391 FunctionDecl *Decl) { 2392 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 2393 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 2394 return; 2395 2396 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 2397 InstantiatingTemplate::ExceptionSpecification()); 2398 if (Inst) { 2399 // We hit the instantiation depth limit. Clear the exception specification 2400 // so that our callers don't have to cope with EST_Uninstantiated. 2401 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 2402 EPI.ExceptionSpecType = EST_None; 2403 Decl->setType(Context.getFunctionType(Proto->getResultType(), 2404 Proto->arg_type_begin(), 2405 Proto->getNumArgs(), 2406 EPI)); 2407 return; 2408 } 2409 2410 // Enter the scope of this instantiation. We don't use 2411 // PushDeclContext because we don't have a scope. 2412 Sema::ContextRAII savedContext(*this, Decl); 2413 LocalInstantiationScope Scope(*this); 2414 2415 MultiLevelTemplateArgumentList TemplateArgs = 2416 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true); 2417 2418 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 2419 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs); 2420 2421 ::InstantiateExceptionSpec(*this, Decl, 2422 Template->getType()->castAs<FunctionProtoType>(), 2423 TemplateArgs); 2424 } 2425 2426 /// \brief Initializes the common fields of an instantiation function 2427 /// declaration (New) from the corresponding fields of its template (Tmpl). 2428 /// 2429 /// \returns true if there was an error 2430 bool 2431 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 2432 FunctionDecl *Tmpl) { 2433 if (Tmpl->isDeleted()) 2434 New->setDeletedAsWritten(); 2435 2436 // If we are performing substituting explicitly-specified template arguments 2437 // or deduced template arguments into a function template and we reach this 2438 // point, we are now past the point where SFINAE applies and have committed 2439 // to keeping the new function template specialization. We therefore 2440 // convert the active template instantiation for the function template 2441 // into a template instantiation for this specific function template 2442 // specialization, which is not a SFINAE context, so that we diagnose any 2443 // further errors in the declaration itself. 2444 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 2445 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 2446 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 2447 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 2448 if (FunctionTemplateDecl *FunTmpl 2449 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 2450 assert(FunTmpl->getTemplatedDecl() == Tmpl && 2451 "Deduction from the wrong function template?"); 2452 (void) FunTmpl; 2453 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 2454 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 2455 } 2456 } 2457 2458 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 2459 assert(Proto && "Function template without prototype?"); 2460 2461 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 2462 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 2463 2464 // DR1330: In C++11, defer instantiation of a non-trivial 2465 // exception specification. 2466 if (SemaRef.getLangOpts().CPlusPlus0x && 2467 EPI.ExceptionSpecType != EST_None && 2468 EPI.ExceptionSpecType != EST_DynamicNone && 2469 EPI.ExceptionSpecType != EST_BasicNoexcept) { 2470 FunctionDecl *ExceptionSpecTemplate = Tmpl; 2471 if (EPI.ExceptionSpecType == EST_Uninstantiated) 2472 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate; 2473 assert(EPI.ExceptionSpecType != EST_Unevaluated && 2474 "instantiating implicitly-declared special member"); 2475 2476 // Mark the function has having an uninstantiated exception specification. 2477 const FunctionProtoType *NewProto 2478 = New->getType()->getAs<FunctionProtoType>(); 2479 assert(NewProto && "Template instantiation without function prototype?"); 2480 EPI = NewProto->getExtProtoInfo(); 2481 EPI.ExceptionSpecType = EST_Uninstantiated; 2482 EPI.ExceptionSpecDecl = New; 2483 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate; 2484 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 2485 NewProto->arg_type_begin(), 2486 NewProto->getNumArgs(), 2487 EPI)); 2488 } else { 2489 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs); 2490 } 2491 } 2492 2493 // Get the definition. Leaves the variable unchanged if undefined. 2494 const FunctionDecl *Definition = Tmpl; 2495 Tmpl->isDefined(Definition); 2496 2497 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 2498 LateAttrs, StartingScope); 2499 2500 return false; 2501 } 2502 2503 /// \brief Initializes common fields of an instantiated method 2504 /// declaration (New) from the corresponding fields of its template 2505 /// (Tmpl). 2506 /// 2507 /// \returns true if there was an error 2508 bool 2509 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 2510 CXXMethodDecl *Tmpl) { 2511 if (InitFunctionInstantiation(New, Tmpl)) 2512 return true; 2513 2514 New->setAccess(Tmpl->getAccess()); 2515 if (Tmpl->isVirtualAsWritten()) 2516 New->setVirtualAsWritten(true); 2517 2518 // FIXME: attributes 2519 // FIXME: New needs a pointer to Tmpl 2520 return false; 2521 } 2522 2523 /// \brief Instantiate the definition of the given function from its 2524 /// template. 2525 /// 2526 /// \param PointOfInstantiation the point at which the instantiation was 2527 /// required. Note that this is not precisely a "point of instantiation" 2528 /// for the function, but it's close. 2529 /// 2530 /// \param Function the already-instantiated declaration of a 2531 /// function template specialization or member function of a class template 2532 /// specialization. 2533 /// 2534 /// \param Recursive if true, recursively instantiates any functions that 2535 /// are required by this instantiation. 2536 /// 2537 /// \param DefinitionRequired if true, then we are performing an explicit 2538 /// instantiation where the body of the function is required. Complain if 2539 /// there is no such body. 2540 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 2541 FunctionDecl *Function, 2542 bool Recursive, 2543 bool DefinitionRequired) { 2544 if (Function->isInvalidDecl() || Function->isDefined()) 2545 return; 2546 2547 // Never instantiate an explicit specialization except if it is a class scope 2548 // explicit specialization. 2549 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 2550 !Function->getClassScopeSpecializationPattern()) 2551 return; 2552 2553 // Find the function body that we'll be substituting. 2554 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 2555 assert(PatternDecl && "instantiating a non-template"); 2556 2557 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 2558 assert(PatternDecl && "template definition is not a template"); 2559 if (!Pattern) { 2560 // Try to find a defaulted definition 2561 PatternDecl->isDefined(PatternDecl); 2562 } 2563 assert(PatternDecl && "template definition is not a template"); 2564 2565 // Postpone late parsed template instantiations. 2566 if (PatternDecl->isLateTemplateParsed() && 2567 !LateTemplateParser) { 2568 PendingInstantiations.push_back( 2569 std::make_pair(Function, PointOfInstantiation)); 2570 return; 2571 } 2572 2573 // Call the LateTemplateParser callback if there a need to late parse 2574 // a templated function definition. 2575 if (!Pattern && PatternDecl->isLateTemplateParsed() && 2576 LateTemplateParser) { 2577 LateTemplateParser(OpaqueParser, PatternDecl); 2578 Pattern = PatternDecl->getBody(PatternDecl); 2579 } 2580 2581 if (!Pattern && !PatternDecl->isDefaulted()) { 2582 if (DefinitionRequired) { 2583 if (Function->getPrimaryTemplate()) 2584 Diag(PointOfInstantiation, 2585 diag::err_explicit_instantiation_undefined_func_template) 2586 << Function->getPrimaryTemplate(); 2587 else 2588 Diag(PointOfInstantiation, 2589 diag::err_explicit_instantiation_undefined_member) 2590 << 1 << Function->getDeclName() << Function->getDeclContext(); 2591 2592 if (PatternDecl) 2593 Diag(PatternDecl->getLocation(), 2594 diag::note_explicit_instantiation_here); 2595 Function->setInvalidDecl(); 2596 } else if (Function->getTemplateSpecializationKind() 2597 == TSK_ExplicitInstantiationDefinition) { 2598 PendingInstantiations.push_back( 2599 std::make_pair(Function, PointOfInstantiation)); 2600 } 2601 2602 return; 2603 } 2604 2605 // C++0x [temp.explicit]p9: 2606 // Except for inline functions, other explicit instantiation declarations 2607 // have the effect of suppressing the implicit instantiation of the entity 2608 // to which they refer. 2609 if (Function->getTemplateSpecializationKind() 2610 == TSK_ExplicitInstantiationDeclaration && 2611 !PatternDecl->isInlined()) 2612 return; 2613 2614 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 2615 if (Inst) 2616 return; 2617 2618 // Copy the inner loc start from the pattern. 2619 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 2620 2621 // If we're performing recursive template instantiation, create our own 2622 // queue of pending implicit instantiations that we will instantiate later, 2623 // while we're still within our own instantiation context. 2624 SmallVector<VTableUse, 16> SavedVTableUses; 2625 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 2626 if (Recursive) { 2627 VTableUses.swap(SavedVTableUses); 2628 PendingInstantiations.swap(SavedPendingInstantiations); 2629 } 2630 2631 EnterExpressionEvaluationContext EvalContext(*this, 2632 Sema::PotentiallyEvaluated); 2633 ActOnStartOfFunctionDef(0, Function); 2634 2635 // Introduce a new scope where local variable instantiations will be 2636 // recorded, unless we're actually a member function within a local 2637 // class, in which case we need to merge our results with the parent 2638 // scope (of the enclosing function). 2639 bool MergeWithParentScope = false; 2640 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 2641 MergeWithParentScope = Rec->isLocalClass(); 2642 2643 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2644 2645 // Enter the scope of this instantiation. We don't use 2646 // PushDeclContext because we don't have a scope. 2647 Sema::ContextRAII savedContext(*this, Function); 2648 2649 MultiLevelTemplateArgumentList TemplateArgs = 2650 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 2651 2652 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 2653 TemplateArgs); 2654 2655 if (PatternDecl->isDefaulted()) { 2656 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true); 2657 2658 SetDeclDefaulted(Function, PatternDecl->getLocation()); 2659 } else { 2660 // If this is a constructor, instantiate the member initializers. 2661 if (const CXXConstructorDecl *Ctor = 2662 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 2663 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 2664 TemplateArgs); 2665 } 2666 2667 // Instantiate the function body. 2668 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 2669 2670 if (Body.isInvalid()) 2671 Function->setInvalidDecl(); 2672 2673 ActOnFinishFunctionBody(Function, Body.get(), 2674 /*IsInstantiation=*/true); 2675 } 2676 2677 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 2678 2679 savedContext.pop(); 2680 2681 DeclGroupRef DG(Function); 2682 Consumer.HandleTopLevelDecl(DG); 2683 2684 // This class may have local implicit instantiations that need to be 2685 // instantiation within this scope. 2686 PerformPendingInstantiations(/*LocalOnly=*/true); 2687 Scope.Exit(); 2688 2689 if (Recursive) { 2690 // Define any pending vtables. 2691 DefineUsedVTables(); 2692 2693 // Instantiate any pending implicit instantiations found during the 2694 // instantiation of this template. 2695 PerformPendingInstantiations(); 2696 2697 // Restore the set of pending vtables. 2698 assert(VTableUses.empty() && 2699 "VTableUses should be empty before it is discarded."); 2700 VTableUses.swap(SavedVTableUses); 2701 2702 // Restore the set of pending implicit instantiations. 2703 assert(PendingInstantiations.empty() && 2704 "PendingInstantiations should be empty before it is discarded."); 2705 PendingInstantiations.swap(SavedPendingInstantiations); 2706 } 2707 } 2708 2709 /// \brief Instantiate the definition of the given variable from its 2710 /// template. 2711 /// 2712 /// \param PointOfInstantiation the point at which the instantiation was 2713 /// required. Note that this is not precisely a "point of instantiation" 2714 /// for the function, but it's close. 2715 /// 2716 /// \param Var the already-instantiated declaration of a static member 2717 /// variable of a class template specialization. 2718 /// 2719 /// \param Recursive if true, recursively instantiates any functions that 2720 /// are required by this instantiation. 2721 /// 2722 /// \param DefinitionRequired if true, then we are performing an explicit 2723 /// instantiation where an out-of-line definition of the member variable 2724 /// is required. Complain if there is no such definition. 2725 void Sema::InstantiateStaticDataMemberDefinition( 2726 SourceLocation PointOfInstantiation, 2727 VarDecl *Var, 2728 bool Recursive, 2729 bool DefinitionRequired) { 2730 if (Var->isInvalidDecl()) 2731 return; 2732 2733 // Find the out-of-line definition of this static data member. 2734 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 2735 assert(Def && "This data member was not instantiated from a template?"); 2736 assert(Def->isStaticDataMember() && "Not a static data member?"); 2737 Def = Def->getOutOfLineDefinition(); 2738 2739 if (!Def) { 2740 // We did not find an out-of-line definition of this static data member, 2741 // so we won't perform any instantiation. Rather, we rely on the user to 2742 // instantiate this definition (or provide a specialization for it) in 2743 // another translation unit. 2744 if (DefinitionRequired) { 2745 Def = Var->getInstantiatedFromStaticDataMember(); 2746 Diag(PointOfInstantiation, 2747 diag::err_explicit_instantiation_undefined_member) 2748 << 2 << Var->getDeclName() << Var->getDeclContext(); 2749 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 2750 } else if (Var->getTemplateSpecializationKind() 2751 == TSK_ExplicitInstantiationDefinition) { 2752 PendingInstantiations.push_back( 2753 std::make_pair(Var, PointOfInstantiation)); 2754 } 2755 2756 return; 2757 } 2758 2759 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 2760 2761 // Never instantiate an explicit specialization. 2762 if (TSK == TSK_ExplicitSpecialization) 2763 return; 2764 2765 // C++0x [temp.explicit]p9: 2766 // Except for inline functions, other explicit instantiation declarations 2767 // have the effect of suppressing the implicit instantiation of the entity 2768 // to which they refer. 2769 if (TSK == TSK_ExplicitInstantiationDeclaration) 2770 return; 2771 2772 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 2773 2774 // If we already have a definition, we're done. 2775 if (VarDecl *Def = Var->getDefinition()) { 2776 // We may be explicitly instantiating something we've already implicitly 2777 // instantiated. 2778 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 2779 PointOfInstantiation); 2780 return; 2781 } 2782 2783 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 2784 if (Inst) 2785 return; 2786 2787 // If we're performing recursive template instantiation, create our own 2788 // queue of pending implicit instantiations that we will instantiate later, 2789 // while we're still within our own instantiation context. 2790 SmallVector<VTableUse, 16> SavedVTableUses; 2791 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 2792 if (Recursive) { 2793 VTableUses.swap(SavedVTableUses); 2794 PendingInstantiations.swap(SavedPendingInstantiations); 2795 } 2796 2797 // Enter the scope of this instantiation. We don't use 2798 // PushDeclContext because we don't have a scope. 2799 ContextRAII previousContext(*this, Var->getDeclContext()); 2800 LocalInstantiationScope Local(*this); 2801 2802 VarDecl *OldVar = Var; 2803 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 2804 getTemplateInstantiationArgs(Var))); 2805 2806 previousContext.pop(); 2807 2808 if (Var) { 2809 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 2810 assert(MSInfo && "Missing member specialization information?"); 2811 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 2812 MSInfo->getPointOfInstantiation()); 2813 DeclGroupRef DG(Var); 2814 Consumer.HandleTopLevelDecl(DG); 2815 } 2816 Local.Exit(); 2817 2818 if (Recursive) { 2819 // Define any newly required vtables. 2820 DefineUsedVTables(); 2821 2822 // Instantiate any pending implicit instantiations found during the 2823 // instantiation of this template. 2824 PerformPendingInstantiations(); 2825 2826 // Restore the set of pending vtables. 2827 assert(VTableUses.empty() && 2828 "VTableUses should be empty before it is discarded, " 2829 "while instantiating static data member."); 2830 VTableUses.swap(SavedVTableUses); 2831 2832 // Restore the set of pending implicit instantiations. 2833 assert(PendingInstantiations.empty() && 2834 "PendingInstantiations should be empty before it is discarded, " 2835 "while instantiating static data member."); 2836 PendingInstantiations.swap(SavedPendingInstantiations); 2837 } 2838 } 2839 2840 void 2841 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 2842 const CXXConstructorDecl *Tmpl, 2843 const MultiLevelTemplateArgumentList &TemplateArgs) { 2844 2845 SmallVector<CXXCtorInitializer*, 4> NewInits; 2846 bool AnyErrors = false; 2847 2848 // Instantiate all the initializers. 2849 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 2850 InitsEnd = Tmpl->init_end(); 2851 Inits != InitsEnd; ++Inits) { 2852 CXXCtorInitializer *Init = *Inits; 2853 2854 // Only instantiate written initializers, let Sema re-construct implicit 2855 // ones. 2856 if (!Init->isWritten()) 2857 continue; 2858 2859 SourceLocation EllipsisLoc; 2860 2861 if (Init->isPackExpansion()) { 2862 // This is a pack expansion. We should expand it now. 2863 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 2864 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2865 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 2866 bool ShouldExpand = false; 2867 bool RetainExpansion = false; 2868 llvm::Optional<unsigned> NumExpansions; 2869 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 2870 BaseTL.getSourceRange(), 2871 Unexpanded, 2872 TemplateArgs, ShouldExpand, 2873 RetainExpansion, 2874 NumExpansions)) { 2875 AnyErrors = true; 2876 New->setInvalidDecl(); 2877 continue; 2878 } 2879 assert(ShouldExpand && "Partial instantiation of base initializer?"); 2880 2881 // Loop over all of the arguments in the argument pack(s), 2882 for (unsigned I = 0; I != *NumExpansions; ++I) { 2883 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 2884 2885 // Instantiate the initializer. 2886 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 2887 /*CXXDirectInit=*/true); 2888 if (TempInit.isInvalid()) { 2889 AnyErrors = true; 2890 break; 2891 } 2892 2893 // Instantiate the base type. 2894 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 2895 TemplateArgs, 2896 Init->getSourceLocation(), 2897 New->getDeclName()); 2898 if (!BaseTInfo) { 2899 AnyErrors = true; 2900 break; 2901 } 2902 2903 // Build the initializer. 2904 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 2905 BaseTInfo, TempInit.take(), 2906 New->getParent(), 2907 SourceLocation()); 2908 if (NewInit.isInvalid()) { 2909 AnyErrors = true; 2910 break; 2911 } 2912 2913 NewInits.push_back(NewInit.get()); 2914 } 2915 2916 continue; 2917 } 2918 2919 // Instantiate the initializer. 2920 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 2921 /*CXXDirectInit=*/true); 2922 if (TempInit.isInvalid()) { 2923 AnyErrors = true; 2924 continue; 2925 } 2926 2927 MemInitResult NewInit; 2928 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 2929 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 2930 TemplateArgs, 2931 Init->getSourceLocation(), 2932 New->getDeclName()); 2933 if (!TInfo) { 2934 AnyErrors = true; 2935 New->setInvalidDecl(); 2936 continue; 2937 } 2938 2939 if (Init->isBaseInitializer()) 2940 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(), 2941 New->getParent(), EllipsisLoc); 2942 else 2943 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(), 2944 cast<CXXRecordDecl>(CurContext->getParent())); 2945 } else if (Init->isMemberInitializer()) { 2946 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 2947 Init->getMemberLocation(), 2948 Init->getMember(), 2949 TemplateArgs)); 2950 if (!Member) { 2951 AnyErrors = true; 2952 New->setInvalidDecl(); 2953 continue; 2954 } 2955 2956 NewInit = BuildMemberInitializer(Member, TempInit.take(), 2957 Init->getSourceLocation()); 2958 } else if (Init->isIndirectMemberInitializer()) { 2959 IndirectFieldDecl *IndirectMember = 2960 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 2961 Init->getMemberLocation(), 2962 Init->getIndirectMember(), TemplateArgs)); 2963 2964 if (!IndirectMember) { 2965 AnyErrors = true; 2966 New->setInvalidDecl(); 2967 continue; 2968 } 2969 2970 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(), 2971 Init->getSourceLocation()); 2972 } 2973 2974 if (NewInit.isInvalid()) { 2975 AnyErrors = true; 2976 New->setInvalidDecl(); 2977 } else { 2978 NewInits.push_back(NewInit.get()); 2979 } 2980 } 2981 2982 // Assign all the initializers to the new constructor. 2983 ActOnMemInitializers(New, 2984 /*FIXME: ColonLoc */ 2985 SourceLocation(), 2986 NewInits.data(), NewInits.size(), 2987 AnyErrors); 2988 } 2989 2990 ExprResult Sema::SubstInitializer(Expr *Init, 2991 const MultiLevelTemplateArgumentList &TemplateArgs, 2992 bool CXXDirectInit) { 2993 // Initializers are instantiated like expressions, except that various outer 2994 // layers are stripped. 2995 if (!Init) 2996 return Owned(Init); 2997 2998 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init)) 2999 Init = ExprTemp->getSubExpr(); 3000 3001 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init)) 3002 Init = Binder->getSubExpr(); 3003 3004 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init)) 3005 Init = ICE->getSubExprAsWritten(); 3006 3007 // If this is a direct-initializer, we take apart CXXConstructExprs. 3008 // Everything else is passed through. 3009 CXXConstructExpr *Construct; 3010 if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) || 3011 isa<CXXTemporaryObjectExpr>(Construct)) 3012 return SubstExpr(Init, TemplateArgs); 3013 3014 ASTOwningVector<Expr*> NewArgs(*this); 3015 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true, 3016 TemplateArgs, NewArgs)) 3017 return ExprError(); 3018 3019 // Treat an empty initializer like none. 3020 if (NewArgs.empty()) 3021 return Owned((Expr*)0); 3022 3023 // Build a ParenListExpr to represent anything else. 3024 // FIXME: Fake locations! 3025 SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart()); 3026 return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs)); 3027 } 3028 3029 // TODO: this could be templated if the various decl types used the 3030 // same method name. 3031 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 3032 ClassTemplateDecl *Instance) { 3033 Pattern = Pattern->getCanonicalDecl(); 3034 3035 do { 3036 Instance = Instance->getCanonicalDecl(); 3037 if (Pattern == Instance) return true; 3038 Instance = Instance->getInstantiatedFromMemberTemplate(); 3039 } while (Instance); 3040 3041 return false; 3042 } 3043 3044 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 3045 FunctionTemplateDecl *Instance) { 3046 Pattern = Pattern->getCanonicalDecl(); 3047 3048 do { 3049 Instance = Instance->getCanonicalDecl(); 3050 if (Pattern == Instance) return true; 3051 Instance = Instance->getInstantiatedFromMemberTemplate(); 3052 } while (Instance); 3053 3054 return false; 3055 } 3056 3057 static bool 3058 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 3059 ClassTemplatePartialSpecializationDecl *Instance) { 3060 Pattern 3061 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 3062 do { 3063 Instance = cast<ClassTemplatePartialSpecializationDecl>( 3064 Instance->getCanonicalDecl()); 3065 if (Pattern == Instance) 3066 return true; 3067 Instance = Instance->getInstantiatedFromMember(); 3068 } while (Instance); 3069 3070 return false; 3071 } 3072 3073 static bool isInstantiationOf(CXXRecordDecl *Pattern, 3074 CXXRecordDecl *Instance) { 3075 Pattern = Pattern->getCanonicalDecl(); 3076 3077 do { 3078 Instance = Instance->getCanonicalDecl(); 3079 if (Pattern == Instance) return true; 3080 Instance = Instance->getInstantiatedFromMemberClass(); 3081 } while (Instance); 3082 3083 return false; 3084 } 3085 3086 static bool isInstantiationOf(FunctionDecl *Pattern, 3087 FunctionDecl *Instance) { 3088 Pattern = Pattern->getCanonicalDecl(); 3089 3090 do { 3091 Instance = Instance->getCanonicalDecl(); 3092 if (Pattern == Instance) return true; 3093 Instance = Instance->getInstantiatedFromMemberFunction(); 3094 } while (Instance); 3095 3096 return false; 3097 } 3098 3099 static bool isInstantiationOf(EnumDecl *Pattern, 3100 EnumDecl *Instance) { 3101 Pattern = Pattern->getCanonicalDecl(); 3102 3103 do { 3104 Instance = Instance->getCanonicalDecl(); 3105 if (Pattern == Instance) return true; 3106 Instance = Instance->getInstantiatedFromMemberEnum(); 3107 } while (Instance); 3108 3109 return false; 3110 } 3111 3112 static bool isInstantiationOf(UsingShadowDecl *Pattern, 3113 UsingShadowDecl *Instance, 3114 ASTContext &C) { 3115 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 3116 } 3117 3118 static bool isInstantiationOf(UsingDecl *Pattern, 3119 UsingDecl *Instance, 3120 ASTContext &C) { 3121 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 3122 } 3123 3124 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 3125 UsingDecl *Instance, 3126 ASTContext &C) { 3127 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 3128 } 3129 3130 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 3131 UsingDecl *Instance, 3132 ASTContext &C) { 3133 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 3134 } 3135 3136 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 3137 VarDecl *Instance) { 3138 assert(Instance->isStaticDataMember()); 3139 3140 Pattern = Pattern->getCanonicalDecl(); 3141 3142 do { 3143 Instance = Instance->getCanonicalDecl(); 3144 if (Pattern == Instance) return true; 3145 Instance = Instance->getInstantiatedFromStaticDataMember(); 3146 } while (Instance); 3147 3148 return false; 3149 } 3150 3151 // Other is the prospective instantiation 3152 // D is the prospective pattern 3153 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 3154 if (D->getKind() != Other->getKind()) { 3155 if (UnresolvedUsingTypenameDecl *UUD 3156 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3157 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 3158 return isInstantiationOf(UUD, UD, Ctx); 3159 } 3160 } 3161 3162 if (UnresolvedUsingValueDecl *UUD 3163 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3164 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 3165 return isInstantiationOf(UUD, UD, Ctx); 3166 } 3167 } 3168 3169 return false; 3170 } 3171 3172 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 3173 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 3174 3175 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 3176 return isInstantiationOf(cast<FunctionDecl>(D), Function); 3177 3178 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 3179 return isInstantiationOf(cast<EnumDecl>(D), Enum); 3180 3181 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 3182 if (Var->isStaticDataMember()) 3183 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 3184 3185 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 3186 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 3187 3188 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 3189 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 3190 3191 if (ClassTemplatePartialSpecializationDecl *PartialSpec 3192 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 3193 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 3194 PartialSpec); 3195 3196 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 3197 if (!Field->getDeclName()) { 3198 // This is an unnamed field. 3199 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 3200 cast<FieldDecl>(D); 3201 } 3202 } 3203 3204 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 3205 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 3206 3207 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 3208 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 3209 3210 return D->getDeclName() && isa<NamedDecl>(Other) && 3211 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 3212 } 3213 3214 template<typename ForwardIterator> 3215 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 3216 NamedDecl *D, 3217 ForwardIterator first, 3218 ForwardIterator last) { 3219 for (; first != last; ++first) 3220 if (isInstantiationOf(Ctx, D, *first)) 3221 return cast<NamedDecl>(*first); 3222 3223 return 0; 3224 } 3225 3226 /// \brief Finds the instantiation of the given declaration context 3227 /// within the current instantiation. 3228 /// 3229 /// \returns NULL if there was an error 3230 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 3231 const MultiLevelTemplateArgumentList &TemplateArgs) { 3232 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 3233 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 3234 return cast_or_null<DeclContext>(ID); 3235 } else return DC; 3236 } 3237 3238 /// \brief Find the instantiation of the given declaration within the 3239 /// current instantiation. 3240 /// 3241 /// This routine is intended to be used when \p D is a declaration 3242 /// referenced from within a template, that needs to mapped into the 3243 /// corresponding declaration within an instantiation. For example, 3244 /// given: 3245 /// 3246 /// \code 3247 /// template<typename T> 3248 /// struct X { 3249 /// enum Kind { 3250 /// KnownValue = sizeof(T) 3251 /// }; 3252 /// 3253 /// bool getKind() const { return KnownValue; } 3254 /// }; 3255 /// 3256 /// template struct X<int>; 3257 /// \endcode 3258 /// 3259 /// In the instantiation of X<int>::getKind(), we need to map the 3260 /// EnumConstantDecl for KnownValue (which refers to 3261 /// X<T>::\<Kind>\::KnownValue) to its instantiation 3262 /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs 3263 /// this mapping from within the instantiation of X<int>. 3264 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 3265 const MultiLevelTemplateArgumentList &TemplateArgs) { 3266 DeclContext *ParentDC = D->getDeclContext(); 3267 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 3268 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 3269 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 3270 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 3271 // D is a local of some kind. Look into the map of local 3272 // declarations to their instantiations. 3273 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 3274 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 3275 = CurrentInstantiationScope->findInstantiationOf(D); 3276 3277 if (Found) { 3278 if (Decl *FD = Found->dyn_cast<Decl *>()) 3279 return cast<NamedDecl>(FD); 3280 3281 unsigned PackIdx = ArgumentPackSubstitutionIndex; 3282 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 3283 } 3284 3285 // If we didn't find the decl, then we must have a label decl that hasn't 3286 // been found yet. Lazily instantiate it and return it now. 3287 assert(isa<LabelDecl>(D)); 3288 3289 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 3290 assert(Inst && "Failed to instantiate label??"); 3291 3292 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 3293 return cast<LabelDecl>(Inst); 3294 } 3295 3296 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 3297 if (!Record->isDependentContext()) 3298 return D; 3299 3300 // Determine whether this record is the "templated" declaration describing 3301 // a class template or class template partial specialization. 3302 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 3303 if (ClassTemplate) 3304 ClassTemplate = ClassTemplate->getCanonicalDecl(); 3305 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 3306 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 3307 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 3308 3309 // Walk the current context to find either the record or an instantiation of 3310 // it. 3311 DeclContext *DC = CurContext; 3312 while (!DC->isFileContext()) { 3313 // If we're performing substitution while we're inside the template 3314 // definition, we'll find our own context. We're done. 3315 if (DC->Equals(Record)) 3316 return Record; 3317 3318 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 3319 // Check whether we're in the process of instantiating a class template 3320 // specialization of the template we're mapping. 3321 if (ClassTemplateSpecializationDecl *InstSpec 3322 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 3323 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 3324 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 3325 return InstRecord; 3326 } 3327 3328 // Check whether we're in the process of instantiating a member class. 3329 if (isInstantiationOf(Record, InstRecord)) 3330 return InstRecord; 3331 } 3332 3333 3334 // Move to the outer template scope. 3335 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 3336 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 3337 DC = FD->getLexicalDeclContext(); 3338 continue; 3339 } 3340 } 3341 3342 DC = DC->getParent(); 3343 } 3344 3345 // Fall through to deal with other dependent record types (e.g., 3346 // anonymous unions in class templates). 3347 } 3348 3349 if (!ParentDC->isDependentContext()) 3350 return D; 3351 3352 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 3353 if (!ParentDC) 3354 return 0; 3355 3356 if (ParentDC != D->getDeclContext()) { 3357 // We performed some kind of instantiation in the parent context, 3358 // so now we need to look into the instantiated parent context to 3359 // find the instantiation of the declaration D. 3360 3361 // If our context used to be dependent, we may need to instantiate 3362 // it before performing lookup into that context. 3363 bool IsBeingInstantiated = false; 3364 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 3365 if (!Spec->isDependentContext()) { 3366 QualType T = Context.getTypeDeclType(Spec); 3367 const RecordType *Tag = T->getAs<RecordType>(); 3368 assert(Tag && "type of non-dependent record is not a RecordType"); 3369 if (Tag->isBeingDefined()) 3370 IsBeingInstantiated = true; 3371 if (!Tag->isBeingDefined() && 3372 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 3373 return 0; 3374 3375 ParentDC = Tag->getDecl(); 3376 } 3377 } 3378 3379 NamedDecl *Result = 0; 3380 if (D->getDeclName()) { 3381 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 3382 Result = findInstantiationOf(Context, D, Found.first, Found.second); 3383 } else { 3384 // Since we don't have a name for the entity we're looking for, 3385 // our only option is to walk through all of the declarations to 3386 // find that name. This will occur in a few cases: 3387 // 3388 // - anonymous struct/union within a template 3389 // - unnamed class/struct/union/enum within a template 3390 // 3391 // FIXME: Find a better way to find these instantiations! 3392 Result = findInstantiationOf(Context, D, 3393 ParentDC->decls_begin(), 3394 ParentDC->decls_end()); 3395 } 3396 3397 if (!Result) { 3398 if (isa<UsingShadowDecl>(D)) { 3399 // UsingShadowDecls can instantiate to nothing because of using hiding. 3400 } else if (Diags.hasErrorOccurred()) { 3401 // We've already complained about something, so most likely this 3402 // declaration failed to instantiate. There's no point in complaining 3403 // further, since this is normal in invalid code. 3404 } else if (IsBeingInstantiated) { 3405 // The class in which this member exists is currently being 3406 // instantiated, and we haven't gotten around to instantiating this 3407 // member yet. This can happen when the code uses forward declarations 3408 // of member classes, and introduces ordering dependencies via 3409 // template instantiation. 3410 Diag(Loc, diag::err_member_not_yet_instantiated) 3411 << D->getDeclName() 3412 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 3413 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 3414 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 3415 // This enumeration constant was found when the template was defined, 3416 // but can't be found in the instantiation. This can happen if an 3417 // unscoped enumeration member is explicitly specialized. 3418 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 3419 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 3420 TemplateArgs)); 3421 assert(Spec->getTemplateSpecializationKind() == 3422 TSK_ExplicitSpecialization); 3423 Diag(Loc, diag::err_enumerator_does_not_exist) 3424 << D->getDeclName() 3425 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 3426 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 3427 << Context.getTypeDeclType(Spec); 3428 } else { 3429 // We should have found something, but didn't. 3430 llvm_unreachable("Unable to find instantiation of declaration!"); 3431 } 3432 } 3433 3434 D = Result; 3435 } 3436 3437 return D; 3438 } 3439 3440 /// \brief Performs template instantiation for all implicit template 3441 /// instantiations we have seen until this point. 3442 void Sema::PerformPendingInstantiations(bool LocalOnly) { 3443 // Load pending instantiations from the external source. 3444 if (!LocalOnly && ExternalSource) { 3445 SmallVector<PendingImplicitInstantiation, 4> Pending; 3446 ExternalSource->ReadPendingInstantiations(Pending); 3447 PendingInstantiations.insert(PendingInstantiations.begin(), 3448 Pending.begin(), Pending.end()); 3449 } 3450 3451 while (!PendingLocalImplicitInstantiations.empty() || 3452 (!LocalOnly && !PendingInstantiations.empty())) { 3453 PendingImplicitInstantiation Inst; 3454 3455 if (PendingLocalImplicitInstantiations.empty()) { 3456 Inst = PendingInstantiations.front(); 3457 PendingInstantiations.pop_front(); 3458 } else { 3459 Inst = PendingLocalImplicitInstantiations.front(); 3460 PendingLocalImplicitInstantiations.pop_front(); 3461 } 3462 3463 // Instantiate function definitions 3464 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 3465 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 3466 "instantiating function definition"); 3467 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 3468 TSK_ExplicitInstantiationDefinition; 3469 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 3470 DefinitionRequired); 3471 continue; 3472 } 3473 3474 // Instantiate static data member definitions. 3475 VarDecl *Var = cast<VarDecl>(Inst.first); 3476 assert(Var->isStaticDataMember() && "Not a static data member?"); 3477 3478 // Don't try to instantiate declarations if the most recent redeclaration 3479 // is invalid. 3480 if (Var->getMostRecentDecl()->isInvalidDecl()) 3481 continue; 3482 3483 // Check if the most recent declaration has changed the specialization kind 3484 // and removed the need for implicit instantiation. 3485 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 3486 case TSK_Undeclared: 3487 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 3488 case TSK_ExplicitInstantiationDeclaration: 3489 case TSK_ExplicitSpecialization: 3490 continue; // No longer need to instantiate this type. 3491 case TSK_ExplicitInstantiationDefinition: 3492 // We only need an instantiation if the pending instantiation *is* the 3493 // explicit instantiation. 3494 if (Var != Var->getMostRecentDecl()) continue; 3495 case TSK_ImplicitInstantiation: 3496 break; 3497 } 3498 3499 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(), 3500 "instantiating static data member " 3501 "definition"); 3502 3503 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 3504 TSK_ExplicitInstantiationDefinition; 3505 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true, 3506 DefinitionRequired); 3507 } 3508 } 3509 3510 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 3511 const MultiLevelTemplateArgumentList &TemplateArgs) { 3512 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 3513 E = Pattern->ddiag_end(); I != E; ++I) { 3514 DependentDiagnostic *DD = *I; 3515 3516 switch (DD->getKind()) { 3517 case DependentDiagnostic::Access: 3518 HandleDependentAccessCheck(*DD, TemplateArgs); 3519 break; 3520 } 3521 } 3522 } 3523