SemaTemplateInstantiateDecl.cpp revision f97986dce99ea113744872de1d2a6d2da274061b
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 *VisitCXXRecordDecl(CXXRecordDecl *D); 48 Decl *VisitCXXMethodDecl(CXXMethodDecl *D); 49 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 50 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 51 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 52 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 53 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D); 54 55 // Base case. FIXME: Remove once we can instantiate everything. 56 Decl *VisitDecl(Decl *) { 57 assert(false && "Template instantiation of unknown declaration kind!"); 58 return 0; 59 } 60 61 // Helper functions for instantiating methods. 62 QualType InstantiateFunctionType(FunctionDecl *D, 63 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 64 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 65 }; 66} 67 68Decl * 69TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 70 assert(false && "Translation units cannot be instantiated"); 71 return D; 72} 73 74Decl * 75TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 76 assert(false && "Namespaces cannot be instantiated"); 77 return D; 78} 79 80Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 81 bool Invalid = false; 82 QualType T = D->getUnderlyingType(); 83 if (T->isDependentType()) { 84 T = SemaRef.InstantiateType(T, TemplateArgs, 85 D->getLocation(), D->getDeclName()); 86 if (T.isNull()) { 87 Invalid = true; 88 T = SemaRef.Context.IntTy; 89 } 90 } 91 92 // Create the new typedef 93 TypedefDecl *Typedef 94 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 95 D->getIdentifier(), T); 96 if (Invalid) 97 Typedef->setInvalidDecl(); 98 99 Owner->addDecl(SemaRef.Context, Typedef); 100 return Typedef; 101} 102 103Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 104 // Instantiate the type of the declaration 105 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs, 106 D->getTypeSpecStartLoc(), 107 D->getDeclName()); 108 if (T.isNull()) 109 return 0; 110 111 // Build the instantiated declaration 112 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 113 D->getLocation(), D->getIdentifier(), 114 T, D->getStorageClass(), 115 D->getTypeSpecStartLoc()); 116 Var->setThreadSpecified(D->isThreadSpecified()); 117 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 118 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 119 120 // FIXME: In theory, we could have a previous declaration for variables that 121 // are not static data members. 122 bool Redeclaration = false; 123 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration); 124 Owner->addDecl(SemaRef.Context, Var); 125 126 if (D->getInit()) { 127 OwningExprResult Init 128 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs); 129 if (Init.isInvalid()) 130 Var->setInvalidDecl(); 131 else 132 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 133 D->hasCXXDirectInitializer()); 134 } else { 135 // FIXME: Call ActOnUninitializedDecl? (Not always) 136 } 137 138 return Var; 139} 140 141Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 142 bool Invalid = false; 143 QualType T = D->getType(); 144 if (T->isDependentType()) { 145 T = SemaRef.InstantiateType(T, TemplateArgs, 146 D->getLocation(), D->getDeclName()); 147 if (!T.isNull() && T->isFunctionType()) { 148 // C++ [temp.arg.type]p3: 149 // If a declaration acquires a function type through a type 150 // dependent on a template-parameter and this causes a 151 // declaration that does not use the syntactic form of a 152 // function declarator to have function type, the program is 153 // ill-formed. 154 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 155 << T; 156 T = QualType(); 157 Invalid = true; 158 } 159 } 160 161 Expr *BitWidth = D->getBitWidth(); 162 if (Invalid) 163 BitWidth = 0; 164 else if (BitWidth) { 165 OwningExprResult InstantiatedBitWidth 166 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs); 167 if (InstantiatedBitWidth.isInvalid()) { 168 Invalid = true; 169 BitWidth = 0; 170 } else 171 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 172 } 173 174 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T, 175 cast<RecordDecl>(Owner), 176 D->getLocation(), 177 D->isMutable(), 178 BitWidth, 179 D->getAccess(), 180 0); 181 if (Field) { 182 if (Invalid) 183 Field->setInvalidDecl(); 184 185 Owner->addDecl(SemaRef.Context, Field); 186 } 187 188 return Field; 189} 190 191Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 192 Expr *AssertExpr = D->getAssertExpr(); 193 194 OwningExprResult InstantiatedAssertExpr 195 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs); 196 if (InstantiatedAssertExpr.isInvalid()) 197 return 0; 198 199 OwningExprResult Message = SemaRef.Clone(D->getMessage()); 200 Decl *StaticAssert 201 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 202 move(InstantiatedAssertExpr), 203 move(Message)).getAs<Decl>(); 204 return StaticAssert; 205} 206 207Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 208 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 209 D->getLocation(), D->getIdentifier(), 210 /*PrevDecl=*/0); 211 Enum->setAccess(D->getAccess()); 212 Owner->addDecl(SemaRef.Context, Enum); 213 Enum->startDefinition(); 214 215 llvm::SmallVector<Sema::DeclPtrTy, 16> Enumerators; 216 217 EnumConstantDecl *LastEnumConst = 0; 218 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context), 219 ECEnd = D->enumerator_end(SemaRef.Context); 220 EC != ECEnd; ++EC) { 221 // The specified value for the enumerator. 222 OwningExprResult Value = SemaRef.Owned((Expr *)0); 223 if (Expr *UninstValue = EC->getInitExpr()) 224 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs); 225 226 // Drop the initial value and continue. 227 bool isInvalid = false; 228 if (Value.isInvalid()) { 229 Value = SemaRef.Owned((Expr *)0); 230 isInvalid = true; 231 } 232 233 EnumConstantDecl *EnumConst 234 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 235 EC->getLocation(), EC->getIdentifier(), 236 move(Value)); 237 238 if (isInvalid) { 239 if (EnumConst) 240 EnumConst->setInvalidDecl(); 241 Enum->setInvalidDecl(); 242 } 243 244 if (EnumConst) { 245 Enum->addDecl(SemaRef.Context, EnumConst); 246 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 247 LastEnumConst = EnumConst; 248 } 249 } 250 251 // FIXME: Fixup LBraceLoc and RBraceLoc 252 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 253 Sema::DeclPtrTy::make(Enum), 254 &Enumerators[0], Enumerators.size()); 255 256 return Enum; 257} 258 259Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 260 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 261 return 0; 262} 263 264Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 265 CXXRecordDecl *PrevDecl = 0; 266 if (D->isInjectedClassName()) 267 PrevDecl = cast<CXXRecordDecl>(Owner); 268 269 CXXRecordDecl *Record 270 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 271 D->getLocation(), D->getIdentifier(), PrevDecl); 272 Record->setImplicit(D->isImplicit()); 273 Record->setAccess(D->getAccess()); 274 if (!D->isInjectedClassName()) 275 Record->setInstantiationOfMemberClass(D); 276 277 Owner->addDecl(SemaRef.Context, Record); 278 return Record; 279} 280 281Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 282 // Only handle actual methods; we'll deal with constructors, 283 // destructors, etc. separately. 284 if (D->getKind() != Decl::CXXMethod) 285 return 0; 286 287 Sema::LocalInstantiationScope Scope(SemaRef); 288 289 llvm::SmallVector<ParmVarDecl *, 16> Params; 290 QualType T = InstantiateFunctionType(D, Params); 291 if (T.isNull()) 292 return 0; 293 294 // Build the instantiated method declaration. 295 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 296 CXXMethodDecl *Method 297 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 298 D->getDeclName(), T, D->isStatic(), 299 D->isInline()); 300 Method->setInstantiationOfMemberFunction(D); 301 302 // Attach the parameters 303 for (unsigned P = 0; P < Params.size(); ++P) 304 Params[P]->setOwningFunction(Method); 305 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 306 307 if (InitMethodInstantiation(Method, D)) 308 Method->setInvalidDecl(); 309 310 NamedDecl *PrevDecl 311 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(), 312 Sema::LookupOrdinaryName, true); 313 // In C++, the previous declaration we find might be a tag type 314 // (class or enum). In this case, the new declaration will hide the 315 // tag type. Note that this does does not apply if we're declaring a 316 // typedef (C++ [dcl.typedef]p4). 317 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 318 PrevDecl = 0; 319 bool Redeclaration = false; 320 bool OverloadableAttrRequired = false; 321 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration, 322 /*FIXME:*/OverloadableAttrRequired); 323 324 if (!Method->isInvalidDecl() || !PrevDecl) 325 Owner->addDecl(SemaRef.Context, Method); 326 return Method; 327} 328 329Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 330 Sema::LocalInstantiationScope Scope(SemaRef); 331 332 llvm::SmallVector<ParmVarDecl *, 16> Params; 333 QualType T = InstantiateFunctionType(D, Params); 334 if (T.isNull()) 335 return 0; 336 337 // Build the instantiated method declaration. 338 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 339 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 340 DeclarationName Name 341 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 342 SemaRef.Context.getCanonicalType(ClassTy)); 343 CXXConstructorDecl *Constructor 344 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(), 345 Name, T, D->isExplicit(), D->isInline(), 346 false); 347 Constructor->setInstantiationOfMemberFunction(D); 348 349 // Attach the parameters 350 for (unsigned P = 0; P < Params.size(); ++P) 351 Params[P]->setOwningFunction(Constructor); 352 Constructor->setParams(SemaRef.Context, Params.data(), Params.size()); 353 354 if (InitMethodInstantiation(Constructor, D)) 355 Constructor->setInvalidDecl(); 356 357 NamedDecl *PrevDecl 358 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true); 359 360 // In C++, the previous declaration we find might be a tag type 361 // (class or enum). In this case, the new declaration will hide the 362 // tag type. Note that this does does not apply if we're declaring a 363 // typedef (C++ [dcl.typedef]p4). 364 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 365 PrevDecl = 0; 366 bool Redeclaration = false; 367 bool OverloadableAttrRequired = false; 368 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration, 369 /*FIXME:*/OverloadableAttrRequired); 370 371 Record->addedConstructor(SemaRef.Context, Constructor); 372 Owner->addDecl(SemaRef.Context, Constructor); 373 return Constructor; 374} 375 376Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 377 Sema::LocalInstantiationScope Scope(SemaRef); 378 379 llvm::SmallVector<ParmVarDecl *, 16> Params; 380 QualType T = InstantiateFunctionType(D, Params); 381 if (T.isNull()) 382 return 0; 383 assert(Params.size() == 0 && "Destructor with parameters?"); 384 385 // Build the instantiated destructor declaration. 386 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 387 QualType ClassTy = 388 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record)); 389 CXXDestructorDecl *Destructor 390 = CXXDestructorDecl::Create(SemaRef.Context, Record, 391 D->getLocation(), 392 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy), 393 T, D->isInline(), false); 394 Destructor->setInstantiationOfMemberFunction(D); 395 if (InitMethodInstantiation(Destructor, D)) 396 Destructor->setInvalidDecl(); 397 398 bool Redeclaration = false; 399 bool OverloadableAttrRequired = false; 400 NamedDecl *PrevDecl = 0; 401 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration, 402 /*FIXME:*/OverloadableAttrRequired); 403 Owner->addDecl(SemaRef.Context, Destructor); 404 return Destructor; 405} 406 407Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 408 Sema::LocalInstantiationScope Scope(SemaRef); 409 410 llvm::SmallVector<ParmVarDecl *, 16> Params; 411 QualType T = InstantiateFunctionType(D, Params); 412 if (T.isNull()) 413 return 0; 414 assert(Params.size() == 0 && "Destructor with parameters?"); 415 416 // Build the instantiated conversion declaration. 417 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 418 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 419 QualType ConvTy 420 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType()); 421 CXXConversionDecl *Conversion 422 = CXXConversionDecl::Create(SemaRef.Context, Record, 423 D->getLocation(), 424 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy), 425 T, D->isInline(), D->isExplicit()); 426 Conversion->setInstantiationOfMemberFunction(D); 427 if (InitMethodInstantiation(Conversion, D)) 428 Conversion->setInvalidDecl(); 429 430 bool Redeclaration = false; 431 bool OverloadableAttrRequired = false; 432 NamedDecl *PrevDecl = 0; 433 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration, 434 /*FIXME:*/OverloadableAttrRequired); 435 Owner->addDecl(SemaRef.Context, Conversion); 436 return Conversion; 437} 438 439ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 440 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs, 441 D->getLocation(), D->getDeclName()); 442 if (OrigT.isNull()) 443 return 0; 444 445 QualType T = SemaRef.adjustParameterType(OrigT); 446 447 if (D->getDefaultArg()) { 448 // FIXME: Leave a marker for "uninstantiated" default 449 // arguments. They only get instantiated on demand at the call 450 // site. 451 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning, 452 "sorry, dropping default argument during template instantiation"); 453 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID) 454 << D->getDefaultArg()->getSourceRange(); 455 } 456 457 // Allocate the parameter 458 ParmVarDecl *Param = 0; 459 if (T == OrigT) 460 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 461 D->getIdentifier(), T, D->getStorageClass(), 462 0); 463 else 464 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner, 465 D->getLocation(), D->getIdentifier(), 466 T, OrigT, D->getStorageClass(), 0); 467 468 // Note: we don't try to instantiate function parameters until after 469 // we've instantiated the function's type. Therefore, we don't have 470 // to check for 'void' parameter types here. 471 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 472 return Param; 473} 474 475Decl * 476TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { 477 // Since parameter types can decay either before or after 478 // instantiation, we simply treat OriginalParmVarDecls as 479 // ParmVarDecls the same way, and create one or the other depending 480 // on what happens after template instantiation. 481 return VisitParmVarDecl(D); 482} 483 484Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner, 485 const TemplateArgumentList &TemplateArgs) { 486 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 487 return Instantiator.Visit(D); 488} 489 490/// \brief Instantiates the type of the given function, including 491/// instantiating all of the function parameters. 492/// 493/// \param D The function that we will be instantiated 494/// 495/// \param Params the instantiated parameter declarations 496 497/// \returns the instantiated function's type if successfull, a NULL 498/// type if there was an error. 499QualType 500TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D, 501 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 502 bool InvalidDecl = false; 503 504 // Instantiate the function parameters 505 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 506 llvm::SmallVector<QualType, 16> ParamTys; 507 for (FunctionDecl::param_iterator P = D->param_begin(), 508 PEnd = D->param_end(); 509 P != PEnd; ++P) { 510 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 511 if (PInst->getType()->isVoidType()) { 512 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 513 PInst->setInvalidDecl(); 514 } 515 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 516 PInst->getType(), 517 diag::err_abstract_type_in_decl, 518 Sema::AbstractParamType)) 519 PInst->setInvalidDecl(); 520 521 Params.push_back(PInst); 522 ParamTys.push_back(PInst->getType()); 523 524 if (PInst->isInvalidDecl()) 525 InvalidDecl = true; 526 } else 527 InvalidDecl = true; 528 } 529 530 // FIXME: Deallocate dead declarations. 531 if (InvalidDecl) 532 return QualType(); 533 534 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType(); 535 assert(Proto && "Missing prototype?"); 536 QualType ResultType 537 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs, 538 D->getLocation(), D->getDeclName()); 539 if (ResultType.isNull()) 540 return QualType(); 541 542 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 543 Proto->isVariadic(), Proto->getTypeQuals(), 544 D->getLocation(), D->getDeclName()); 545} 546 547/// \brief Initializes common fields of an instantiated method 548/// declaration (New) from the corresponding fields of its template 549/// (Tmpl). 550/// 551/// \returns true if there was an error 552bool 553TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 554 CXXMethodDecl *Tmpl) { 555 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 556 New->setAccess(Tmpl->getAccess()); 557 if (Tmpl->isVirtualAsWritten()) { 558 New->setVirtualAsWritten(true); 559 Record->setAggregate(false); 560 Record->setPOD(false); 561 Record->setPolymorphic(true); 562 } 563 if (Tmpl->isDeleted()) 564 New->setDeleted(); 565 if (Tmpl->isPure()) { 566 New->setPure(); 567 Record->setAbstract(true); 568 } 569 570 // FIXME: attributes 571 // FIXME: New needs a pointer to Tmpl 572 return false; 573} 574 575/// \brief Instantiate the definition of the given function from its 576/// template. 577/// 578/// \param Function the already-instantiated declaration of a 579/// function. 580void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 581 FunctionDecl *Function) { 582 // FIXME: make this work for function template specializations, too. 583 584 if (Function->isInvalidDecl()) 585 return; 586 587 // Find the function body that we'll be substituting. 588 const FunctionDecl *PatternDecl 589 = Function->getInstantiatedFromMemberFunction(); 590 Stmt *Pattern = 0; 591 if (PatternDecl) 592 Pattern = PatternDecl->getBody(Context, PatternDecl); 593 594 if (!Pattern) 595 return; 596 597 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 598 if (Inst) 599 return; 600 601 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 602 603 // Introduce a new scope where local variable instantiations will be 604 // recorded. 605 LocalInstantiationScope Scope(*this); 606 607 // Introduce the instantiated function parameters into the local 608 // instantiation scope. 609 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 610 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 611 Function->getParamDecl(I)); 612 613 // Enter the scope of this instantiation. We don't use 614 // PushDeclContext because we don't have a scope. 615 DeclContext *PreviousContext = CurContext; 616 CurContext = Function; 617 618 // Instantiate the function body. 619 OwningStmtResult Body 620 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function)); 621 622 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 623 /*IsInstantiation=*/true); 624 625 CurContext = PreviousContext; 626 627 DeclGroupRef DG(Function); 628 Consumer.HandleTopLevelDecl(DG); 629} 630 631/// \brief Instantiate the definition of the given variable from its 632/// template. 633/// 634/// \param Var the already-instantiated declaration of a variable. 635void Sema::InstantiateVariableDefinition(VarDecl *Var) { 636 // FIXME: Implement this! 637} 638 639static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 640 if (D->getKind() != Other->getKind()) 641 return false; 642 643 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 644 return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass()) 645 == Ctx.getCanonicalDecl(D); 646 647 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 648 return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction()) 649 == Ctx.getCanonicalDecl(D); 650 651 // FIXME: Need something similar to the above for EnumDecls. 652 653 // FIXME: How can we find instantiations of anonymous unions? 654 655 return D->getDeclName() && isa<NamedDecl>(Other) && 656 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 657} 658 659template<typename ForwardIterator> 660static NamedDecl *findInstantiationOf(ASTContext &Ctx, 661 NamedDecl *D, 662 ForwardIterator first, 663 ForwardIterator last) { 664 for (; first != last; ++first) 665 if (isInstantiationOf(Ctx, D, *first)) 666 return cast<NamedDecl>(*first); 667 668 return 0; 669} 670 671/// \brief Find the instantiation of the given declaration with the 672/// given template arguments. 673/// 674/// This routine is intended to be used when \p D is a declaration 675/// referenced from within a template, that needs to mapped into the 676/// corresponding declaration within an instantiation. For example, 677/// given: 678/// 679/// \code 680/// template<typename T> 681/// struct X { 682/// enum Kind { 683/// KnownValue = sizeof(T) 684/// }; 685/// 686/// bool getKind() const { return KnownValue; } 687/// }; 688/// 689/// template struct X<int>; 690/// \endcode 691/// 692/// In the instantiation of X<int>::getKind(), we need to map the 693/// EnumConstantDecl for KnownValue (which refers to 694/// X<T>::<Kind>::KnownValue) to its instantiation 695/// (X<int>::<Kind>::KnownValue). InstantiateDeclRef() performs this 696/// mapping, given the template arguments 'int'. 697NamedDecl * 698Sema::InstantiateDeclRef(NamedDecl *D, const TemplateArgumentList &TemplateArgs) { 699 DeclContext *ParentDC = D->getDeclContext(); 700 701 if (!ParentDC->isFileContext()) { 702 NamedDecl *ParentDecl = cast<NamedDecl>(ParentDC); 703 ParentDecl = InstantiateDeclRef(ParentDecl, TemplateArgs); 704 if (!ParentDecl) 705 return 0; 706 707 ParentDC = cast<DeclContext>(ParentDecl); 708 } 709 710 if (ParentDC->isFunctionOrMethod()) { 711 // D is a local of some kind. Look into the map of local 712 // variables to their instantiations. 713 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 714 } 715 716 if (ParentDC != D->getDeclContext()) { 717 // We performed some kind of instantiation in the parent context, 718 // so now we need to look into the instantiated parent context to 719 // find the instantiation of the declaration D. 720 NamedDecl *Result = 0; 721 if (D->getDeclName()) { 722 DeclContext::lookup_result Found 723 = ParentDC->lookup(Context, D->getDeclName()); 724 Result = findInstantiationOf(Context, D, Found.first, Found.second); 725 } else { 726 // Since we don't have a name for the entity we're looking for, 727 // our only option is to walk through all of the declarations to 728 // find that name. This will occur in a few cases: 729 // 730 // - anonymous struct/union within a template 731 // - unnamed class/struct/union/enum within a template 732 // 733 // FIXME: Find a better way to find these instantiations! 734 Result = findInstantiationOf(Context, D, 735 ParentDC->decls_begin(Context), 736 ParentDC->decls_end(Context)); 737 } 738 assert(Result && "Unable to find instantiation of declaration!"); 739 D = Result; 740 } 741 742 // D itself might be a class template that we need to instantiate 743 // with the given template arguments. 744 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 745 if (ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate()) { 746 QualType InjectedClassName 747 = ClassTemplate->getInjectedClassNameType(Context); 748 QualType InstantiatedType = InstantiateType(InjectedClassName, 749 TemplateArgs, 750 Record->getLocation(), 751 Record->getDeclName()); 752 if (InstantiatedType.isNull()) 753 return 0; 754 if (const RecordType *RT = InstantiatedType->getAsRecordType()) 755 D = RT->getDecl(); 756 } 757 758 return D; 759} 760