SemaTemplateInstantiateDecl.cpp revision 90fc78e83a12eaee80a3d0a174429529b7f82e85
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 "Sema.h" 13#include "clang/AST/ASTConsumer.h" 14#include "clang/AST/ASTContext.h" 15#include "clang/AST/DeclTemplate.h" 16#include "clang/AST/DeclVisitor.h" 17#include "clang/AST/Expr.h" 18#include "llvm/Support/Compiler.h" 19 20using namespace clang; 21 22namespace { 23 class VISIBILITY_HIDDEN TemplateDeclInstantiator 24 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 25 Sema &SemaRef; 26 DeclContext *Owner; 27 const TemplateArgumentList &TemplateArgs; 28 29 public: 30 typedef Sema::OwningExprResult OwningExprResult; 31 32 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 33 const TemplateArgumentList &TemplateArgs) 34 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 35 36 // FIXME: Once we get closer to completion, replace these manually-written 37 // declarations with automatically-generated ones from 38 // clang/AST/DeclNodes.def. 39 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 40 Decl *VisitNamespaceDecl(NamespaceDecl *D); 41 Decl *VisitTypedefDecl(TypedefDecl *D); 42 Decl *VisitVarDecl(VarDecl *D); 43 Decl *VisitFieldDecl(FieldDecl *D); 44 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 45 Decl *VisitEnumDecl(EnumDecl *D); 46 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 47 Decl *VisitFunctionDecl(FunctionDecl *D); 48 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 49 Decl *VisitCXXMethodDecl(CXXMethodDecl *D); 50 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 51 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 52 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 53 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 54 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D); 55 56 // Base case. FIXME: Remove once we can instantiate everything. 57 Decl *VisitDecl(Decl *) { 58 assert(false && "Template instantiation of unknown declaration kind!"); 59 return 0; 60 } 61 62 // Helper functions for instantiating methods. 63 QualType InstantiateFunctionType(FunctionDecl *D, 64 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 65 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 66 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 67 }; 68} 69 70Decl * 71TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 72 assert(false && "Translation units cannot be instantiated"); 73 return D; 74} 75 76Decl * 77TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 78 assert(false && "Namespaces cannot be instantiated"); 79 return D; 80} 81 82Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 83 bool Invalid = false; 84 QualType T = D->getUnderlyingType(); 85 if (T->isDependentType()) { 86 T = SemaRef.InstantiateType(T, TemplateArgs, 87 D->getLocation(), D->getDeclName()); 88 if (T.isNull()) { 89 Invalid = true; 90 T = SemaRef.Context.IntTy; 91 } 92 } 93 94 // Create the new typedef 95 TypedefDecl *Typedef 96 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 97 D->getIdentifier(), T); 98 if (Invalid) 99 Typedef->setInvalidDecl(); 100 101 Owner->addDecl(Typedef); 102 103 return Typedef; 104} 105 106Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 107 // Instantiate the type of the declaration 108 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs, 109 D->getTypeSpecStartLoc(), 110 D->getDeclName()); 111 if (T.isNull()) 112 return 0; 113 114 // Build the instantiated declaration 115 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 116 D->getLocation(), D->getIdentifier(), 117 T, D->getStorageClass(), 118 D->getTypeSpecStartLoc()); 119 Var->setThreadSpecified(D->isThreadSpecified()); 120 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 121 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 122 123 // If we are instantiating a static data member defined 124 // out-of-line, the instantiation will have the same lexical 125 // context (which will be a namespace scope) as the template. 126 if (D->isOutOfLine()) 127 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 128 129 // FIXME: In theory, we could have a previous declaration for variables that 130 // are not static data members. 131 bool Redeclaration = false; 132 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration); 133 134 if (D->isOutOfLine()) { 135 D->getLexicalDeclContext()->addDecl(Var); 136 Owner->makeDeclVisibleInContext(Var); 137 } else { 138 Owner->addDecl(Var); 139 } 140 141 if (D->getInit()) { 142 OwningExprResult Init 143 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs); 144 if (Init.isInvalid()) 145 Var->setInvalidDecl(); 146 else 147 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 148 D->hasCXXDirectInitializer()); 149 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 150 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 151 152 // Link instantiations of static data members back to the template from 153 // which they were instantiated. 154 if (Var->isStaticDataMember()) 155 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D); 156 157 return Var; 158} 159 160Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 161 bool Invalid = false; 162 QualType T = D->getType(); 163 if (T->isDependentType()) { 164 T = SemaRef.InstantiateType(T, TemplateArgs, 165 D->getLocation(), D->getDeclName()); 166 if (!T.isNull() && T->isFunctionType()) { 167 // C++ [temp.arg.type]p3: 168 // If a declaration acquires a function type through a type 169 // dependent on a template-parameter and this causes a 170 // declaration that does not use the syntactic form of a 171 // function declarator to have function type, the program is 172 // ill-formed. 173 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 174 << T; 175 T = QualType(); 176 Invalid = true; 177 } 178 } 179 180 Expr *BitWidth = D->getBitWidth(); 181 if (Invalid) 182 BitWidth = 0; 183 else if (BitWidth) { 184 // The bit-width expression is not potentially evaluated. 185 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 186 187 OwningExprResult InstantiatedBitWidth 188 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs); 189 if (InstantiatedBitWidth.isInvalid()) { 190 Invalid = true; 191 BitWidth = 0; 192 } else 193 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 194 } 195 196 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T, 197 cast<RecordDecl>(Owner), 198 D->getLocation(), 199 D->isMutable(), 200 BitWidth, 201 D->getTypeSpecStartLoc(), 202 D->getAccess(), 203 0); 204 if (Field) { 205 if (Invalid) 206 Field->setInvalidDecl(); 207 208 Owner->addDecl(Field); 209 } 210 211 return Field; 212} 213 214Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 215 Expr *AssertExpr = D->getAssertExpr(); 216 217 // The expression in a static assertion is not potentially evaluated. 218 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 219 220 OwningExprResult InstantiatedAssertExpr 221 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs); 222 if (InstantiatedAssertExpr.isInvalid()) 223 return 0; 224 225 OwningExprResult Message = SemaRef.Clone(D->getMessage()); 226 Decl *StaticAssert 227 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 228 move(InstantiatedAssertExpr), 229 move(Message)).getAs<Decl>(); 230 return StaticAssert; 231} 232 233Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 234 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 235 D->getLocation(), D->getIdentifier(), 236 D->getTagKeywordLoc(), 237 /*PrevDecl=*/0); 238 Enum->setInstantiationOfMemberEnum(D); 239 Enum->setAccess(D->getAccess()); 240 Owner->addDecl(Enum); 241 Enum->startDefinition(); 242 243 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 244 245 EnumConstantDecl *LastEnumConst = 0; 246 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 247 ECEnd = D->enumerator_end(); 248 EC != ECEnd; ++EC) { 249 // The specified value for the enumerator. 250 OwningExprResult Value = SemaRef.Owned((Expr *)0); 251 if (Expr *UninstValue = EC->getInitExpr()) { 252 // The enumerator's value expression is not potentially evaluated. 253 EnterExpressionEvaluationContext Unevaluated(SemaRef, 254 Action::Unevaluated); 255 256 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs); 257 } 258 259 // Drop the initial value and continue. 260 bool isInvalid = false; 261 if (Value.isInvalid()) { 262 Value = SemaRef.Owned((Expr *)0); 263 isInvalid = true; 264 } 265 266 EnumConstantDecl *EnumConst 267 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 268 EC->getLocation(), EC->getIdentifier(), 269 move(Value)); 270 271 if (isInvalid) { 272 if (EnumConst) 273 EnumConst->setInvalidDecl(); 274 Enum->setInvalidDecl(); 275 } 276 277 if (EnumConst) { 278 Enum->addDecl(EnumConst); 279 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 280 LastEnumConst = EnumConst; 281 } 282 } 283 284 // FIXME: Fixup LBraceLoc and RBraceLoc 285 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 286 Sema::DeclPtrTy::make(Enum), 287 &Enumerators[0], Enumerators.size()); 288 289 return Enum; 290} 291 292Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 293 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 294 return 0; 295} 296 297Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 298 CXXRecordDecl *PrevDecl = 0; 299 if (D->isInjectedClassName()) 300 PrevDecl = cast<CXXRecordDecl>(Owner); 301 302 CXXRecordDecl *Record 303 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 304 D->getLocation(), D->getIdentifier(), 305 D->getTagKeywordLoc(), PrevDecl); 306 Record->setImplicit(D->isImplicit()); 307 Record->setAccess(D->getAccess()); 308 if (!D->isInjectedClassName()) 309 Record->setInstantiationOfMemberClass(D); 310 311 Owner->addDecl(Record); 312 return Record; 313} 314 315Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 316 // Check whether there is already a function template specialization for 317 // this declaration. 318 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 319 void *InsertPos = 0; 320 if (FunctionTemplate) { 321 llvm::FoldingSetNodeID ID; 322 FunctionTemplateSpecializationInfo::Profile(ID, 323 TemplateArgs.getFlatArgumentList(), 324 TemplateArgs.flat_size(), 325 SemaRef.Context); 326 327 FunctionTemplateSpecializationInfo *Info 328 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 329 InsertPos); 330 331 // If we already have a function template specialization, return it. 332 if (Info) 333 return Info->Function; 334 } 335 336 Sema::LocalInstantiationScope Scope(SemaRef); 337 338 llvm::SmallVector<ParmVarDecl *, 4> Params; 339 QualType T = InstantiateFunctionType(D, Params); 340 if (T.isNull()) 341 return 0; 342 343 // Build the instantiated method declaration. 344 FunctionDecl *Function 345 = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(), 346 D->getDeclName(), T, D->getStorageClass(), 347 D->isInline(), D->hasWrittenPrototype(), 348 D->getTypeSpecStartLoc()); 349 350 // FIXME: friend functions 351 352 // Attach the parameters 353 for (unsigned P = 0; P < Params.size(); ++P) 354 Params[P]->setOwningFunction(Function); 355 Function->setParams(SemaRef.Context, Params.data(), Params.size()); 356 357 if (InitFunctionInstantiation(Function, D)) 358 Function->setInvalidDecl(); 359 360 bool Redeclaration = false; 361 bool OverloadableAttrRequired = false; 362 NamedDecl *PrevDecl = 0; 363 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration, 364 /*FIXME:*/OverloadableAttrRequired); 365 366 if (FunctionTemplate) { 367 // Record this function template specialization. 368 Function->setFunctionTemplateSpecialization(SemaRef.Context, 369 FunctionTemplate, 370 &TemplateArgs, 371 InsertPos); 372 } 373 374 return Function; 375} 376 377Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 378 // FIXME: Look for existing, explicit specializations. 379 Sema::LocalInstantiationScope Scope(SemaRef); 380 381 llvm::SmallVector<ParmVarDecl *, 4> Params; 382 QualType T = InstantiateFunctionType(D, Params); 383 if (T.isNull()) 384 return 0; 385 386 // Build the instantiated method declaration. 387 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 388 CXXMethodDecl *Method 389 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 390 D->getDeclName(), T, D->isStatic(), 391 D->isInline()); 392 Method->setInstantiationOfMemberFunction(D); 393 394 // If we are instantiating a member function defined 395 // out-of-line, the instantiation will have the same lexical 396 // context (which will be a namespace scope) as the template. 397 if (D->isOutOfLine()) 398 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 399 400 // Attach the parameters 401 for (unsigned P = 0; P < Params.size(); ++P) 402 Params[P]->setOwningFunction(Method); 403 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 404 405 if (InitMethodInstantiation(Method, D)) 406 Method->setInvalidDecl(); 407 408 NamedDecl *PrevDecl 409 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(), 410 Sema::LookupOrdinaryName, true); 411 // In C++, the previous declaration we find might be a tag type 412 // (class or enum). In this case, the new declaration will hide the 413 // tag type. Note that this does does not apply if we're declaring a 414 // typedef (C++ [dcl.typedef]p4). 415 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 416 PrevDecl = 0; 417 bool Redeclaration = false; 418 bool OverloadableAttrRequired = false; 419 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration, 420 /*FIXME:*/OverloadableAttrRequired); 421 422 if (!Method->isInvalidDecl() || !PrevDecl) 423 Owner->addDecl(Method); 424 return Method; 425} 426 427Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 428 // FIXME: Look for existing, explicit specializations. 429 Sema::LocalInstantiationScope Scope(SemaRef); 430 431 llvm::SmallVector<ParmVarDecl *, 4> Params; 432 QualType T = InstantiateFunctionType(D, Params); 433 if (T.isNull()) 434 return 0; 435 436 // Build the instantiated method declaration. 437 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 438 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 439 DeclarationName Name 440 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 441 SemaRef.Context.getCanonicalType(ClassTy)); 442 CXXConstructorDecl *Constructor 443 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(), 444 Name, T, D->isExplicit(), D->isInline(), 445 false); 446 Constructor->setInstantiationOfMemberFunction(D); 447 448 // Attach the parameters 449 for (unsigned P = 0; P < Params.size(); ++P) 450 Params[P]->setOwningFunction(Constructor); 451 Constructor->setParams(SemaRef.Context, Params.data(), Params.size()); 452 453 if (InitMethodInstantiation(Constructor, D)) 454 Constructor->setInvalidDecl(); 455 456 NamedDecl *PrevDecl 457 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true); 458 459 // In C++, the previous declaration we find might be a tag type 460 // (class or enum). In this case, the new declaration will hide the 461 // tag type. Note that this does does not apply if we're declaring a 462 // typedef (C++ [dcl.typedef]p4). 463 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 464 PrevDecl = 0; 465 bool Redeclaration = false; 466 bool OverloadableAttrRequired = false; 467 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration, 468 /*FIXME:*/OverloadableAttrRequired); 469 470 Record->addedConstructor(SemaRef.Context, Constructor); 471 Owner->addDecl(Constructor); 472 return Constructor; 473} 474 475Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 476 // FIXME: Look for existing, explicit specializations. 477 Sema::LocalInstantiationScope Scope(SemaRef); 478 479 llvm::SmallVector<ParmVarDecl *, 4> Params; 480 QualType T = InstantiateFunctionType(D, Params); 481 if (T.isNull()) 482 return 0; 483 assert(Params.size() == 0 && "Destructor with parameters?"); 484 485 // Build the instantiated destructor declaration. 486 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 487 QualType ClassTy = 488 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record)); 489 CXXDestructorDecl *Destructor 490 = CXXDestructorDecl::Create(SemaRef.Context, Record, 491 D->getLocation(), 492 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy), 493 T, D->isInline(), false); 494 Destructor->setInstantiationOfMemberFunction(D); 495 if (InitMethodInstantiation(Destructor, D)) 496 Destructor->setInvalidDecl(); 497 498 bool Redeclaration = false; 499 bool OverloadableAttrRequired = false; 500 NamedDecl *PrevDecl = 0; 501 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration, 502 /*FIXME:*/OverloadableAttrRequired); 503 Owner->addDecl(Destructor); 504 return Destructor; 505} 506 507Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 508 // FIXME: Look for existing, explicit specializations. 509 Sema::LocalInstantiationScope Scope(SemaRef); 510 511 llvm::SmallVector<ParmVarDecl *, 4> Params; 512 QualType T = InstantiateFunctionType(D, Params); 513 if (T.isNull()) 514 return 0; 515 assert(Params.size() == 0 && "Destructor with parameters?"); 516 517 // Build the instantiated conversion declaration. 518 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 519 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 520 QualType ConvTy 521 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType()); 522 CXXConversionDecl *Conversion 523 = CXXConversionDecl::Create(SemaRef.Context, Record, 524 D->getLocation(), 525 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy), 526 T, D->isInline(), D->isExplicit()); 527 Conversion->setInstantiationOfMemberFunction(D); 528 if (InitMethodInstantiation(Conversion, D)) 529 Conversion->setInvalidDecl(); 530 531 bool Redeclaration = false; 532 bool OverloadableAttrRequired = false; 533 NamedDecl *PrevDecl = 0; 534 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration, 535 /*FIXME:*/OverloadableAttrRequired); 536 Owner->addDecl(Conversion); 537 return Conversion; 538} 539 540ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 541 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs, 542 D->getLocation(), D->getDeclName()); 543 if (OrigT.isNull()) 544 return 0; 545 546 QualType T = SemaRef.adjustParameterType(OrigT); 547 548 if (D->getDefaultArg()) { 549 // FIXME: Leave a marker for "uninstantiated" default 550 // arguments. They only get instantiated on demand at the call 551 // site. 552 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning, 553 "sorry, dropping default argument during template instantiation"); 554 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID) 555 << D->getDefaultArg()->getSourceRange(); 556 } 557 558 // Allocate the parameter 559 ParmVarDecl *Param = 0; 560 if (T == OrigT) 561 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 562 D->getIdentifier(), T, D->getStorageClass(), 563 0); 564 else 565 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner, 566 D->getLocation(), D->getIdentifier(), 567 T, OrigT, D->getStorageClass(), 0); 568 569 // Note: we don't try to instantiate function parameters until after 570 // we've instantiated the function's type. Therefore, we don't have 571 // to check for 'void' parameter types here. 572 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 573 return Param; 574} 575 576Decl * 577TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { 578 // Since parameter types can decay either before or after 579 // instantiation, we simply treat OriginalParmVarDecls as 580 // ParmVarDecls the same way, and create one or the other depending 581 // on what happens after template instantiation. 582 return VisitParmVarDecl(D); 583} 584 585Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner, 586 const TemplateArgumentList &TemplateArgs) { 587 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 588 return Instantiator.Visit(D); 589} 590 591/// \brief Instantiates the type of the given function, including 592/// instantiating all of the function parameters. 593/// 594/// \param D The function that we will be instantiated 595/// 596/// \param Params the instantiated parameter declarations 597 598/// \returns the instantiated function's type if successfull, a NULL 599/// type if there was an error. 600QualType 601TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D, 602 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 603 bool InvalidDecl = false; 604 605 // Instantiate the function parameters 606 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 607 llvm::SmallVector<QualType, 4> ParamTys; 608 for (FunctionDecl::param_iterator P = D->param_begin(), 609 PEnd = D->param_end(); 610 P != PEnd; ++P) { 611 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 612 if (PInst->getType()->isVoidType()) { 613 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 614 PInst->setInvalidDecl(); 615 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 616 PInst->getType(), 617 diag::err_abstract_type_in_decl, 618 Sema::AbstractParamType)) 619 PInst->setInvalidDecl(); 620 621 Params.push_back(PInst); 622 ParamTys.push_back(PInst->getType()); 623 624 if (PInst->isInvalidDecl()) 625 InvalidDecl = true; 626 } else 627 InvalidDecl = true; 628 } 629 630 // FIXME: Deallocate dead declarations. 631 if (InvalidDecl) 632 return QualType(); 633 634 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType(); 635 assert(Proto && "Missing prototype?"); 636 QualType ResultType 637 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs, 638 D->getLocation(), D->getDeclName()); 639 if (ResultType.isNull()) 640 return QualType(); 641 642 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 643 Proto->isVariadic(), Proto->getTypeQuals(), 644 D->getLocation(), D->getDeclName()); 645} 646 647/// \brief Initializes the common fields of an instantiation function 648/// declaration (New) from the corresponding fields of its template (Tmpl). 649/// 650/// \returns true if there was an error 651bool 652TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 653 FunctionDecl *Tmpl) { 654 if (Tmpl->isDeleted()) 655 New->setDeleted(); 656 657 // If we are performing substituting explicitly-specified template arguments 658 // or deduced template arguments into a function template and we reach this 659 // point, we are now past the point where SFINAE applies and have committed 660 // to keeping the new function template specialization. We therefore 661 // convert the active template instantiation for the function template 662 // into a template instantiation for this specific function template 663 // specialization, which is not a SFINAE context, so that we diagnose any 664 // further errors in the declaration itself. 665 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 666 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 667 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 668 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 669 if (FunctionTemplateDecl *FunTmpl 670 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 671 assert(FunTmpl->getTemplatedDecl() == Tmpl && 672 "Deduction from the wrong function template?"); 673 (void) FunTmpl; 674 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 675 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 676 } 677 } 678 679 return false; 680} 681 682/// \brief Initializes common fields of an instantiated method 683/// declaration (New) from the corresponding fields of its template 684/// (Tmpl). 685/// 686/// \returns true if there was an error 687bool 688TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 689 CXXMethodDecl *Tmpl) { 690 if (InitFunctionInstantiation(New, Tmpl)) 691 return true; 692 693 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 694 New->setAccess(Tmpl->getAccess()); 695 if (Tmpl->isVirtualAsWritten()) { 696 New->setVirtualAsWritten(true); 697 Record->setAggregate(false); 698 Record->setPOD(false); 699 Record->setPolymorphic(true); 700 } 701 if (Tmpl->isPure()) { 702 New->setPure(); 703 Record->setAbstract(true); 704 } 705 706 // FIXME: attributes 707 // FIXME: New needs a pointer to Tmpl 708 return false; 709} 710 711/// \brief Instantiate the definition of the given function from its 712/// template. 713/// 714/// \param PointOfInstantiation the point at which the instantiation was 715/// required. Note that this is not precisely a "point of instantiation" 716/// for the function, but it's close. 717/// 718/// \param Function the already-instantiated declaration of a 719/// function template specialization or member function of a class template 720/// specialization. 721/// 722/// \param Recursive if true, recursively instantiates any functions that 723/// are required by this instantiation. 724void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 725 FunctionDecl *Function, 726 bool Recursive) { 727 if (Function->isInvalidDecl()) 728 return; 729 730 assert(!Function->getBody() && "Already instantiated!"); 731 732 // Find the function body that we'll be substituting. 733 const FunctionDecl *PatternDecl = 0; 734 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) 735 PatternDecl = Primary->getTemplatedDecl(); 736 else 737 PatternDecl = Function->getInstantiatedFromMemberFunction(); 738 Stmt *Pattern = 0; 739 if (PatternDecl) 740 Pattern = PatternDecl->getBody(PatternDecl); 741 742 if (!Pattern) 743 return; 744 745 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 746 if (Inst) 747 return; 748 749 // If we're performing recursive template instantiation, create our own 750 // queue of pending implicit instantiations that we will instantiate later, 751 // while we're still within our own instantiation context. 752 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 753 if (Recursive) 754 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 755 756 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 757 758 // Introduce a new scope where local variable instantiations will be 759 // recorded. 760 LocalInstantiationScope Scope(*this); 761 762 // Introduce the instantiated function parameters into the local 763 // instantiation scope. 764 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 765 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 766 Function->getParamDecl(I)); 767 768 // Enter the scope of this instantiation. We don't use 769 // PushDeclContext because we don't have a scope. 770 DeclContext *PreviousContext = CurContext; 771 CurContext = Function; 772 773 // Instantiate the function body. 774 OwningStmtResult Body 775 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function)); 776 777 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 778 /*IsInstantiation=*/true); 779 780 CurContext = PreviousContext; 781 782 DeclGroupRef DG(Function); 783 Consumer.HandleTopLevelDecl(DG); 784 785 if (Recursive) { 786 // Instantiate any pending implicit instantiations found during the 787 // instantiation of this template. 788 PerformPendingImplicitInstantiations(); 789 790 // Restore the set of pending implicit instantiations. 791 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 792 } 793} 794 795/// \brief Instantiate the definition of the given variable from its 796/// template. 797/// 798/// \param PointOfInstantiation the point at which the instantiation was 799/// required. Note that this is not precisely a "point of instantiation" 800/// for the function, but it's close. 801/// 802/// \param Var the already-instantiated declaration of a static member 803/// variable of a class template specialization. 804/// 805/// \param Recursive if true, recursively instantiates any functions that 806/// are required by this instantiation. 807void Sema::InstantiateStaticDataMemberDefinition( 808 SourceLocation PointOfInstantiation, 809 VarDecl *Var, 810 bool Recursive) { 811 if (Var->isInvalidDecl()) 812 return; 813 814 // Find the out-of-line definition of this static data member. 815 // FIXME: Do we have to look for specializations separately? 816 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 817 bool FoundOutOfLineDef = false; 818 assert(Def && "This data member was not instantiated from a template?"); 819 assert(Def->isStaticDataMember() && "Not a static data member?"); 820 for (VarDecl::redecl_iterator RD = Def->redecls_begin(), 821 RDEnd = Def->redecls_end(); 822 RD != RDEnd; ++RD) { 823 if (RD->getLexicalDeclContext()->isFileContext()) { 824 Def = *RD; 825 FoundOutOfLineDef = true; 826 } 827 } 828 829 if (!FoundOutOfLineDef) { 830 // We did not find an out-of-line definition of this static data member, 831 // so we won't perform any instantiation. Rather, we rely on the user to 832 // instantiate this definition (or provide a specialization for it) in 833 // another translation unit. 834 return; 835 } 836 837 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 838 if (Inst) 839 return; 840 841 // If we're performing recursive template instantiation, create our own 842 // queue of pending implicit instantiations that we will instantiate later, 843 // while we're still within our own instantiation context. 844 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 845 if (Recursive) 846 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 847 848 // Enter the scope of this instantiation. We don't use 849 // PushDeclContext because we don't have a scope. 850 DeclContext *PreviousContext = CurContext; 851 CurContext = Var->getDeclContext(); 852 853#if 0 854 // Instantiate the initializer of this static data member. 855 OwningExprResult Init 856 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var)); 857 if (Init.isInvalid()) { 858 // If instantiation of the initializer failed, mark the declaration invalid 859 // and don't instantiate anything else that was triggered by this 860 // instantiation. 861 Var->setInvalidDecl(); 862 863 // Restore the set of pending implicit instantiations. 864 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 865 866 return; 867 } 868 869 // Type-check the initializer. 870 if (Init.get()) 871 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init), 872 Def->hasCXXDirectInitializer()); 873 else 874 ActOnUninitializedDecl(DeclPtrTy::make(Var), false); 875#else 876 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(), 877 getTemplateInstantiationArgs(Var))); 878#endif 879 880 CurContext = PreviousContext; 881 882 if (Var) { 883 DeclGroupRef DG(Var); 884 Consumer.HandleTopLevelDecl(DG); 885 } 886 887 if (Recursive) { 888 // Instantiate any pending implicit instantiations found during the 889 // instantiation of this template. 890 PerformPendingImplicitInstantiations(); 891 892 // Restore the set of pending implicit instantiations. 893 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 894 } 895} 896 897static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 898 if (D->getKind() != Other->getKind()) 899 return false; 900 901 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 902 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl() 903 == D->getCanonicalDecl(); 904 905 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 906 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl() 907 == D->getCanonicalDecl(); 908 909 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 910 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl() 911 == D->getCanonicalDecl(); 912 913 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 914 if (Var->isStaticDataMember()) 915 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl() 916 == D->getCanonicalDecl(); 917 918 // FIXME: How can we find instantiations of anonymous unions? 919 920 return D->getDeclName() && isa<NamedDecl>(Other) && 921 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 922} 923 924template<typename ForwardIterator> 925static NamedDecl *findInstantiationOf(ASTContext &Ctx, 926 NamedDecl *D, 927 ForwardIterator first, 928 ForwardIterator last) { 929 for (; first != last; ++first) 930 if (isInstantiationOf(Ctx, D, *first)) 931 return cast<NamedDecl>(*first); 932 933 return 0; 934} 935 936/// \brief Find the instantiation of the given declaration within the 937/// current instantiation. 938/// 939/// This routine is intended to be used when \p D is a declaration 940/// referenced from within a template, that needs to mapped into the 941/// corresponding declaration within an instantiation. For example, 942/// given: 943/// 944/// \code 945/// template<typename T> 946/// struct X { 947/// enum Kind { 948/// KnownValue = sizeof(T) 949/// }; 950/// 951/// bool getKind() const { return KnownValue; } 952/// }; 953/// 954/// template struct X<int>; 955/// \endcode 956/// 957/// In the instantiation of X<int>::getKind(), we need to map the 958/// EnumConstantDecl for KnownValue (which refers to 959/// X<T>::<Kind>::KnownValue) to its instantiation 960/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 961/// this mapping from within the instantiation of X<int>. 962NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) { 963 DeclContext *ParentDC = D->getDeclContext(); 964 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) { 965 // D is a local of some kind. Look into the map of local 966 // declarations to their instantiations. 967 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 968 } 969 970 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) { 971 ParentDecl = InstantiateCurrentDeclRef(ParentDecl); 972 if (!ParentDecl) 973 return 0; 974 975 ParentDC = cast<DeclContext>(ParentDecl); 976 } 977 978 if (ParentDC != D->getDeclContext()) { 979 // We performed some kind of instantiation in the parent context, 980 // so now we need to look into the instantiated parent context to 981 // find the instantiation of the declaration D. 982 NamedDecl *Result = 0; 983 if (D->getDeclName()) { 984 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 985 Result = findInstantiationOf(Context, D, Found.first, Found.second); 986 } else { 987 // Since we don't have a name for the entity we're looking for, 988 // our only option is to walk through all of the declarations to 989 // find that name. This will occur in a few cases: 990 // 991 // - anonymous struct/union within a template 992 // - unnamed class/struct/union/enum within a template 993 // 994 // FIXME: Find a better way to find these instantiations! 995 Result = findInstantiationOf(Context, D, 996 ParentDC->decls_begin(), 997 ParentDC->decls_end()); 998 } 999 assert(Result && "Unable to find instantiation of declaration!"); 1000 D = Result; 1001 } 1002 1003 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 1004 if (ClassTemplateDecl *ClassTemplate 1005 = Record->getDescribedClassTemplate()) { 1006 // When the declaration D was parsed, it referred to the current 1007 // instantiation. Therefore, look through the current context, 1008 // which contains actual instantiations, to find the 1009 // instantiation of the "current instantiation" that D refers 1010 // to. Alternatively, we could just instantiate the 1011 // injected-class-name with the current template arguments, but 1012 // such an instantiation is far more expensive. 1013 for (DeclContext *DC = CurContext; !DC->isFileContext(); 1014 DC = DC->getParent()) { 1015 if (ClassTemplateSpecializationDecl *Spec 1016 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 1017 if (Spec->getSpecializedTemplate()->getCanonicalDecl() 1018 == ClassTemplate->getCanonicalDecl()) 1019 return Spec; 1020 } 1021 1022 assert(false && 1023 "Unable to find declaration for the current instantiation"); 1024 } 1025 1026 return D; 1027} 1028 1029/// \brief Performs template instantiation for all implicit template 1030/// instantiations we have seen until this point. 1031void Sema::PerformPendingImplicitInstantiations() { 1032 while (!PendingImplicitInstantiations.empty()) { 1033 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front(); 1034 PendingImplicitInstantiations.pop_front(); 1035 1036 // Instantiate function definitions 1037 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 1038 if (!Function->getBody()) 1039 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 1040 continue; 1041 } 1042 1043 // Instantiate static data member definitions. 1044 VarDecl *Var = cast<VarDecl>(Inst.first); 1045 assert(Var->isStaticDataMember() && "Not a static data member?"); 1046 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 1047 } 1048} 1049