SemaTemplateInstantiateDecl.cpp revision b33fe2ff12676bff9db595fdf77e29014d7ba397
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 // FIXME: In theory, we could have a previous declaration for variables that 124 // are not static data members. 125 bool Redeclaration = false; 126 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration); 127 Owner->addDecl(Var); 128 129 if (D->getInit()) { 130 OwningExprResult Init 131 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs); 132 if (Init.isInvalid()) 133 Var->setInvalidDecl(); 134 else 135 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 136 D->hasCXXDirectInitializer()); 137 } else { 138 // FIXME: Call ActOnUninitializedDecl? (Not always) 139 } 140 141 return Var; 142} 143 144Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 145 bool Invalid = false; 146 QualType T = D->getType(); 147 if (T->isDependentType()) { 148 T = SemaRef.InstantiateType(T, TemplateArgs, 149 D->getLocation(), D->getDeclName()); 150 if (!T.isNull() && T->isFunctionType()) { 151 // C++ [temp.arg.type]p3: 152 // If a declaration acquires a function type through a type 153 // dependent on a template-parameter and this causes a 154 // declaration that does not use the syntactic form of a 155 // function declarator to have function type, the program is 156 // ill-formed. 157 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 158 << T; 159 T = QualType(); 160 Invalid = true; 161 } 162 } 163 164 Expr *BitWidth = D->getBitWidth(); 165 if (Invalid) 166 BitWidth = 0; 167 else if (BitWidth) { 168 // The bit-width expression is not potentially evaluated. 169 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 170 171 OwningExprResult InstantiatedBitWidth 172 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs); 173 if (InstantiatedBitWidth.isInvalid()) { 174 Invalid = true; 175 BitWidth = 0; 176 } else 177 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 178 } 179 180 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T, 181 cast<RecordDecl>(Owner), 182 D->getLocation(), 183 D->isMutable(), 184 BitWidth, 185 D->getAccess(), 186 0); 187 if (Field) { 188 if (Invalid) 189 Field->setInvalidDecl(); 190 191 Owner->addDecl(Field); 192 } 193 194 return Field; 195} 196 197Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 198 Expr *AssertExpr = D->getAssertExpr(); 199 200 // The expression in a static assertion is not potentially evaluated. 201 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 202 203 OwningExprResult InstantiatedAssertExpr 204 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs); 205 if (InstantiatedAssertExpr.isInvalid()) 206 return 0; 207 208 OwningExprResult Message = SemaRef.Clone(D->getMessage()); 209 Decl *StaticAssert 210 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 211 move(InstantiatedAssertExpr), 212 move(Message)).getAs<Decl>(); 213 return StaticAssert; 214} 215 216Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 217 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 218 D->getLocation(), D->getIdentifier(), 219 /*PrevDecl=*/0); 220 Enum->setInstantiationOfMemberEnum(D); 221 Enum->setAccess(D->getAccess()); 222 Owner->addDecl(Enum); 223 Enum->startDefinition(); 224 225 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 226 227 EnumConstantDecl *LastEnumConst = 0; 228 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 229 ECEnd = D->enumerator_end(); 230 EC != ECEnd; ++EC) { 231 // The specified value for the enumerator. 232 OwningExprResult Value = SemaRef.Owned((Expr *)0); 233 if (Expr *UninstValue = EC->getInitExpr()) { 234 // The enumerator's value expression is not potentially evaluated. 235 EnterExpressionEvaluationContext Unevaluated(SemaRef, 236 Action::Unevaluated); 237 238 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs); 239 } 240 241 // Drop the initial value and continue. 242 bool isInvalid = false; 243 if (Value.isInvalid()) { 244 Value = SemaRef.Owned((Expr *)0); 245 isInvalid = true; 246 } 247 248 EnumConstantDecl *EnumConst 249 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 250 EC->getLocation(), EC->getIdentifier(), 251 move(Value)); 252 253 if (isInvalid) { 254 if (EnumConst) 255 EnumConst->setInvalidDecl(); 256 Enum->setInvalidDecl(); 257 } 258 259 if (EnumConst) { 260 Enum->addDecl(EnumConst); 261 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 262 LastEnumConst = EnumConst; 263 } 264 } 265 266 // FIXME: Fixup LBraceLoc and RBraceLoc 267 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 268 Sema::DeclPtrTy::make(Enum), 269 &Enumerators[0], Enumerators.size()); 270 271 return Enum; 272} 273 274Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 275 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 276 return 0; 277} 278 279Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 280 CXXRecordDecl *PrevDecl = 0; 281 if (D->isInjectedClassName()) 282 PrevDecl = cast<CXXRecordDecl>(Owner); 283 284 CXXRecordDecl *Record 285 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 286 D->getLocation(), D->getIdentifier(), PrevDecl); 287 Record->setImplicit(D->isImplicit()); 288 Record->setAccess(D->getAccess()); 289 if (!D->isInjectedClassName()) 290 Record->setInstantiationOfMemberClass(D); 291 292 Owner->addDecl(Record); 293 return Record; 294} 295 296Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 297 // Check whether there is already a function template specialization for 298 // this declaration. 299 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 300 void *InsertPos = 0; 301 if (FunctionTemplate) { 302 llvm::FoldingSetNodeID ID; 303 FunctionTemplateSpecializationInfo::Profile(ID, 304 TemplateArgs.getFlatArgumentList(), 305 TemplateArgs.flat_size()); 306 307 FunctionTemplateSpecializationInfo *Info 308 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 309 InsertPos); 310 311 // If we already have a function template specialization, return it. 312 if (Info) 313 return Info->Function; 314 } 315 316 Sema::LocalInstantiationScope Scope(SemaRef); 317 318 llvm::SmallVector<ParmVarDecl *, 4> Params; 319 QualType T = InstantiateFunctionType(D, Params); 320 if (T.isNull()) 321 return 0; 322 323 // Build the instantiated method declaration. 324 FunctionDecl *Function 325 = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(), 326 D->getDeclName(), T, D->getStorageClass(), 327 D->isInline(), D->hasWrittenPrototype(), 328 D->getTypeSpecStartLoc()); 329 330 // FIXME: friend functions 331 332 // Attach the parameters 333 for (unsigned P = 0; P < Params.size(); ++P) 334 Params[P]->setOwningFunction(Function); 335 Function->setParams(SemaRef.Context, Params.data(), Params.size()); 336 337 if (InitFunctionInstantiation(Function, D)) 338 Function->setInvalidDecl(); 339 340 bool Redeclaration = false; 341 bool OverloadableAttrRequired = false; 342 NamedDecl *PrevDecl = 0; 343 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration, 344 /*FIXME:*/OverloadableAttrRequired); 345 346 if (FunctionTemplate) { 347 // Record this function template specialization. 348 Function->setFunctionTemplateSpecialization(SemaRef.Context, 349 FunctionTemplate, 350 &TemplateArgs, 351 InsertPos); 352 } 353 354 return Function; 355} 356 357Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 358 // FIXME: Look for existing, explicit specializations. 359 Sema::LocalInstantiationScope Scope(SemaRef); 360 361 llvm::SmallVector<ParmVarDecl *, 4> Params; 362 QualType T = InstantiateFunctionType(D, Params); 363 if (T.isNull()) 364 return 0; 365 366 // Build the instantiated method declaration. 367 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 368 CXXMethodDecl *Method 369 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 370 D->getDeclName(), T, D->isStatic(), 371 D->isInline()); 372 Method->setInstantiationOfMemberFunction(D); 373 374 // Attach the parameters 375 for (unsigned P = 0; P < Params.size(); ++P) 376 Params[P]->setOwningFunction(Method); 377 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 378 379 if (InitMethodInstantiation(Method, D)) 380 Method->setInvalidDecl(); 381 382 NamedDecl *PrevDecl 383 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(), 384 Sema::LookupOrdinaryName, true); 385 // In C++, the previous declaration we find might be a tag type 386 // (class or enum). In this case, the new declaration will hide the 387 // tag type. Note that this does does not apply if we're declaring a 388 // typedef (C++ [dcl.typedef]p4). 389 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 390 PrevDecl = 0; 391 bool Redeclaration = false; 392 bool OverloadableAttrRequired = false; 393 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration, 394 /*FIXME:*/OverloadableAttrRequired); 395 396 if (!Method->isInvalidDecl() || !PrevDecl) 397 Owner->addDecl(Method); 398 return Method; 399} 400 401Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 402 // FIXME: Look for existing, explicit specializations. 403 Sema::LocalInstantiationScope Scope(SemaRef); 404 405 llvm::SmallVector<ParmVarDecl *, 4> Params; 406 QualType T = InstantiateFunctionType(D, Params); 407 if (T.isNull()) 408 return 0; 409 410 // Build the instantiated method declaration. 411 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 412 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 413 DeclarationName Name 414 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 415 SemaRef.Context.getCanonicalType(ClassTy)); 416 CXXConstructorDecl *Constructor 417 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(), 418 Name, T, D->isExplicit(), D->isInline(), 419 false); 420 Constructor->setInstantiationOfMemberFunction(D); 421 422 // Attach the parameters 423 for (unsigned P = 0; P < Params.size(); ++P) 424 Params[P]->setOwningFunction(Constructor); 425 Constructor->setParams(SemaRef.Context, Params.data(), Params.size()); 426 427 if (InitMethodInstantiation(Constructor, D)) 428 Constructor->setInvalidDecl(); 429 430 NamedDecl *PrevDecl 431 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true); 432 433 // In C++, the previous declaration we find might be a tag type 434 // (class or enum). In this case, the new declaration will hide the 435 // tag type. Note that this does does not apply if we're declaring a 436 // typedef (C++ [dcl.typedef]p4). 437 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 438 PrevDecl = 0; 439 bool Redeclaration = false; 440 bool OverloadableAttrRequired = false; 441 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration, 442 /*FIXME:*/OverloadableAttrRequired); 443 444 Record->addedConstructor(SemaRef.Context, Constructor); 445 Owner->addDecl(Constructor); 446 return Constructor; 447} 448 449Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 450 // FIXME: Look for existing, explicit specializations. 451 Sema::LocalInstantiationScope Scope(SemaRef); 452 453 llvm::SmallVector<ParmVarDecl *, 4> Params; 454 QualType T = InstantiateFunctionType(D, Params); 455 if (T.isNull()) 456 return 0; 457 assert(Params.size() == 0 && "Destructor with parameters?"); 458 459 // Build the instantiated destructor declaration. 460 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 461 QualType ClassTy = 462 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record)); 463 CXXDestructorDecl *Destructor 464 = CXXDestructorDecl::Create(SemaRef.Context, Record, 465 D->getLocation(), 466 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy), 467 T, D->isInline(), false); 468 Destructor->setInstantiationOfMemberFunction(D); 469 if (InitMethodInstantiation(Destructor, D)) 470 Destructor->setInvalidDecl(); 471 472 bool Redeclaration = false; 473 bool OverloadableAttrRequired = false; 474 NamedDecl *PrevDecl = 0; 475 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration, 476 /*FIXME:*/OverloadableAttrRequired); 477 Owner->addDecl(Destructor); 478 return Destructor; 479} 480 481Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 482 // FIXME: Look for existing, explicit specializations. 483 Sema::LocalInstantiationScope Scope(SemaRef); 484 485 llvm::SmallVector<ParmVarDecl *, 4> Params; 486 QualType T = InstantiateFunctionType(D, Params); 487 if (T.isNull()) 488 return 0; 489 assert(Params.size() == 0 && "Destructor with parameters?"); 490 491 // Build the instantiated conversion declaration. 492 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 493 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 494 QualType ConvTy 495 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType()); 496 CXXConversionDecl *Conversion 497 = CXXConversionDecl::Create(SemaRef.Context, Record, 498 D->getLocation(), 499 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy), 500 T, D->isInline(), D->isExplicit()); 501 Conversion->setInstantiationOfMemberFunction(D); 502 if (InitMethodInstantiation(Conversion, D)) 503 Conversion->setInvalidDecl(); 504 505 bool Redeclaration = false; 506 bool OverloadableAttrRequired = false; 507 NamedDecl *PrevDecl = 0; 508 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration, 509 /*FIXME:*/OverloadableAttrRequired); 510 Owner->addDecl(Conversion); 511 return Conversion; 512} 513 514ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 515 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs, 516 D->getLocation(), D->getDeclName()); 517 if (OrigT.isNull()) 518 return 0; 519 520 QualType T = SemaRef.adjustParameterType(OrigT); 521 522 if (D->getDefaultArg()) { 523 // FIXME: Leave a marker for "uninstantiated" default 524 // arguments. They only get instantiated on demand at the call 525 // site. 526 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning, 527 "sorry, dropping default argument during template instantiation"); 528 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID) 529 << D->getDefaultArg()->getSourceRange(); 530 } 531 532 // Allocate the parameter 533 ParmVarDecl *Param = 0; 534 if (T == OrigT) 535 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 536 D->getIdentifier(), T, D->getStorageClass(), 537 0); 538 else 539 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner, 540 D->getLocation(), D->getIdentifier(), 541 T, OrigT, D->getStorageClass(), 0); 542 543 // Note: we don't try to instantiate function parameters until after 544 // we've instantiated the function's type. Therefore, we don't have 545 // to check for 'void' parameter types here. 546 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 547 return Param; 548} 549 550Decl * 551TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { 552 // Since parameter types can decay either before or after 553 // instantiation, we simply treat OriginalParmVarDecls as 554 // ParmVarDecls the same way, and create one or the other depending 555 // on what happens after template instantiation. 556 return VisitParmVarDecl(D); 557} 558 559Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner, 560 const TemplateArgumentList &TemplateArgs) { 561 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 562 return Instantiator.Visit(D); 563} 564 565/// \brief Instantiates the type of the given function, including 566/// instantiating all of the function parameters. 567/// 568/// \param D The function that we will be instantiated 569/// 570/// \param Params the instantiated parameter declarations 571 572/// \returns the instantiated function's type if successfull, a NULL 573/// type if there was an error. 574QualType 575TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D, 576 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 577 bool InvalidDecl = false; 578 579 // Instantiate the function parameters 580 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 581 llvm::SmallVector<QualType, 4> ParamTys; 582 for (FunctionDecl::param_iterator P = D->param_begin(), 583 PEnd = D->param_end(); 584 P != PEnd; ++P) { 585 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 586 if (PInst->getType()->isVoidType()) { 587 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 588 PInst->setInvalidDecl(); 589 } 590 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 591 PInst->getType(), 592 diag::err_abstract_type_in_decl, 593 Sema::AbstractParamType)) 594 PInst->setInvalidDecl(); 595 596 Params.push_back(PInst); 597 ParamTys.push_back(PInst->getType()); 598 599 if (PInst->isInvalidDecl()) 600 InvalidDecl = true; 601 } else 602 InvalidDecl = true; 603 } 604 605 // FIXME: Deallocate dead declarations. 606 if (InvalidDecl) 607 return QualType(); 608 609 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType(); 610 assert(Proto && "Missing prototype?"); 611 QualType ResultType 612 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs, 613 D->getLocation(), D->getDeclName()); 614 if (ResultType.isNull()) 615 return QualType(); 616 617 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 618 Proto->isVariadic(), Proto->getTypeQuals(), 619 D->getLocation(), D->getDeclName()); 620} 621 622/// \brief Initializes the common fields of an instantiation function 623/// declaration (New) from the corresponding fields of its template (Tmpl). 624/// 625/// \returns true if there was an error 626bool 627TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 628 FunctionDecl *Tmpl) { 629 if (Tmpl->isDeleted()) 630 New->setDeleted(); 631 return false; 632} 633 634/// \brief Initializes common fields of an instantiated method 635/// declaration (New) from the corresponding fields of its template 636/// (Tmpl). 637/// 638/// \returns true if there was an error 639bool 640TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 641 CXXMethodDecl *Tmpl) { 642 if (InitFunctionInstantiation(New, Tmpl)) 643 return true; 644 645 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 646 New->setAccess(Tmpl->getAccess()); 647 if (Tmpl->isVirtualAsWritten()) { 648 New->setVirtualAsWritten(true); 649 Record->setAggregate(false); 650 Record->setPOD(false); 651 Record->setPolymorphic(true); 652 } 653 if (Tmpl->isPure()) { 654 New->setPure(); 655 Record->setAbstract(true); 656 } 657 658 // FIXME: attributes 659 // FIXME: New needs a pointer to Tmpl 660 return false; 661} 662 663/// \brief Instantiate the definition of the given function from its 664/// template. 665/// 666/// \param PointOfInstantiation the point at which the instantiation was 667/// required. Note that this is not precisely a "point of instantiation" 668/// for the function, but it's close. 669/// 670/// \param Function the already-instantiated declaration of a 671/// function template specialization or member function of a class template 672/// specialization. 673/// 674/// \param Recursive if true, recursively instantiates any functions that 675/// are required by this instantiation. 676void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 677 FunctionDecl *Function, 678 bool Recursive) { 679 if (Function->isInvalidDecl()) 680 return; 681 682 assert(!Function->getBody() && "Already instantiated!"); 683 684 // Find the function body that we'll be substituting. 685 const FunctionDecl *PatternDecl = 0; 686 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) 687 PatternDecl = Primary->getTemplatedDecl(); 688 else 689 PatternDecl = Function->getInstantiatedFromMemberFunction(); 690 Stmt *Pattern = 0; 691 if (PatternDecl) 692 Pattern = PatternDecl->getBody(PatternDecl); 693 694 if (!Pattern) 695 return; 696 697 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 698 if (Inst) 699 return; 700 701 // If we're performing recursive template instantiation, create our own 702 // queue of pending implicit instantiations that we will instantiate later, 703 // while we're still within our own instantiation context. 704 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 705 if (Recursive) 706 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 707 708 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 709 710 // Introduce a new scope where local variable instantiations will be 711 // recorded. 712 LocalInstantiationScope Scope(*this); 713 714 // Introduce the instantiated function parameters into the local 715 // instantiation scope. 716 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 717 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 718 Function->getParamDecl(I)); 719 720 // Enter the scope of this instantiation. We don't use 721 // PushDeclContext because we don't have a scope. 722 DeclContext *PreviousContext = CurContext; 723 CurContext = Function; 724 725 // Instantiate the function body. 726 OwningStmtResult Body 727 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function)); 728 729 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 730 /*IsInstantiation=*/true); 731 732 CurContext = PreviousContext; 733 734 DeclGroupRef DG(Function); 735 Consumer.HandleTopLevelDecl(DG); 736 737 if (Recursive) { 738 // Instantiate any pending implicit instantiations found during the 739 // instantiation of this template. 740 PerformPendingImplicitInstantiations(); 741 742 // Restore the set of pending implicit instantiations. 743 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 744 } 745} 746 747/// \brief Instantiate the definition of the given variable from its 748/// template. 749/// 750/// \param Var the already-instantiated declaration of a variable. 751void Sema::InstantiateVariableDefinition(VarDecl *Var) { 752 // FIXME: Implement this! 753} 754 755static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 756 if (D->getKind() != Other->getKind()) 757 return false; 758 759 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 760 return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass()) 761 == Ctx.getCanonicalDecl(D); 762 763 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 764 return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction()) 765 == Ctx.getCanonicalDecl(D); 766 767 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 768 return Ctx.getCanonicalDecl(Enum->getInstantiatedFromMemberEnum()) 769 == Ctx.getCanonicalDecl(D); 770 771 // FIXME: How can we find instantiations of anonymous unions? 772 773 return D->getDeclName() && isa<NamedDecl>(Other) && 774 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 775} 776 777template<typename ForwardIterator> 778static NamedDecl *findInstantiationOf(ASTContext &Ctx, 779 NamedDecl *D, 780 ForwardIterator first, 781 ForwardIterator last) { 782 for (; first != last; ++first) 783 if (isInstantiationOf(Ctx, D, *first)) 784 return cast<NamedDecl>(*first); 785 786 return 0; 787} 788 789/// \brief Find the instantiation of the given declaration within the 790/// current instantiation. 791/// 792/// This routine is intended to be used when \p D is a declaration 793/// referenced from within a template, that needs to mapped into the 794/// corresponding declaration within an instantiation. For example, 795/// given: 796/// 797/// \code 798/// template<typename T> 799/// struct X { 800/// enum Kind { 801/// KnownValue = sizeof(T) 802/// }; 803/// 804/// bool getKind() const { return KnownValue; } 805/// }; 806/// 807/// template struct X<int>; 808/// \endcode 809/// 810/// In the instantiation of X<int>::getKind(), we need to map the 811/// EnumConstantDecl for KnownValue (which refers to 812/// X<T>::<Kind>::KnownValue) to its instantiation 813/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 814/// this mapping from within the instantiation of X<int>. 815NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) { 816 DeclContext *ParentDC = D->getDeclContext(); 817 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) { 818 // D is a local of some kind. Look into the map of local 819 // declarations to their instantiations. 820 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 821 } 822 823 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) { 824 ParentDecl = InstantiateCurrentDeclRef(ParentDecl); 825 if (!ParentDecl) 826 return 0; 827 828 ParentDC = cast<DeclContext>(ParentDecl); 829 } 830 831 if (ParentDC != D->getDeclContext()) { 832 // We performed some kind of instantiation in the parent context, 833 // so now we need to look into the instantiated parent context to 834 // find the instantiation of the declaration D. 835 NamedDecl *Result = 0; 836 if (D->getDeclName()) { 837 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 838 Result = findInstantiationOf(Context, D, Found.first, Found.second); 839 } else { 840 // Since we don't have a name for the entity we're looking for, 841 // our only option is to walk through all of the declarations to 842 // find that name. This will occur in a few cases: 843 // 844 // - anonymous struct/union within a template 845 // - unnamed class/struct/union/enum within a template 846 // 847 // FIXME: Find a better way to find these instantiations! 848 Result = findInstantiationOf(Context, D, 849 ParentDC->decls_begin(), 850 ParentDC->decls_end()); 851 } 852 assert(Result && "Unable to find instantiation of declaration!"); 853 D = Result; 854 } 855 856 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 857 if (ClassTemplateDecl *ClassTemplate 858 = Record->getDescribedClassTemplate()) { 859 // When the declaration D was parsed, it referred to the current 860 // instantiation. Therefore, look through the current context, 861 // which contains actual instantiations, to find the 862 // instantiation of the "current instantiation" that D refers 863 // to. Alternatively, we could just instantiate the 864 // injected-class-name with the current template arguments, but 865 // such an instantiation is far more expensive. 866 for (DeclContext *DC = CurContext; !DC->isFileContext(); 867 DC = DC->getParent()) { 868 if (ClassTemplateSpecializationDecl *Spec 869 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 870 if (Context.getCanonicalDecl(Spec->getSpecializedTemplate()) 871 == Context.getCanonicalDecl(ClassTemplate)) 872 return Spec; 873 } 874 875 assert(false && 876 "Unable to find declaration for the current instantiation"); 877 } 878 879 return D; 880} 881 882/// \brief Performs template instantiation for all implicit template 883/// instantiations we have seen until this point. 884void Sema::PerformPendingImplicitInstantiations() { 885 while (!PendingImplicitInstantiations.empty()) { 886 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front(); 887 PendingImplicitInstantiations.pop_front(); 888 889 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) 890 if (!Function->getBody()) 891 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 892 893 // FIXME: instantiate static member variables 894 } 895} 896