clang API Documentation
00001 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/ 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 //===----------------------------------------------------------------------===/ 00008 // 00009 // This file implements C++ template instantiation for declarations. 00010 // 00011 //===----------------------------------------------------------------------===/ 00012 #include "Sema.h" 00013 #include "Lookup.h" 00014 #include "clang/AST/ASTConsumer.h" 00015 #include "clang/AST/ASTContext.h" 00016 #include "clang/AST/DeclTemplate.h" 00017 #include "clang/AST/DeclVisitor.h" 00018 #include "clang/AST/DependentDiagnostic.h" 00019 #include "clang/AST/Expr.h" 00020 #include "clang/AST/ExprCXX.h" 00021 #include "clang/AST/TypeLoc.h" 00022 #include "clang/Basic/PrettyStackTrace.h" 00023 #include "clang/Lex/Preprocessor.h" 00024 00025 using namespace clang; 00026 00027 namespace { 00028 class TemplateDeclInstantiator 00029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 00030 Sema &SemaRef; 00031 DeclContext *Owner; 00032 const MultiLevelTemplateArgumentList &TemplateArgs; 00033 00034 void InstantiateAttrs(Decl *Tmpl, Decl *New); 00035 00036 public: 00037 typedef Sema::OwningExprResult OwningExprResult; 00038 00039 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 00040 const MultiLevelTemplateArgumentList &TemplateArgs) 00041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 00042 00043 // FIXME: Once we get closer to completion, replace these manually-written 00044 // declarations with automatically-generated ones from 00045 // clang/AST/DeclNodes.def. 00046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 00047 Decl *VisitNamespaceDecl(NamespaceDecl *D); 00048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 00049 Decl *VisitTypedefDecl(TypedefDecl *D); 00050 Decl *VisitVarDecl(VarDecl *D); 00051 Decl *VisitFieldDecl(FieldDecl *D); 00052 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 00053 Decl *VisitEnumDecl(EnumDecl *D); 00054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 00055 Decl *VisitFriendDecl(FriendDecl *D); 00056 Decl *VisitFunctionDecl(FunctionDecl *D, 00057 TemplateParameterList *TemplateParams = 0); 00058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 00059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 00060 TemplateParameterList *TemplateParams = 0); 00061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 00062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 00063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 00064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 00065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 00066 Decl *VisitClassTemplatePartialSpecializationDecl( 00067 ClassTemplatePartialSpecializationDecl *D); 00068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 00069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 00070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 00071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 00072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 00073 Decl *VisitUsingDecl(UsingDecl *D); 00074 Decl *VisitUsingShadowDecl(UsingShadowDecl *D); 00075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 00076 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 00077 00078 // Base case. FIXME: Remove once we can instantiate everything. 00079 Decl *VisitDecl(Decl *D) { 00080 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 00081 Diagnostic::Error, 00082 "cannot instantiate %0 yet"); 00083 SemaRef.Diag(D->getLocation(), DiagID) 00084 << D->getDeclKindName(); 00085 00086 return 0; 00087 } 00088 00089 const LangOptions &getLangOptions() { 00090 return SemaRef.getLangOptions(); 00091 } 00092 00093 // Helper functions for instantiating methods. 00094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D, 00095 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 00096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 00097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 00098 00099 TemplateParameterList * 00100 SubstTemplateParams(TemplateParameterList *List); 00101 00102 bool SubstQualifier(const DeclaratorDecl *OldDecl, 00103 DeclaratorDecl *NewDecl); 00104 bool SubstQualifier(const TagDecl *OldDecl, 00105 TagDecl *NewDecl); 00106 00107 bool InstantiateClassTemplatePartialSpecialization( 00108 ClassTemplateDecl *ClassTemplate, 00109 ClassTemplatePartialSpecializationDecl *PartialSpec); 00110 }; 00111 } 00112 00113 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 00114 DeclaratorDecl *NewDecl) { 00115 NestedNameSpecifier *OldQual = OldDecl->getQualifier(); 00116 if (!OldQual) return false; 00117 00118 SourceRange QualRange = OldDecl->getQualifierRange(); 00119 00120 NestedNameSpecifier *NewQual 00121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs); 00122 if (!NewQual) 00123 return true; 00124 00125 NewDecl->setQualifierInfo(NewQual, QualRange); 00126 return false; 00127 } 00128 00129 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 00130 TagDecl *NewDecl) { 00131 NestedNameSpecifier *OldQual = OldDecl->getQualifier(); 00132 if (!OldQual) return false; 00133 00134 SourceRange QualRange = OldDecl->getQualifierRange(); 00135 00136 NestedNameSpecifier *NewQual 00137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs); 00138 if (!NewQual) 00139 return true; 00140 00141 NewDecl->setQualifierInfo(NewQual, QualRange); 00142 return false; 00143 } 00144 00145 // FIXME: Is this too simple? 00146 void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 00147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 00148 TmplAttr = TmplAttr->getNext()) { 00149 00150 // FIXME: Is cloning correct for all attributes? 00151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 00152 00153 New->addAttr(NewAttr); 00154 } 00155 } 00156 00157 Decl * 00158 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 00159 assert(false && "Translation units cannot be instantiated"); 00160 return D; 00161 } 00162 00163 Decl * 00164 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 00165 assert(false && "Namespaces cannot be instantiated"); 00166 return D; 00167 } 00168 00169 Decl * 00170 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 00171 NamespaceAliasDecl *Inst 00172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 00173 D->getNamespaceLoc(), 00174 D->getAliasLoc(), 00175 D->getNamespace()->getIdentifier(), 00176 D->getQualifierRange(), 00177 D->getQualifier(), 00178 D->getTargetNameLoc(), 00179 D->getNamespace()); 00180 Owner->addDecl(Inst); 00181 return Inst; 00182 } 00183 00184 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 00185 bool Invalid = false; 00186 TypeSourceInfo *DI = D->getTypeSourceInfo(); 00187 if (DI->getType()->isDependentType()) { 00188 DI = SemaRef.SubstType(DI, TemplateArgs, 00189 D->getLocation(), D->getDeclName()); 00190 if (!DI) { 00191 Invalid = true; 00192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 00193 } 00194 } 00195 00196 // Create the new typedef 00197 TypedefDecl *Typedef 00198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 00199 D->getIdentifier(), DI); 00200 if (Invalid) 00201 Typedef->setInvalidDecl(); 00202 00203 if (const TagType *TT = DI->getType()->getAs<TagType>()) { 00204 TagDecl *TD = TT->getDecl(); 00205 00206 // If the TagDecl that the TypedefDecl points to is an anonymous decl 00207 // keep track of the TypedefDecl. 00208 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 00209 TD->setTypedefForAnonDecl(Typedef); 00210 } 00211 00212 if (TypedefDecl *Prev = D->getPreviousDeclaration()) { 00213 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 00214 TemplateArgs); 00215 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev)); 00216 } 00217 00218 00219 Typedef->setAccess(D->getAccess()); 00220 Owner->addDecl(Typedef); 00221 00222 return Typedef; 00223 } 00224 00225 /// \brief Instantiate the arguments provided as part of initialization. 00226 /// 00227 /// \returns true if an error occurred, false otherwise. 00228 static bool InstantiateInitializationArguments(Sema &SemaRef, 00229 Expr **Args, unsigned NumArgs, 00230 const MultiLevelTemplateArgumentList &TemplateArgs, 00231 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs, 00232 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) { 00233 for (unsigned I = 0; I != NumArgs; ++I) { 00234 // When we hit the first defaulted argument, break out of the loop: 00235 // we don't pass those default arguments on. 00236 if (Args[I]->isDefaultArgument()) 00237 break; 00238 00239 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs); 00240 if (Arg.isInvalid()) 00241 return true; 00242 00243 Expr *ArgExpr = (Expr *)Arg.get(); 00244 InitArgs.push_back(Arg.release()); 00245 00246 // FIXME: We're faking all of the comma locations. Do we need them? 00247 FakeCommaLocs.push_back( 00248 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd())); 00249 } 00250 00251 return false; 00252 } 00253 00254 /// \brief Instantiate an initializer, breaking it into separate 00255 /// initialization arguments. 00256 /// 00257 /// \param S The semantic analysis object. 00258 /// 00259 /// \param Init The initializer to instantiate. 00260 /// 00261 /// \param TemplateArgs Template arguments to be substituted into the 00262 /// initializer. 00263 /// 00264 /// \param NewArgs Will be filled in with the instantiation arguments. 00265 /// 00266 /// \returns true if an error occurred, false otherwise 00267 static bool InstantiateInitializer(Sema &S, Expr *Init, 00268 const MultiLevelTemplateArgumentList &TemplateArgs, 00269 SourceLocation &LParenLoc, 00270 llvm::SmallVector<SourceLocation, 4> &CommaLocs, 00271 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs, 00272 SourceLocation &RParenLoc) { 00273 NewArgs.clear(); 00274 LParenLoc = SourceLocation(); 00275 RParenLoc = SourceLocation(); 00276 00277 if (!Init) 00278 return false; 00279 00280 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init)) 00281 Init = ExprTemp->getSubExpr(); 00282 00283 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init)) 00284 Init = Binder->getSubExpr(); 00285 00286 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init)) 00287 Init = ICE->getSubExprAsWritten(); 00288 00289 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 00290 LParenLoc = ParenList->getLParenLoc(); 00291 RParenLoc = ParenList->getRParenLoc(); 00292 return InstantiateInitializationArguments(S, ParenList->getExprs(), 00293 ParenList->getNumExprs(), 00294 TemplateArgs, CommaLocs, 00295 NewArgs); 00296 } 00297 00298 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) { 00299 if (!isa<CXXTemporaryObjectExpr>(Construct)) { 00300 if (InstantiateInitializationArguments(S, 00301 Construct->getArgs(), 00302 Construct->getNumArgs(), 00303 TemplateArgs, 00304 CommaLocs, NewArgs)) 00305 return true; 00306 00307 // FIXME: Fake locations! 00308 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart()); 00309 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back(); 00310 return false; 00311 } 00312 } 00313 00314 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs); 00315 if (Result.isInvalid()) 00316 return true; 00317 00318 NewArgs.push_back(Result.takeAs<Expr>()); 00319 return false; 00320 } 00321 00322 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 00323 // Do substitution on the type of the declaration 00324 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 00325 TemplateArgs, 00326 D->getTypeSpecStartLoc(), 00327 D->getDeclName()); 00328 if (!DI) 00329 return 0; 00330 00331 // Build the instantiated declaration 00332 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 00333 D->getLocation(), D->getIdentifier(), 00334 DI->getType(), DI, 00335 D->getStorageClass(), 00336 D->getStorageClassAsWritten()); 00337 Var->setThreadSpecified(D->isThreadSpecified()); 00338 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 00339 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 00340 00341 // Substitute the nested name specifier, if any. 00342 if (SubstQualifier(D, Var)) 00343 return 0; 00344 00345 // If we are instantiating a static data member defined 00346 // out-of-line, the instantiation will have the same lexical 00347 // context (which will be a namespace scope) as the template. 00348 if (D->isOutOfLine()) 00349 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 00350 00351 Var->setAccess(D->getAccess()); 00352 00353 // FIXME: In theory, we could have a previous declaration for variables that 00354 // are not static data members. 00355 bool Redeclaration = false; 00356 // FIXME: having to fake up a LookupResult is dumb. 00357 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 00358 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 00359 if (D->isStaticDataMember()) 00360 SemaRef.LookupQualifiedName(Previous, Owner, false); 00361 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 00362 00363 if (D->isOutOfLine()) { 00364 D->getLexicalDeclContext()->addDecl(Var); 00365 Owner->makeDeclVisibleInContext(Var); 00366 } else { 00367 Owner->addDecl(Var); 00368 00369 if (Owner->isFunctionOrMethod()) 00370 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var); 00371 } 00372 00373 // Link instantiations of static data members back to the template from 00374 // which they were instantiated. 00375 if (Var->isStaticDataMember()) 00376 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 00377 TSK_ImplicitInstantiation); 00378 00379 if (Var->getAnyInitializer()) { 00380 // We already have an initializer in the class. 00381 } else if (D->getInit()) { 00382 if (Var->isStaticDataMember() && !D->isOutOfLine()) 00383 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated); 00384 else 00385 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 00386 00387 // Instantiate the initializer. 00388 SourceLocation LParenLoc, RParenLoc; 00389 llvm::SmallVector<SourceLocation, 4> CommaLocs; 00390 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef); 00391 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc, 00392 CommaLocs, InitArgs, RParenLoc)) { 00393 // Attach the initializer to the declaration. 00394 if (D->hasCXXDirectInitializer()) { 00395 // Add the direct initializer to the declaration. 00396 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 00397 LParenLoc, 00398 move_arg(InitArgs), 00399 CommaLocs.data(), 00400 RParenLoc); 00401 } else if (InitArgs.size() == 1) { 00402 Expr *Init = (Expr*)(InitArgs.take()[0]); 00403 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), 00404 SemaRef.Owned(Init), 00405 false); 00406 } else { 00407 assert(InitArgs.size() == 0); 00408 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 00409 } 00410 } else { 00411 // FIXME: Not too happy about invalidating the declaration 00412 // because of a bogus initializer. 00413 Var->setInvalidDecl(); 00414 } 00415 00416 SemaRef.PopExpressionEvaluationContext(); 00417 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 00418 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 00419 00420 return Var; 00421 } 00422 00423 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 00424 bool Invalid = false; 00425 TypeSourceInfo *DI = D->getTypeSourceInfo(); 00426 if (DI->getType()->isDependentType()) { 00427 DI = SemaRef.SubstType(DI, TemplateArgs, 00428 D->getLocation(), D->getDeclName()); 00429 if (!DI) { 00430 DI = D->getTypeSourceInfo(); 00431 Invalid = true; 00432 } else if (DI->getType()->isFunctionType()) { 00433 // C++ [temp.arg.type]p3: 00434 // If a declaration acquires a function type through a type 00435 // dependent on a template-parameter and this causes a 00436 // declaration that does not use the syntactic form of a 00437 // function declarator to have function type, the program is 00438 // ill-formed. 00439 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 00440 << DI->getType(); 00441 Invalid = true; 00442 } 00443 } 00444 00445 Expr *BitWidth = D->getBitWidth(); 00446 if (Invalid) 00447 BitWidth = 0; 00448 else if (BitWidth) { 00449 // The bit-width expression is not potentially evaluated. 00450 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 00451 00452 OwningExprResult InstantiatedBitWidth 00453 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 00454 if (InstantiatedBitWidth.isInvalid()) { 00455 Invalid = true; 00456 BitWidth = 0; 00457 } else 00458 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 00459 } 00460 00461 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 00462 DI->getType(), DI, 00463 cast<RecordDecl>(Owner), 00464 D->getLocation(), 00465 D->isMutable(), 00466 BitWidth, 00467 D->getTypeSpecStartLoc(), 00468 D->getAccess(), 00469 0); 00470 if (!Field) { 00471 cast<Decl>(Owner)->setInvalidDecl(); 00472 return 0; 00473 } 00474 00475 InstantiateAttrs(D, Field); 00476 00477 if (Invalid) 00478 Field->setInvalidDecl(); 00479 00480 if (!Field->getDeclName()) { 00481 // Keep track of where this decl came from. 00482 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 00483 } 00484 00485 Field->setImplicit(D->isImplicit()); 00486 Field->setAccess(D->getAccess()); 00487 Owner->addDecl(Field); 00488 00489 return Field; 00490 } 00491 00492 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 00493 // Handle friend type expressions by simply substituting template 00494 // parameters into the pattern type and checking the result. 00495 if (TypeSourceInfo *Ty = D->getFriendType()) { 00496 TypeSourceInfo *InstTy = 00497 SemaRef.SubstType(Ty, TemplateArgs, 00498 D->getLocation(), DeclarationName()); 00499 if (!InstTy) 00500 return 0; 00501 00502 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy); 00503 if (!FD) 00504 return 0; 00505 00506 FD->setAccess(AS_public); 00507 Owner->addDecl(FD); 00508 return FD; 00509 } 00510 00511 NamedDecl *ND = D->getFriendDecl(); 00512 assert(ND && "friend decl must be a decl or a type!"); 00513 00514 // All of the Visit implementations for the various potential friend 00515 // declarations have to be carefully written to work for friend 00516 // objects, with the most important detail being that the target 00517 // decl should almost certainly not be placed in Owner. 00518 Decl *NewND = Visit(ND); 00519 if (!NewND) return 0; 00520 00521 FriendDecl *FD = 00522 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 00523 cast<NamedDecl>(NewND), D->getFriendLoc()); 00524 FD->setAccess(AS_public); 00525 Owner->addDecl(FD); 00526 return FD; 00527 } 00528 00529 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 00530 Expr *AssertExpr = D->getAssertExpr(); 00531 00532 // The expression in a static assertion is not potentially evaluated. 00533 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 00534 00535 OwningExprResult InstantiatedAssertExpr 00536 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 00537 if (InstantiatedAssertExpr.isInvalid()) 00538 return 0; 00539 00540 OwningExprResult Message(SemaRef, D->getMessage()); 00541 D->getMessage()->Retain(); 00542 Decl *StaticAssert 00543 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 00544 move(InstantiatedAssertExpr), 00545 move(Message)).getAs<Decl>(); 00546 return StaticAssert; 00547 } 00548 00549 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 00550 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 00551 D->getLocation(), D->getIdentifier(), 00552 D->getTagKeywordLoc(), 00553 /*PrevDecl=*/0); 00554 Enum->setInstantiationOfMemberEnum(D); 00555 Enum->setAccess(D->getAccess()); 00556 if (SubstQualifier(D, Enum)) return 0; 00557 Owner->addDecl(Enum); 00558 Enum->startDefinition(); 00559 00560 if (D->getDeclContext()->isFunctionOrMethod()) 00561 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 00562 00563 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 00564 00565 EnumConstantDecl *LastEnumConst = 0; 00566 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 00567 ECEnd = D->enumerator_end(); 00568 EC != ECEnd; ++EC) { 00569 // The specified value for the enumerator. 00570 OwningExprResult Value = SemaRef.Owned((Expr *)0); 00571 if (Expr *UninstValue = EC->getInitExpr()) { 00572 // The enumerator's value expression is not potentially evaluated. 00573 EnterExpressionEvaluationContext Unevaluated(SemaRef, 00574 Action::Unevaluated); 00575 00576 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 00577 } 00578 00579 // Drop the initial value and continue. 00580 bool isInvalid = false; 00581 if (Value.isInvalid()) { 00582 Value = SemaRef.Owned((Expr *)0); 00583 isInvalid = true; 00584 } 00585 00586 EnumConstantDecl *EnumConst 00587 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 00588 EC->getLocation(), EC->getIdentifier(), 00589 move(Value)); 00590 00591 if (isInvalid) { 00592 if (EnumConst) 00593 EnumConst->setInvalidDecl(); 00594 Enum->setInvalidDecl(); 00595 } 00596 00597 if (EnumConst) { 00598 EnumConst->setAccess(Enum->getAccess()); 00599 Enum->addDecl(EnumConst); 00600 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 00601 LastEnumConst = EnumConst; 00602 00603 if (D->getDeclContext()->isFunctionOrMethod()) { 00604 // If the enumeration is within a function or method, record the enum 00605 // constant as a local. 00606 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 00607 } 00608 } 00609 } 00610 00611 // FIXME: Fixup LBraceLoc and RBraceLoc 00612 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 00613 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 00614 Sema::DeclPtrTy::make(Enum), 00615 &Enumerators[0], Enumerators.size(), 00616 0, 0); 00617 00618 return Enum; 00619 } 00620 00621 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 00622 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 00623 return 0; 00624 } 00625 00626 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 00627 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 00628 00629 // Create a local instantiation scope for this class template, which 00630 // will contain the instantiations of the template parameters. 00631 Sema::LocalInstantiationScope Scope(SemaRef); 00632 TemplateParameterList *TempParams = D->getTemplateParameters(); 00633 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 00634 if (!InstParams) 00635 return NULL; 00636 00637 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 00638 00639 // Instantiate the qualifier. We have to do this first in case 00640 // we're a friend declaration, because if we are then we need to put 00641 // the new declaration in the appropriate context. 00642 NestedNameSpecifier *Qualifier = Pattern->getQualifier(); 00643 if (Qualifier) { 00644 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 00645 Pattern->getQualifierRange(), 00646 TemplateArgs); 00647 if (!Qualifier) return 0; 00648 } 00649 00650 CXXRecordDecl *PrevDecl = 0; 00651 ClassTemplateDecl *PrevClassTemplate = 0; 00652 00653 // If this isn't a friend, then it's a member template, in which 00654 // case we just want to build the instantiation in the 00655 // specialization. If it is a friend, we want to build it in 00656 // the appropriate context. 00657 DeclContext *DC = Owner; 00658 if (isFriend) { 00659 if (Qualifier) { 00660 CXXScopeSpec SS; 00661 SS.setScopeRep(Qualifier); 00662 SS.setRange(Pattern->getQualifierRange()); 00663 DC = SemaRef.computeDeclContext(SS); 00664 if (!DC) return 0; 00665 } else { 00666 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 00667 Pattern->getDeclContext(), 00668 TemplateArgs); 00669 } 00670 00671 // Look for a previous declaration of the template in the owning 00672 // context. 00673 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 00674 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 00675 SemaRef.LookupQualifiedName(R, DC); 00676 00677 if (R.isSingleResult()) { 00678 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 00679 if (PrevClassTemplate) 00680 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 00681 } 00682 00683 if (!PrevClassTemplate && Qualifier) { 00684 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 00685 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 00686 << Pattern->getQualifierRange(); 00687 return 0; 00688 } 00689 00690 bool AdoptedPreviousTemplateParams = false; 00691 if (PrevClassTemplate) { 00692 bool Complain = true; 00693 00694 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 00695 // template for struct std::tr1::__detail::_Map_base, where the 00696 // template parameters of the friend declaration don't match the 00697 // template parameters of the original declaration. In this one 00698 // case, we don't complain about the ill-formed friend 00699 // declaration. 00700 if (isFriend && Pattern->getIdentifier() && 00701 Pattern->getIdentifier()->isStr("_Map_base") && 00702 DC->isNamespace() && 00703 cast<NamespaceDecl>(DC)->getIdentifier() && 00704 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 00705 DeclContext *DCParent = DC->getParent(); 00706 if (DCParent->isNamespace() && 00707 cast<NamespaceDecl>(DCParent)->getIdentifier() && 00708 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 00709 DeclContext *DCParent2 = DCParent->getParent(); 00710 if (DCParent2->isNamespace() && 00711 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 00712 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 00713 DCParent2->getParent()->isTranslationUnit()) 00714 Complain = false; 00715 } 00716 } 00717 00718 TemplateParameterList *PrevParams 00719 = PrevClassTemplate->getTemplateParameters(); 00720 00721 // Make sure the parameter lists match. 00722 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 00723 Complain, 00724 Sema::TPL_TemplateMatch)) { 00725 if (Complain) 00726 return 0; 00727 00728 AdoptedPreviousTemplateParams = true; 00729 InstParams = PrevParams; 00730 } 00731 00732 // Do some additional validation, then merge default arguments 00733 // from the existing declarations. 00734 if (!AdoptedPreviousTemplateParams && 00735 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 00736 Sema::TPC_ClassTemplate)) 00737 return 0; 00738 } 00739 } 00740 00741 CXXRecordDecl *RecordInst 00742 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 00743 Pattern->getLocation(), Pattern->getIdentifier(), 00744 Pattern->getTagKeywordLoc(), PrevDecl, 00745 /*DelayTypeCreation=*/true); 00746 00747 if (Qualifier) 00748 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange()); 00749 00750 ClassTemplateDecl *Inst 00751 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 00752 D->getIdentifier(), InstParams, RecordInst, 00753 PrevClassTemplate); 00754 RecordInst->setDescribedClassTemplate(Inst); 00755 00756 if (isFriend) { 00757 if (PrevClassTemplate) 00758 Inst->setAccess(PrevClassTemplate->getAccess()); 00759 else 00760 Inst->setAccess(D->getAccess()); 00761 00762 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 00763 // TODO: do we want to track the instantiation progeny of this 00764 // friend target decl? 00765 } else { 00766 Inst->setAccess(D->getAccess()); 00767 Inst->setInstantiatedFromMemberTemplate(D); 00768 } 00769 00770 // Trigger creation of the type for the instantiation. 00771 SemaRef.Context.getInjectedClassNameType(RecordInst, 00772 Inst->getInjectedClassNameSpecialization(SemaRef.Context)); 00773 00774 // Finish handling of friends. 00775 if (isFriend) { 00776 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false); 00777 return Inst; 00778 } 00779 00780 Owner->addDecl(Inst); 00781 00782 // Instantiate all of the partial specializations of this member class 00783 // template. 00784 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 00785 D->getPartialSpecializations(PartialSpecs); 00786 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 00787 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 00788 00789 return Inst; 00790 } 00791 00792 Decl * 00793 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 00794 ClassTemplatePartialSpecializationDecl *D) { 00795 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 00796 00797 // Lookup the already-instantiated declaration in the instantiation 00798 // of the class template and return that. 00799 DeclContext::lookup_result Found 00800 = Owner->lookup(ClassTemplate->getDeclName()); 00801 if (Found.first == Found.second) 00802 return 0; 00803 00804 ClassTemplateDecl *InstClassTemplate 00805 = dyn_cast<ClassTemplateDecl>(*Found.first); 00806 if (!InstClassTemplate) 00807 return 0; 00808 00809 Decl *DCanon = D->getCanonicalDecl(); 00810 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 00811 P = InstClassTemplate->getPartialSpecializations().begin(), 00812 PEnd = InstClassTemplate->getPartialSpecializations().end(); 00813 P != PEnd; ++P) { 00814 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 00815 return &*P; 00816 } 00817 00818 return 0; 00819 } 00820 00821 Decl * 00822 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 00823 // Create a local instantiation scope for this function template, which 00824 // will contain the instantiations of the template parameters and then get 00825 // merged with the local instantiation scope for the function template 00826 // itself. 00827 Sema::LocalInstantiationScope Scope(SemaRef); 00828 00829 TemplateParameterList *TempParams = D->getTemplateParameters(); 00830 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 00831 if (!InstParams) 00832 return NULL; 00833 00834 FunctionDecl *Instantiated = 0; 00835 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 00836 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 00837 InstParams)); 00838 else 00839 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 00840 D->getTemplatedDecl(), 00841 InstParams)); 00842 00843 if (!Instantiated) 00844 return 0; 00845 00846 Instantiated->setAccess(D->getAccess()); 00847 00848 // Link the instantiated function template declaration to the function 00849 // template from which it was instantiated. 00850 FunctionTemplateDecl *InstTemplate 00851 = Instantiated->getDescribedFunctionTemplate(); 00852 InstTemplate->setAccess(D->getAccess()); 00853 assert(InstTemplate && 00854 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 00855 00856 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 00857 00858 // Link the instantiation back to the pattern *unless* this is a 00859 // non-definition friend declaration. 00860 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 00861 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 00862 InstTemplate->setInstantiatedFromMemberTemplate(D); 00863 00864 // Make declarations visible in the appropriate context. 00865 if (!isFriend) 00866 Owner->addDecl(InstTemplate); 00867 00868 return InstTemplate; 00869 } 00870 00871 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 00872 CXXRecordDecl *PrevDecl = 0; 00873 if (D->isInjectedClassName()) 00874 PrevDecl = cast<CXXRecordDecl>(Owner); 00875 else if (D->getPreviousDeclaration()) { 00876 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 00877 D->getPreviousDeclaration(), 00878 TemplateArgs); 00879 if (!Prev) return 0; 00880 PrevDecl = cast<CXXRecordDecl>(Prev); 00881 } 00882 00883 CXXRecordDecl *Record 00884 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 00885 D->getLocation(), D->getIdentifier(), 00886 D->getTagKeywordLoc(), PrevDecl); 00887 00888 // Substitute the nested name specifier, if any. 00889 if (SubstQualifier(D, Record)) 00890 return 0; 00891 00892 Record->setImplicit(D->isImplicit()); 00893 // FIXME: Check against AS_none is an ugly hack to work around the issue that 00894 // the tag decls introduced by friend class declarations don't have an access 00895 // specifier. Remove once this area of the code gets sorted out. 00896 if (D->getAccess() != AS_none) 00897 Record->setAccess(D->getAccess()); 00898 if (!D->isInjectedClassName()) 00899 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 00900 00901 // If the original function was part of a friend declaration, 00902 // inherit its namespace state. 00903 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 00904 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 00905 00906 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 00907 00908 Owner->addDecl(Record); 00909 return Record; 00910 } 00911 00912 /// Normal class members are of more specific types and therefore 00913 /// don't make it here. This function serves two purposes: 00914 /// 1) instantiating function templates 00915 /// 2) substituting friend declarations 00916 /// FIXME: preserve function definitions in case #2 00917 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 00918 TemplateParameterList *TemplateParams) { 00919 // Check whether there is already a function template specialization for 00920 // this declaration. 00921 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 00922 void *InsertPos = 0; 00923 if (FunctionTemplate && !TemplateParams) { 00924 llvm::FoldingSetNodeID ID; 00925 FunctionTemplateSpecializationInfo::Profile(ID, 00926 TemplateArgs.getInnermost().getFlatArgumentList(), 00927 TemplateArgs.getInnermost().flat_size(), 00928 SemaRef.Context); 00929 00930 FunctionTemplateSpecializationInfo *Info 00931 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 00932 InsertPos); 00933 00934 // If we already have a function template specialization, return it. 00935 if (Info) 00936 return Info->Function; 00937 } 00938 00939 bool isFriend; 00940 if (FunctionTemplate) 00941 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 00942 else 00943 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 00944 00945 bool MergeWithParentScope = (TemplateParams != 0) || 00946 !(isa<Decl>(Owner) && 00947 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 00948 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 00949 00950 llvm::SmallVector<ParmVarDecl *, 4> Params; 00951 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 00952 TInfo = SubstFunctionType(D, Params); 00953 if (!TInfo) 00954 return 0; 00955 QualType T = TInfo->getType(); 00956 00957 NestedNameSpecifier *Qualifier = D->getQualifier(); 00958 if (Qualifier) { 00959 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 00960 D->getQualifierRange(), 00961 TemplateArgs); 00962 if (!Qualifier) return 0; 00963 } 00964 00965 // If we're instantiating a local function declaration, put the result 00966 // in the owner; otherwise we need to find the instantiated context. 00967 DeclContext *DC; 00968 if (D->getDeclContext()->isFunctionOrMethod()) 00969 DC = Owner; 00970 else if (isFriend && Qualifier) { 00971 CXXScopeSpec SS; 00972 SS.setScopeRep(Qualifier); 00973 SS.setRange(D->getQualifierRange()); 00974 DC = SemaRef.computeDeclContext(SS); 00975 if (!DC) return 0; 00976 } else { 00977 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 00978 TemplateArgs); 00979 } 00980 00981 FunctionDecl *Function = 00982 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 00983 D->getDeclName(), T, TInfo, 00984 D->getStorageClass(), D->getStorageClassAsWritten(), 00985 D->isInlineSpecified(), D->hasWrittenPrototype()); 00986 00987 if (Qualifier) 00988 Function->setQualifierInfo(Qualifier, D->getQualifierRange()); 00989 00990 DeclContext *LexicalDC = Owner; 00991 if (!isFriend && D->isOutOfLine()) { 00992 assert(D->getDeclContext()->isFileContext()); 00993 LexicalDC = D->getDeclContext(); 00994 } 00995 00996 Function->setLexicalDeclContext(LexicalDC); 00997 00998 // Attach the parameters 00999 for (unsigned P = 0; P < Params.size(); ++P) 01000 Params[P]->setOwningFunction(Function); 01001 Function->setParams(Params.data(), Params.size()); 01002 01003 if (TemplateParams) { 01004 // Our resulting instantiation is actually a function template, since we 01005 // are substituting only the outer template parameters. For example, given 01006 // 01007 // template<typename T> 01008 // struct X { 01009 // template<typename U> friend void f(T, U); 01010 // }; 01011 // 01012 // X<int> x; 01013 // 01014 // We are instantiating the friend function template "f" within X<int>, 01015 // which means substituting int for T, but leaving "f" as a friend function 01016 // template. 01017 // Build the function template itself. 01018 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 01019 Function->getLocation(), 01020 Function->getDeclName(), 01021 TemplateParams, Function); 01022 Function->setDescribedFunctionTemplate(FunctionTemplate); 01023 01024 FunctionTemplate->setLexicalDeclContext(LexicalDC); 01025 01026 if (isFriend && D->isThisDeclarationADefinition()) { 01027 // TODO: should we remember this connection regardless of whether 01028 // the friend declaration provided a body? 01029 FunctionTemplate->setInstantiatedFromMemberTemplate( 01030 D->getDescribedFunctionTemplate()); 01031 } 01032 } else if (FunctionTemplate) { 01033 // Record this function template specialization. 01034 Function->setFunctionTemplateSpecialization(FunctionTemplate, 01035 &TemplateArgs.getInnermost(), 01036 InsertPos); 01037 } else if (isFriend && D->isThisDeclarationADefinition()) { 01038 // TODO: should we remember this connection regardless of whether 01039 // the friend declaration provided a body? 01040 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 01041 } 01042 01043 if (InitFunctionInstantiation(Function, D)) 01044 Function->setInvalidDecl(); 01045 01046 bool Redeclaration = false; 01047 bool OverloadableAttrRequired = false; 01048 bool isExplicitSpecialization = false; 01049 01050 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 01051 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 01052 01053 if (DependentFunctionTemplateSpecializationInfo *Info 01054 = D->getDependentSpecializationInfo()) { 01055 assert(isFriend && "non-friend has dependent specialization info?"); 01056 01057 // This needs to be set now for future sanity. 01058 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 01059 01060 // Instantiate the explicit template arguments. 01061 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 01062 Info->getRAngleLoc()); 01063 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) { 01064 TemplateArgumentLoc Loc; 01065 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs)) 01066 return 0; 01067 01068 ExplicitArgs.addArgument(Loc); 01069 } 01070 01071 // Map the candidate templates to their instantiations. 01072 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 01073 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 01074 Info->getTemplate(I), 01075 TemplateArgs); 01076 if (!Temp) return 0; 01077 01078 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 01079 } 01080 01081 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 01082 &ExplicitArgs, 01083 Previous)) 01084 Function->setInvalidDecl(); 01085 01086 isExplicitSpecialization = true; 01087 01088 } else if (TemplateParams || !FunctionTemplate) { 01089 // Look only into the namespace where the friend would be declared to 01090 // find a previous declaration. This is the innermost enclosing namespace, 01091 // as described in ActOnFriendFunctionDecl. 01092 SemaRef.LookupQualifiedName(Previous, DC); 01093 01094 // In C++, the previous declaration we find might be a tag type 01095 // (class or enum). In this case, the new declaration will hide the 01096 // tag type. Note that this does does not apply if we're declaring a 01097 // typedef (C++ [dcl.typedef]p4). 01098 if (Previous.isSingleTagDecl()) 01099 Previous.clear(); 01100 } 01101 01102 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 01103 isExplicitSpecialization, Redeclaration, 01104 /*FIXME:*/OverloadableAttrRequired); 01105 01106 NamedDecl *PrincipalDecl = (TemplateParams 01107 ? cast<NamedDecl>(FunctionTemplate) 01108 : Function); 01109 01110 // If the original function was part of a friend declaration, 01111 // inherit its namespace state and add it to the owner. 01112 if (isFriend) { 01113 NamedDecl *PrevDecl; 01114 if (TemplateParams) 01115 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 01116 else 01117 PrevDecl = Function->getPreviousDeclaration(); 01118 01119 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0); 01120 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false); 01121 } 01122 01123 if (Function->isOverloadedOperator() && !DC->isRecord() && 01124 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 01125 PrincipalDecl->setNonMemberOperator(); 01126 01127 return Function; 01128 } 01129 01130 Decl * 01131 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 01132 TemplateParameterList *TemplateParams) { 01133 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 01134 void *InsertPos = 0; 01135 if (FunctionTemplate && !TemplateParams) { 01136 // We are creating a function template specialization from a function 01137 // template. Check whether there is already a function template 01138 // specialization for this particular set of template arguments. 01139 llvm::FoldingSetNodeID ID; 01140 FunctionTemplateSpecializationInfo::Profile(ID, 01141 TemplateArgs.getInnermost().getFlatArgumentList(), 01142 TemplateArgs.getInnermost().flat_size(), 01143 SemaRef.Context); 01144 01145 FunctionTemplateSpecializationInfo *Info 01146 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 01147 InsertPos); 01148 01149 // If we already have a function template specialization, return it. 01150 if (Info) 01151 return Info->Function; 01152 } 01153 01154 bool isFriend; 01155 if (FunctionTemplate) 01156 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 01157 else 01158 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 01159 01160 bool MergeWithParentScope = (TemplateParams != 0) || 01161 !(isa<Decl>(Owner) && 01162 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 01163 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 01164 01165 llvm::SmallVector<ParmVarDecl *, 4> Params; 01166 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 01167 TInfo = SubstFunctionType(D, Params); 01168 if (!TInfo) 01169 return 0; 01170 QualType T = TInfo->getType(); 01171 01172 // \brief If the type of this function is not *directly* a function 01173 // type, then we're instantiating the a function that was declared 01174 // via a typedef, e.g., 01175 // 01176 // typedef int functype(int, int); 01177 // functype func; 01178 // 01179 // In this case, we'll just go instantiate the ParmVarDecls that we 01180 // synthesized in the method declaration. 01181 if (!isa<FunctionProtoType>(T)) { 01182 assert(!Params.size() && "Instantiating type could not yield parameters"); 01183 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) { 01184 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I), 01185 TemplateArgs); 01186 if (!P) 01187 return 0; 01188 01189 Params.push_back(P); 01190 } 01191 } 01192 01193 NestedNameSpecifier *Qualifier = D->getQualifier(); 01194 if (Qualifier) { 01195 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 01196 D->getQualifierRange(), 01197 TemplateArgs); 01198 if (!Qualifier) return 0; 01199 } 01200 01201 DeclContext *DC = Owner; 01202 if (isFriend) { 01203 if (Qualifier) { 01204 CXXScopeSpec SS; 01205 SS.setScopeRep(Qualifier); 01206 SS.setRange(D->getQualifierRange()); 01207 DC = SemaRef.computeDeclContext(SS); 01208 } else { 01209 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 01210 D->getDeclContext(), 01211 TemplateArgs); 01212 } 01213 if (!DC) return 0; 01214 } 01215 01216 // Build the instantiated method declaration. 01217 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 01218 CXXMethodDecl *Method = 0; 01219 01220 DeclarationName Name = D->getDeclName(); 01221 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 01222 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 01223 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 01224 SemaRef.Context.getCanonicalType(ClassTy)); 01225 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 01226 Constructor->getLocation(), 01227 Name, T, TInfo, 01228 Constructor->isExplicit(), 01229 Constructor->isInlineSpecified(), 01230 false); 01231 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 01232 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 01233 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 01234 SemaRef.Context.getCanonicalType(ClassTy)); 01235 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 01236 Destructor->getLocation(), Name, 01237 T, Destructor->isInlineSpecified(), 01238 false); 01239 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 01240 CanQualType ConvTy 01241 = SemaRef.Context.getCanonicalType( 01242 T->getAs<FunctionType>()->getResultType()); 01243 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 01244 ConvTy); 01245 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 01246 Conversion->getLocation(), Name, 01247 T, TInfo, 01248 Conversion->isInlineSpecified(), 01249 Conversion->isExplicit()); 01250 } else { 01251 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 01252 D->getDeclName(), T, TInfo, 01253 D->isStatic(), 01254 D->getStorageClassAsWritten(), 01255 D->isInlineSpecified()); 01256 } 01257 01258 if (Qualifier) 01259 Method->setQualifierInfo(Qualifier, D->getQualifierRange()); 01260 01261 if (TemplateParams) { 01262 // Our resulting instantiation is actually a function template, since we 01263 // are substituting only the outer template parameters. For example, given 01264 // 01265 // template<typename T> 01266 // struct X { 01267 // template<typename U> void f(T, U); 01268 // }; 01269 // 01270 // X<int> x; 01271 // 01272 // We are instantiating the member template "f" within X<int>, which means 01273 // substituting int for T, but leaving "f" as a member function template. 01274 // Build the function template itself. 01275 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 01276 Method->getLocation(), 01277 Method->getDeclName(), 01278 TemplateParams, Method); 01279 if (isFriend) { 01280 FunctionTemplate->setLexicalDeclContext(Owner); 01281 FunctionTemplate->setObjectOfFriendDecl(true); 01282 } else if (D->isOutOfLine()) 01283 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 01284 Method->setDescribedFunctionTemplate(FunctionTemplate); 01285 } else if (FunctionTemplate) { 01286 // Record this function template specialization. 01287 Method->setFunctionTemplateSpecialization(FunctionTemplate, 01288 &TemplateArgs.getInnermost(), 01289 InsertPos); 01290 } else if (!isFriend) { 01291 // Record that this is an instantiation of a member function. 01292 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 01293 } 01294 01295 // If we are instantiating a member function defined 01296 // out-of-line, the instantiation will have the same lexical 01297 // context (which will be a namespace scope) as the template. 01298 if (isFriend) { 01299 Method->setLexicalDeclContext(Owner); 01300 Method->setObjectOfFriendDecl(true); 01301 } else if (D->isOutOfLine()) 01302 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 01303 01304 // Attach the parameters 01305 for (unsigned P = 0; P < Params.size(); ++P) 01306 Params[P]->setOwningFunction(Method); 01307 Method->setParams(Params.data(), Params.size()); 01308 01309 if (InitMethodInstantiation(Method, D)) 01310 Method->setInvalidDecl(); 01311 01312 LookupResult Previous(SemaRef, Name, SourceLocation(), 01313 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 01314 01315 if (!FunctionTemplate || TemplateParams || isFriend) { 01316 SemaRef.LookupQualifiedName(Previous, Record); 01317 01318 // In C++, the previous declaration we find might be a tag type 01319 // (class or enum). In this case, the new declaration will hide the 01320 // tag type. Note that this does does not apply if we're declaring a 01321 // typedef (C++ [dcl.typedef]p4). 01322 if (Previous.isSingleTagDecl()) 01323 Previous.clear(); 01324 } 01325 01326 bool Redeclaration = false; 01327 bool OverloadableAttrRequired = false; 01328 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration, 01329 /*FIXME:*/OverloadableAttrRequired); 01330 01331 if (D->isPure()) 01332 SemaRef.CheckPureMethod(Method, SourceRange()); 01333 01334 Method->setAccess(D->getAccess()); 01335 01336 if (FunctionTemplate) { 01337 // If there's a function template, let our caller handle it. 01338 } else if (Method->isInvalidDecl() && !Previous.empty()) { 01339 // Don't hide a (potentially) valid declaration with an invalid one. 01340 } else { 01341 NamedDecl *DeclToAdd = (TemplateParams 01342 ? cast<NamedDecl>(FunctionTemplate) 01343 : Method); 01344 if (isFriend) 01345 Record->makeDeclVisibleInContext(DeclToAdd); 01346 else 01347 Owner->addDecl(DeclToAdd); 01348 } 01349 01350 return Method; 01351 } 01352 01353 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 01354 return VisitCXXMethodDecl(D); 01355 } 01356 01357 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 01358 return VisitCXXMethodDecl(D); 01359 } 01360 01361 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 01362 return VisitCXXMethodDecl(D); 01363 } 01364 01365 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 01366 return SemaRef.SubstParmVarDecl(D, TemplateArgs); 01367 } 01368 01369 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 01370 TemplateTypeParmDecl *D) { 01371 // TODO: don't always clone when decls are refcounted. 01372 const Type* T = D->getTypeForDecl(); 01373 assert(T->isTemplateTypeParmType()); 01374 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 01375 01376 TemplateTypeParmDecl *Inst = 01377 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 01378 TTPT->getDepth() - 1, TTPT->getIndex(), 01379 TTPT->getName(), 01380 D->wasDeclaredWithTypename(), 01381 D->isParameterPack()); 01382 01383 if (D->hasDefaultArgument()) 01384 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 01385 01386 // Introduce this template parameter's instantiation into the instantiation 01387 // scope. 01388 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 01389 01390 return Inst; 01391 } 01392 01393 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 01394 NonTypeTemplateParmDecl *D) { 01395 // Substitute into the type of the non-type template parameter. 01396 QualType T; 01397 TypeSourceInfo *DI = D->getTypeSourceInfo(); 01398 if (DI) { 01399 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 01400 D->getDeclName()); 01401 if (DI) T = DI->getType(); 01402 } else { 01403 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 01404 D->getDeclName()); 01405 DI = 0; 01406 } 01407 if (T.isNull()) 01408 return 0; 01409 01410 // Check that this type is acceptable for a non-type template parameter. 01411 bool Invalid = false; 01412 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 01413 if (T.isNull()) { 01414 T = SemaRef.Context.IntTy; 01415 Invalid = true; 01416 } 01417 01418 NonTypeTemplateParmDecl *Param 01419 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 01420 D->getDepth() - 1, D->getPosition(), 01421 D->getIdentifier(), T, DI); 01422 if (Invalid) 01423 Param->setInvalidDecl(); 01424 01425 Param->setDefaultArgument(D->getDefaultArgument()); 01426 01427 // Introduce this template parameter's instantiation into the instantiation 01428 // scope. 01429 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 01430 return Param; 01431 } 01432 01433 Decl * 01434 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 01435 TemplateTemplateParmDecl *D) { 01436 // Instantiate the template parameter list of the template template parameter. 01437 TemplateParameterList *TempParams = D->getTemplateParameters(); 01438 TemplateParameterList *InstParams; 01439 { 01440 // Perform the actual substitution of template parameters within a new, 01441 // local instantiation scope. 01442 Sema::LocalInstantiationScope Scope(SemaRef); 01443 InstParams = SubstTemplateParams(TempParams); 01444 if (!InstParams) 01445 return NULL; 01446 } 01447 01448 // Build the template template parameter. 01449 TemplateTemplateParmDecl *Param 01450 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 01451 D->getDepth() - 1, D->getPosition(), 01452 D->getIdentifier(), InstParams); 01453 Param->setDefaultArgument(D->getDefaultArgument()); 01454 01455 // Introduce this template parameter's instantiation into the instantiation 01456 // scope. 01457 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 01458 01459 return Param; 01460 } 01461 01462 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 01463 // Using directives are never dependent, so they require no explicit 01464 01465 UsingDirectiveDecl *Inst 01466 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 01467 D->getNamespaceKeyLocation(), 01468 D->getQualifierRange(), D->getQualifier(), 01469 D->getIdentLocation(), 01470 D->getNominatedNamespace(), 01471 D->getCommonAncestor()); 01472 Owner->addDecl(Inst); 01473 return Inst; 01474 } 01475 01476 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 01477 // The nested name specifier is non-dependent, so no transformation 01478 // is required. 01479 01480 // We only need to do redeclaration lookups if we're in a class 01481 // scope (in fact, it's not really even possible in non-class 01482 // scopes). 01483 bool CheckRedeclaration = Owner->isRecord(); 01484 01485 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(), 01486 Sema::LookupUsingDeclName, Sema::ForRedeclaration); 01487 01488 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 01489 D->getLocation(), 01490 D->getNestedNameRange(), 01491 D->getUsingLocation(), 01492 D->getTargetNestedNameDecl(), 01493 D->getDeclName(), 01494 D->isTypeName()); 01495 01496 CXXScopeSpec SS; 01497 SS.setScopeRep(D->getTargetNestedNameDecl()); 01498 SS.setRange(D->getNestedNameRange()); 01499 01500 if (CheckRedeclaration) { 01501 Prev.setHideTags(false); 01502 SemaRef.LookupQualifiedName(Prev, Owner); 01503 01504 // Check for invalid redeclarations. 01505 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 01506 D->isTypeName(), SS, 01507 D->getLocation(), Prev)) 01508 NewUD->setInvalidDecl(); 01509 01510 } 01511 01512 if (!NewUD->isInvalidDecl() && 01513 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 01514 D->getLocation())) 01515 NewUD->setInvalidDecl(); 01516 01517 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 01518 NewUD->setAccess(D->getAccess()); 01519 Owner->addDecl(NewUD); 01520 01521 // Don't process the shadow decls for an invalid decl. 01522 if (NewUD->isInvalidDecl()) 01523 return NewUD; 01524 01525 bool isFunctionScope = Owner->isFunctionOrMethod(); 01526 01527 // Process the shadow decls. 01528 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 01529 I != E; ++I) { 01530 UsingShadowDecl *Shadow = *I; 01531 NamedDecl *InstTarget = 01532 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(), 01533 Shadow->getTargetDecl(), 01534 TemplateArgs)); 01535 01536 if (CheckRedeclaration && 01537 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 01538 continue; 01539 01540 UsingShadowDecl *InstShadow 01541 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 01542 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 01543 01544 if (isFunctionScope) 01545 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 01546 } 01547 01548 return NewUD; 01549 } 01550 01551 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 01552 // Ignore these; we handle them in bulk when processing the UsingDecl. 01553 return 0; 01554 } 01555 01556 Decl * TemplateDeclInstantiator 01557 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 01558 NestedNameSpecifier *NNS = 01559 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 01560 D->getTargetNestedNameRange(), 01561 TemplateArgs); 01562 if (!NNS) 01563 return 0; 01564 01565 CXXScopeSpec SS; 01566 SS.setRange(D->getTargetNestedNameRange()); 01567 SS.setScopeRep(NNS); 01568 01569 NamedDecl *UD = 01570 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 01571 D->getUsingLoc(), SS, D->getLocation(), 01572 D->getDeclName(), 0, 01573 /*instantiation*/ true, 01574 /*typename*/ true, D->getTypenameLoc()); 01575 if (UD) 01576 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 01577 01578 return UD; 01579 } 01580 01581 Decl * TemplateDeclInstantiator 01582 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 01583 NestedNameSpecifier *NNS = 01584 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 01585 D->getTargetNestedNameRange(), 01586 TemplateArgs); 01587 if (!NNS) 01588 return 0; 01589 01590 CXXScopeSpec SS; 01591 SS.setRange(D->getTargetNestedNameRange()); 01592 SS.setScopeRep(NNS); 01593 01594 NamedDecl *UD = 01595 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 01596 D->getUsingLoc(), SS, D->getLocation(), 01597 D->getDeclName(), 0, 01598 /*instantiation*/ true, 01599 /*typename*/ false, SourceLocation()); 01600 if (UD) 01601 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 01602 01603 return UD; 01604 } 01605 01606 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 01607 const MultiLevelTemplateArgumentList &TemplateArgs) { 01608 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 01609 if (D->isInvalidDecl()) 01610 return 0; 01611 01612 return Instantiator.Visit(D); 01613 } 01614 01615 /// \brief Instantiates a nested template parameter list in the current 01616 /// instantiation context. 01617 /// 01618 /// \param L The parameter list to instantiate 01619 /// 01620 /// \returns NULL if there was an error 01621 TemplateParameterList * 01622 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 01623 // Get errors for all the parameters before bailing out. 01624 bool Invalid = false; 01625 01626 unsigned N = L->size(); 01627 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 01628 ParamVector Params; 01629 Params.reserve(N); 01630 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 01631 PI != PE; ++PI) { 01632 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 01633 Params.push_back(D); 01634 Invalid = Invalid || !D || D->isInvalidDecl(); 01635 } 01636 01637 // Clean up if we had an error. 01638 if (Invalid) { 01639 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 01640 PI != PE; ++PI) 01641 if (*PI) 01642 (*PI)->Destroy(SemaRef.Context); 01643 return NULL; 01644 } 01645 01646 TemplateParameterList *InstL 01647 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 01648 L->getLAngleLoc(), &Params.front(), N, 01649 L->getRAngleLoc()); 01650 return InstL; 01651 } 01652 01653 /// \brief Instantiate the declaration of a class template partial 01654 /// specialization. 01655 /// 01656 /// \param ClassTemplate the (instantiated) class template that is partially 01657 // specialized by the instantiation of \p PartialSpec. 01658 /// 01659 /// \param PartialSpec the (uninstantiated) class template partial 01660 /// specialization that we are instantiating. 01661 /// 01662 /// \returns true if there was an error, false otherwise. 01663 bool 01664 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 01665 ClassTemplateDecl *ClassTemplate, 01666 ClassTemplatePartialSpecializationDecl *PartialSpec) { 01667 // Create a local instantiation scope for this class template partial 01668 // specialization, which will contain the instantiations of the template 01669 // parameters. 01670 Sema::LocalInstantiationScope Scope(SemaRef); 01671 01672 // Substitute into the template parameters of the class template partial 01673 // specialization. 01674 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 01675 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 01676 if (!InstParams) 01677 return true; 01678 01679 // Substitute into the template arguments of the class template partial 01680 // specialization. 01681 const TemplateArgumentLoc *PartialSpecTemplateArgs 01682 = PartialSpec->getTemplateArgsAsWritten(); 01683 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 01684 01685 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 01686 for (unsigned I = 0; I != N; ++I) { 01687 TemplateArgumentLoc Loc; 01688 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs)) 01689 return true; 01690 InstTemplateArgs.addArgument(Loc); 01691 } 01692 01693 01694 // Check that the template argument list is well-formed for this 01695 // class template. 01696 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 01697 InstTemplateArgs.size()); 01698 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 01699 PartialSpec->getLocation(), 01700 InstTemplateArgs, 01701 false, 01702 Converted)) 01703 return true; 01704 01705 // Figure out where to insert this class template partial specialization 01706 // in the member template's set of class template partial specializations. 01707 llvm::FoldingSetNodeID ID; 01708 ClassTemplatePartialSpecializationDecl::Profile(ID, 01709 Converted.getFlatArguments(), 01710 Converted.flatSize(), 01711 SemaRef.Context); 01712 void *InsertPos = 0; 01713 ClassTemplateSpecializationDecl *PrevDecl 01714 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 01715 InsertPos); 01716 01717 // Build the canonical type that describes the converted template 01718 // arguments of the class template partial specialization. 01719 QualType CanonType 01720 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 01721 Converted.getFlatArguments(), 01722 Converted.flatSize()); 01723 01724 // Build the fully-sugared type for this class template 01725 // specialization as the user wrote in the specialization 01726 // itself. This means that we'll pretty-print the type retrieved 01727 // from the specialization's declaration the way that the user 01728 // actually wrote the specialization, rather than formatting the 01729 // name based on the "canonical" representation used to store the 01730 // template arguments in the specialization. 01731 TypeSourceInfo *WrittenTy 01732 = SemaRef.Context.getTemplateSpecializationTypeInfo( 01733 TemplateName(ClassTemplate), 01734 PartialSpec->getLocation(), 01735 InstTemplateArgs, 01736 CanonType); 01737 01738 if (PrevDecl) { 01739 // We've already seen a partial specialization with the same template 01740 // parameters and template arguments. This can happen, for example, when 01741 // substituting the outer template arguments ends up causing two 01742 // class template partial specializations of a member class template 01743 // to have identical forms, e.g., 01744 // 01745 // template<typename T, typename U> 01746 // struct Outer { 01747 // template<typename X, typename Y> struct Inner; 01748 // template<typename Y> struct Inner<T, Y>; 01749 // template<typename Y> struct Inner<U, Y>; 01750 // }; 01751 // 01752 // Outer<int, int> outer; // error: the partial specializations of Inner 01753 // // have the same signature. 01754 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 01755 << WrittenTy; 01756 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 01757 << SemaRef.Context.getTypeDeclType(PrevDecl); 01758 return true; 01759 } 01760 01761 01762 // Create the class template partial specialization declaration. 01763 ClassTemplatePartialSpecializationDecl *InstPartialSpec 01764 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 01765 PartialSpec->getTagKind(), 01766 Owner, 01767 PartialSpec->getLocation(), 01768 InstParams, 01769 ClassTemplate, 01770 Converted, 01771 InstTemplateArgs, 01772 CanonType, 01773 0, 01774 ClassTemplate->getPartialSpecializations().size()); 01775 // Substitute the nested name specifier, if any. 01776 if (SubstQualifier(PartialSpec, InstPartialSpec)) 01777 return 0; 01778 01779 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 01780 InstPartialSpec->setTypeAsWritten(WrittenTy); 01781 01782 // Add this partial specialization to the set of class template partial 01783 // specializations. 01784 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 01785 InsertPos); 01786 return false; 01787 } 01788 01789 TypeSourceInfo* 01790 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 01791 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 01792 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 01793 assert(OldTInfo && "substituting function without type source info"); 01794 assert(Params.empty() && "parameter vector is non-empty at start"); 01795 TypeSourceInfo *NewTInfo 01796 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 01797 D->getTypeSpecStartLoc(), 01798 D->getDeclName()); 01799 if (!NewTInfo) 01800 return 0; 01801 01802 if (NewTInfo != OldTInfo) { 01803 // Get parameters from the new type info. 01804 TypeLoc OldTL = OldTInfo->getTypeLoc(); 01805 if (FunctionProtoTypeLoc *OldProtoLoc 01806 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 01807 TypeLoc NewTL = NewTInfo->getTypeLoc(); 01808 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 01809 assert(NewProtoLoc && "Missing prototype?"); 01810 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) { 01811 // FIXME: Variadic templates will break this. 01812 Params.push_back(NewProtoLoc->getArg(i)); 01813 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 01814 OldProtoLoc->getArg(i), 01815 NewProtoLoc->getArg(i)); 01816 } 01817 } 01818 } else { 01819 // The function type itself was not dependent and therefore no 01820 // substitution occurred. However, we still need to instantiate 01821 // the function parameters themselves. 01822 TypeLoc OldTL = OldTInfo->getTypeLoc(); 01823 if (FunctionProtoTypeLoc *OldProtoLoc 01824 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 01825 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 01826 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 01827 if (!Parm) 01828 return 0; 01829 Params.push_back(Parm); 01830 } 01831 } 01832 } 01833 return NewTInfo; 01834 } 01835 01836 /// \brief Initializes the common fields of an instantiation function 01837 /// declaration (New) from the corresponding fields of its template (Tmpl). 01838 /// 01839 /// \returns true if there was an error 01840 bool 01841 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 01842 FunctionDecl *Tmpl) { 01843 if (Tmpl->isDeleted()) 01844 New->setDeleted(); 01845 01846 // If we are performing substituting explicitly-specified template arguments 01847 // or deduced template arguments into a function template and we reach this 01848 // point, we are now past the point where SFINAE applies and have committed 01849 // to keeping the new function template specialization. We therefore 01850 // convert the active template instantiation for the function template 01851 // into a template instantiation for this specific function template 01852 // specialization, which is not a SFINAE context, so that we diagnose any 01853 // further errors in the declaration itself. 01854 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 01855 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 01856 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 01857 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 01858 if (FunctionTemplateDecl *FunTmpl 01859 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 01860 assert(FunTmpl->getTemplatedDecl() == Tmpl && 01861 "Deduction from the wrong function template?"); 01862 (void) FunTmpl; 01863 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 01864 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 01865 --SemaRef.NonInstantiationEntries; 01866 } 01867 } 01868 01869 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 01870 assert(Proto && "Function template without prototype?"); 01871 01872 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() || 01873 Proto->getNoReturnAttr()) { 01874 // The function has an exception specification or a "noreturn" 01875 // attribute. Substitute into each of the exception types. 01876 llvm::SmallVector<QualType, 4> Exceptions; 01877 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 01878 // FIXME: Poor location information! 01879 QualType T 01880 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 01881 New->getLocation(), New->getDeclName()); 01882 if (T.isNull() || 01883 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 01884 continue; 01885 01886 Exceptions.push_back(T); 01887 } 01888 01889 // Rebuild the function type 01890 01891 const FunctionProtoType *NewProto 01892 = New->getType()->getAs<FunctionProtoType>(); 01893 assert(NewProto && "Template instantiation without function prototype?"); 01894 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 01895 NewProto->arg_type_begin(), 01896 NewProto->getNumArgs(), 01897 NewProto->isVariadic(), 01898 NewProto->getTypeQuals(), 01899 Proto->hasExceptionSpec(), 01900 Proto->hasAnyExceptionSpec(), 01901 Exceptions.size(), 01902 Exceptions.data(), 01903 Proto->getExtInfo())); 01904 } 01905 01906 return false; 01907 } 01908 01909 /// \brief Initializes common fields of an instantiated method 01910 /// declaration (New) from the corresponding fields of its template 01911 /// (Tmpl). 01912 /// 01913 /// \returns true if there was an error 01914 bool 01915 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 01916 CXXMethodDecl *Tmpl) { 01917 if (InitFunctionInstantiation(New, Tmpl)) 01918 return true; 01919 01920 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 01921 New->setAccess(Tmpl->getAccess()); 01922 if (Tmpl->isVirtualAsWritten()) 01923 Record->setMethodAsVirtual(New); 01924 01925 // FIXME: attributes 01926 // FIXME: New needs a pointer to Tmpl 01927 return false; 01928 } 01929 01930 /// \brief Instantiate the definition of the given function from its 01931 /// template. 01932 /// 01933 /// \param PointOfInstantiation the point at which the instantiation was 01934 /// required. Note that this is not precisely a "point of instantiation" 01935 /// for the function, but it's close. 01936 /// 01937 /// \param Function the already-instantiated declaration of a 01938 /// function template specialization or member function of a class template 01939 /// specialization. 01940 /// 01941 /// \param Recursive if true, recursively instantiates any functions that 01942 /// are required by this instantiation. 01943 /// 01944 /// \param DefinitionRequired if true, then we are performing an explicit 01945 /// instantiation where the body of the function is required. Complain if 01946 /// there is no such body. 01947 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 01948 FunctionDecl *Function, 01949 bool Recursive, 01950 bool DefinitionRequired) { 01951 if (Function->isInvalidDecl()) 01952 return; 01953 01954 assert(!Function->getBody() && "Already instantiated!"); 01955 01956 // Never instantiate an explicit specialization. 01957 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 01958 return; 01959 01960 // Find the function body that we'll be substituting. 01961 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 01962 Stmt *Pattern = 0; 01963 if (PatternDecl) 01964 Pattern = PatternDecl->getBody(PatternDecl); 01965 01966 if (!Pattern) { 01967 if (DefinitionRequired) { 01968 if (Function->getPrimaryTemplate()) 01969 Diag(PointOfInstantiation, 01970 diag::err_explicit_instantiation_undefined_func_template) 01971 << Function->getPrimaryTemplate(); 01972 else 01973 Diag(PointOfInstantiation, 01974 diag::err_explicit_instantiation_undefined_member) 01975 << 1 << Function->getDeclName() << Function->getDeclContext(); 01976 01977 if (PatternDecl) 01978 Diag(PatternDecl->getLocation(), 01979 diag::note_explicit_instantiation_here); 01980 } 01981 01982 return; 01983 } 01984 01985 // C++0x [temp.explicit]p9: 01986 // Except for inline functions, other explicit instantiation declarations 01987 // have the effect of suppressing the implicit instantiation of the entity 01988 // to which they refer. 01989 if (Function->getTemplateSpecializationKind() 01990 == TSK_ExplicitInstantiationDeclaration && 01991 !PatternDecl->isInlined()) 01992 return; 01993 01994 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 01995 if (Inst) 01996 return; 01997 01998 // If we're performing recursive template instantiation, create our own 01999 // queue of pending implicit instantiations that we will instantiate later, 02000 // while we're still within our own instantiation context. 02001 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 02002 if (Recursive) 02003 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 02004 02005 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 02006 02007 // Introduce a new scope where local variable instantiations will be 02008 // recorded, unless we're actually a member function within a local 02009 // class, in which case we need to merge our results with the parent 02010 // scope (of the enclosing function). 02011 bool MergeWithParentScope = false; 02012 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 02013 MergeWithParentScope = Rec->isLocalClass(); 02014 02015 LocalInstantiationScope Scope(*this, MergeWithParentScope); 02016 02017 // Introduce the instantiated function parameters into the local 02018 // instantiation scope. 02019 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 02020 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 02021 Function->getParamDecl(I)); 02022 02023 // Enter the scope of this instantiation. We don't use 02024 // PushDeclContext because we don't have a scope. 02025 DeclContext *PreviousContext = CurContext; 02026 CurContext = Function; 02027 02028 MultiLevelTemplateArgumentList TemplateArgs = 02029 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 02030 02031 // If this is a constructor, instantiate the member initializers. 02032 if (const CXXConstructorDecl *Ctor = 02033 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 02034 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 02035 TemplateArgs); 02036 } 02037 02038 // Instantiate the function body. 02039 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 02040 02041 if (Body.isInvalid()) 02042 Function->setInvalidDecl(); 02043 02044 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 02045 /*IsInstantiation=*/true); 02046 02047 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 02048 02049 CurContext = PreviousContext; 02050 02051 DeclGroupRef DG(Function); 02052 Consumer.HandleTopLevelDecl(DG); 02053 02054 // This class may have local implicit instantiations that need to be 02055 // instantiation within this scope. 02056 PerformPendingImplicitInstantiations(/*LocalOnly=*/true); 02057 Scope.Exit(); 02058 02059 if (Recursive) { 02060 // Instantiate any pending implicit instantiations found during the 02061 // instantiation of this template. 02062 PerformPendingImplicitInstantiations(); 02063 02064 // Restore the set of pending implicit instantiations. 02065 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 02066 } 02067 } 02068 02069 /// \brief Instantiate the definition of the given variable from its 02070 /// template. 02071 /// 02072 /// \param PointOfInstantiation the point at which the instantiation was 02073 /// required. Note that this is not precisely a "point of instantiation" 02074 /// for the function, but it's close. 02075 /// 02076 /// \param Var the already-instantiated declaration of a static member 02077 /// variable of a class template specialization. 02078 /// 02079 /// \param Recursive if true, recursively instantiates any functions that 02080 /// are required by this instantiation. 02081 /// 02082 /// \param DefinitionRequired if true, then we are performing an explicit 02083 /// instantiation where an out-of-line definition of the member variable 02084 /// is required. Complain if there is no such definition. 02085 void Sema::InstantiateStaticDataMemberDefinition( 02086 SourceLocation PointOfInstantiation, 02087 VarDecl *Var, 02088 bool Recursive, 02089 bool DefinitionRequired) { 02090 if (Var->isInvalidDecl()) 02091 return; 02092 02093 // Find the out-of-line definition of this static data member. 02094 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 02095 assert(Def && "This data member was not instantiated from a template?"); 02096 assert(Def->isStaticDataMember() && "Not a static data member?"); 02097 Def = Def->getOutOfLineDefinition(); 02098 02099 if (!Def) { 02100 // We did not find an out-of-line definition of this static data member, 02101 // so we won't perform any instantiation. Rather, we rely on the user to 02102 // instantiate this definition (or provide a specialization for it) in 02103 // another translation unit. 02104 if (DefinitionRequired) { 02105 Def = Var->getInstantiatedFromStaticDataMember(); 02106 Diag(PointOfInstantiation, 02107 diag::err_explicit_instantiation_undefined_member) 02108 << 2 << Var->getDeclName() << Var->getDeclContext(); 02109 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 02110 } 02111 02112 return; 02113 } 02114 02115 // Never instantiate an explicit specialization. 02116 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 02117 return; 02118 02119 // C++0x [temp.explicit]p9: 02120 // Except for inline functions, other explicit instantiation declarations 02121 // have the effect of suppressing the implicit instantiation of the entity 02122 // to which they refer. 02123 if (Var->getTemplateSpecializationKind() 02124 == TSK_ExplicitInstantiationDeclaration) 02125 return; 02126 02127 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 02128 if (Inst) 02129 return; 02130 02131 // If we're performing recursive template instantiation, create our own 02132 // queue of pending implicit instantiations that we will instantiate later, 02133 // while we're still within our own instantiation context. 02134 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 02135 if (Recursive) 02136 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 02137 02138 // Enter the scope of this instantiation. We don't use 02139 // PushDeclContext because we don't have a scope. 02140 DeclContext *PreviousContext = CurContext; 02141 CurContext = Var->getDeclContext(); 02142 02143 VarDecl *OldVar = Var; 02144 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 02145 getTemplateInstantiationArgs(Var))); 02146 CurContext = PreviousContext; 02147 02148 if (Var) { 02149 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 02150 assert(MSInfo && "Missing member specialization information?"); 02151 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 02152 MSInfo->getPointOfInstantiation()); 02153 DeclGroupRef DG(Var); 02154 Consumer.HandleTopLevelDecl(DG); 02155 } 02156 02157 if (Recursive) { 02158 // Instantiate any pending implicit instantiations found during the 02159 // instantiation of this template. 02160 PerformPendingImplicitInstantiations(); 02161 02162 // Restore the set of pending implicit instantiations. 02163 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 02164 } 02165 } 02166 02167 void 02168 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 02169 const CXXConstructorDecl *Tmpl, 02170 const MultiLevelTemplateArgumentList &TemplateArgs) { 02171 02172 llvm::SmallVector<MemInitTy*, 4> NewInits; 02173 bool AnyErrors = false; 02174 02175 // Instantiate all the initializers. 02176 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 02177 InitsEnd = Tmpl->init_end(); 02178 Inits != InitsEnd; ++Inits) { 02179 CXXBaseOrMemberInitializer *Init = *Inits; 02180 02181 SourceLocation LParenLoc, RParenLoc; 02182 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 02183 llvm::SmallVector<SourceLocation, 4> CommaLocs; 02184 02185 // Instantiate the initializer. 02186 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs, 02187 LParenLoc, CommaLocs, NewArgs, RParenLoc)) { 02188 AnyErrors = true; 02189 continue; 02190 } 02191 02192 MemInitResult NewInit; 02193 if (Init->isBaseInitializer()) { 02194 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 02195 TemplateArgs, 02196 Init->getSourceLocation(), 02197 New->getDeclName()); 02198 if (!BaseTInfo) { 02199 AnyErrors = true; 02200 New->setInvalidDecl(); 02201 continue; 02202 } 02203 02204 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, 02205 (Expr **)NewArgs.data(), 02206 NewArgs.size(), 02207 Init->getLParenLoc(), 02208 Init->getRParenLoc(), 02209 New->getParent()); 02210 } else if (Init->isMemberInitializer()) { 02211 FieldDecl *Member; 02212 02213 // Is this an anonymous union? 02214 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 02215 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 02216 UnionInit, TemplateArgs)); 02217 else 02218 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 02219 Init->getMember(), 02220 TemplateArgs)); 02221 02222 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 02223 NewArgs.size(), 02224 Init->getSourceLocation(), 02225 Init->getLParenLoc(), 02226 Init->getRParenLoc()); 02227 } 02228 02229 if (NewInit.isInvalid()) { 02230 AnyErrors = true; 02231 New->setInvalidDecl(); 02232 } else { 02233 // FIXME: It would be nice if ASTOwningVector had a release function. 02234 NewArgs.take(); 02235 02236 NewInits.push_back((MemInitTy *)NewInit.get()); 02237 } 02238 } 02239 02240 // Assign all the initializers to the new constructor. 02241 ActOnMemInitializers(DeclPtrTy::make(New), 02242 /*FIXME: ColonLoc */ 02243 SourceLocation(), 02244 NewInits.data(), NewInits.size(), 02245 AnyErrors); 02246 } 02247 02248 // TODO: this could be templated if the various decl types used the 02249 // same method name. 02250 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 02251 ClassTemplateDecl *Instance) { 02252 Pattern = Pattern->getCanonicalDecl(); 02253 02254 do { 02255 Instance = Instance->getCanonicalDecl(); 02256 if (Pattern == Instance) return true; 02257 Instance = Instance->getInstantiatedFromMemberTemplate(); 02258 } while (Instance); 02259 02260 return false; 02261 } 02262 02263 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 02264 FunctionTemplateDecl *Instance) { 02265 Pattern = Pattern->getCanonicalDecl(); 02266 02267 do { 02268 Instance = Instance->getCanonicalDecl(); 02269 if (Pattern == Instance) return true; 02270 Instance = Instance->getInstantiatedFromMemberTemplate(); 02271 } while (Instance); 02272 02273 return false; 02274 } 02275 02276 static bool 02277 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 02278 ClassTemplatePartialSpecializationDecl *Instance) { 02279 Pattern 02280 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 02281 do { 02282 Instance = cast<ClassTemplatePartialSpecializationDecl>( 02283 Instance->getCanonicalDecl()); 02284 if (Pattern == Instance) 02285 return true; 02286 Instance = Instance->getInstantiatedFromMember(); 02287 } while (Instance); 02288 02289 return false; 02290 } 02291 02292 static bool isInstantiationOf(CXXRecordDecl *Pattern, 02293 CXXRecordDecl *Instance) { 02294 Pattern = Pattern->getCanonicalDecl(); 02295 02296 do { 02297 Instance = Instance->getCanonicalDecl(); 02298 if (Pattern == Instance) return true; 02299 Instance = Instance->getInstantiatedFromMemberClass(); 02300 } while (Instance); 02301 02302 return false; 02303 } 02304 02305 static bool isInstantiationOf(FunctionDecl *Pattern, 02306 FunctionDecl *Instance) { 02307 Pattern = Pattern->getCanonicalDecl(); 02308 02309 do { 02310 Instance = Instance->getCanonicalDecl(); 02311 if (Pattern == Instance) return true; 02312 Instance = Instance->getInstantiatedFromMemberFunction(); 02313 } while (Instance); 02314 02315 return false; 02316 } 02317 02318 static bool isInstantiationOf(EnumDecl *Pattern, 02319 EnumDecl *Instance) { 02320 Pattern = Pattern->getCanonicalDecl(); 02321 02322 do { 02323 Instance = Instance->getCanonicalDecl(); 02324 if (Pattern == Instance) return true; 02325 Instance = Instance->getInstantiatedFromMemberEnum(); 02326 } while (Instance); 02327 02328 return false; 02329 } 02330 02331 static bool isInstantiationOf(UsingShadowDecl *Pattern, 02332 UsingShadowDecl *Instance, 02333 ASTContext &C) { 02334 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 02335 } 02336 02337 static bool isInstantiationOf(UsingDecl *Pattern, 02338 UsingDecl *Instance, 02339 ASTContext &C) { 02340 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 02341 } 02342 02343 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 02344 UsingDecl *Instance, 02345 ASTContext &C) { 02346 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 02347 } 02348 02349 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 02350 UsingDecl *Instance, 02351 ASTContext &C) { 02352 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 02353 } 02354 02355 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 02356 VarDecl *Instance) { 02357 assert(Instance->isStaticDataMember()); 02358 02359 Pattern = Pattern->getCanonicalDecl(); 02360 02361 do { 02362 Instance = Instance->getCanonicalDecl(); 02363 if (Pattern == Instance) return true; 02364 Instance = Instance->getInstantiatedFromStaticDataMember(); 02365 } while (Instance); 02366 02367 return false; 02368 } 02369 02370 // Other is the prospective instantiation 02371 // D is the prospective pattern 02372 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 02373 if (D->getKind() != Other->getKind()) { 02374 if (UnresolvedUsingTypenameDecl *UUD 02375 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 02376 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 02377 return isInstantiationOf(UUD, UD, Ctx); 02378 } 02379 } 02380 02381 if (UnresolvedUsingValueDecl *UUD 02382 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 02383 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 02384 return isInstantiationOf(UUD, UD, Ctx); 02385 } 02386 } 02387 02388 return false; 02389 } 02390 02391 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 02392 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 02393 02394 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 02395 return isInstantiationOf(cast<FunctionDecl>(D), Function); 02396 02397 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 02398 return isInstantiationOf(cast<EnumDecl>(D), Enum); 02399 02400 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 02401 if (Var->isStaticDataMember()) 02402 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 02403 02404 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 02405 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 02406 02407 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 02408 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 02409 02410 if (ClassTemplatePartialSpecializationDecl *PartialSpec 02411 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 02412 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 02413 PartialSpec); 02414 02415 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 02416 if (!Field->getDeclName()) { 02417 // This is an unnamed field. 02418 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 02419 cast<FieldDecl>(D); 02420 } 02421 } 02422 02423 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 02424 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 02425 02426 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 02427 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 02428 02429 return D->getDeclName() && isa<NamedDecl>(Other) && 02430 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 02431 } 02432 02433 template<typename ForwardIterator> 02434 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 02435 NamedDecl *D, 02436 ForwardIterator first, 02437 ForwardIterator last) { 02438 for (; first != last; ++first) 02439 if (isInstantiationOf(Ctx, D, *first)) 02440 return cast<NamedDecl>(*first); 02441 02442 return 0; 02443 } 02444 02445 /// \brief Finds the instantiation of the given declaration context 02446 /// within the current instantiation. 02447 /// 02448 /// \returns NULL if there was an error 02449 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 02450 const MultiLevelTemplateArgumentList &TemplateArgs) { 02451 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 02452 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 02453 return cast_or_null<DeclContext>(ID); 02454 } else return DC; 02455 } 02456 02457 /// \brief Find the instantiation of the given declaration within the 02458 /// current instantiation. 02459 /// 02460 /// This routine is intended to be used when \p D is a declaration 02461 /// referenced from within a template, that needs to mapped into the 02462 /// corresponding declaration within an instantiation. For example, 02463 /// given: 02464 /// 02465 /// \code 02466 /// template<typename T> 02467 /// struct X { 02468 /// enum Kind { 02469 /// KnownValue = sizeof(T) 02470 /// }; 02471 /// 02472 /// bool getKind() const { return KnownValue; } 02473 /// }; 02474 /// 02475 /// template struct X<int>; 02476 /// \endcode 02477 /// 02478 /// In the instantiation of X<int>::getKind(), we need to map the 02479 /// EnumConstantDecl for KnownValue (which refers to 02480 /// X<T>::<Kind>::KnownValue) to its instantiation 02481 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 02482 /// this mapping from within the instantiation of X<int>. 02483 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 02484 const MultiLevelTemplateArgumentList &TemplateArgs) { 02485 DeclContext *ParentDC = D->getDeclContext(); 02486 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 02487 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 02488 ParentDC->isFunctionOrMethod()) { 02489 // D is a local of some kind. Look into the map of local 02490 // declarations to their instantiations. 02491 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 02492 } 02493 02494 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 02495 if (!Record->isDependentContext()) 02496 return D; 02497 02498 // If the RecordDecl is actually the injected-class-name or a 02499 // "templated" declaration for a class template, class template 02500 // partial specialization, or a member class of a class template, 02501 // substitute into the injected-class-name of the class template 02502 // or partial specialization to find the new DeclContext. 02503 QualType T; 02504 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 02505 02506 if (ClassTemplate) { 02507 T = ClassTemplate->getInjectedClassNameSpecialization(Context); 02508 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 02509 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 02510 ClassTemplate = PartialSpec->getSpecializedTemplate(); 02511 02512 // If we call SubstType with an InjectedClassNameType here we 02513 // can end up in an infinite loop. 02514 T = Context.getTypeDeclType(Record); 02515 assert(isa<InjectedClassNameType>(T) && 02516 "type of partial specialization is not an InjectedClassNameType"); 02517 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 02518 } 02519 02520 if (!T.isNull()) { 02521 // Substitute into the injected-class-name to get the type 02522 // corresponding to the instantiation we want, which may also be 02523 // the current instantiation (if we're in a template 02524 // definition). This substitution should never fail, since we 02525 // know we can instantiate the injected-class-name or we 02526 // wouldn't have gotten to the injected-class-name! 02527 02528 // FIXME: Can we use the CurrentInstantiationScope to avoid this 02529 // extra instantiation in the common case? 02530 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 02531 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 02532 02533 if (!T->isDependentType()) { 02534 assert(T->isRecordType() && "Instantiation must produce a record type"); 02535 return T->getAs<RecordType>()->getDecl(); 02536 } 02537 02538 // We are performing "partial" template instantiation to create 02539 // the member declarations for the members of a class template 02540 // specialization. Therefore, D is actually referring to something 02541 // in the current instantiation. Look through the current 02542 // context, which contains actual instantiations, to find the 02543 // instantiation of the "current instantiation" that D refers 02544 // to. 02545 bool SawNonDependentContext = false; 02546 for (DeclContext *DC = CurContext; !DC->isFileContext(); 02547 DC = DC->getParent()) { 02548 if (ClassTemplateSpecializationDecl *Spec 02549 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 02550 if (isInstantiationOf(ClassTemplate, 02551 Spec->getSpecializedTemplate())) 02552 return Spec; 02553 02554 if (!DC->isDependentContext()) 02555 SawNonDependentContext = true; 02556 } 02557 02558 // We're performing "instantiation" of a member of the current 02559 // instantiation while we are type-checking the 02560 // definition. Compute the declaration context and return that. 02561 assert(!SawNonDependentContext && 02562 "No dependent context while instantiating record"); 02563 DeclContext *DC = computeDeclContext(T); 02564 assert(DC && 02565 "Unable to find declaration for the current instantiation"); 02566 return cast<CXXRecordDecl>(DC); 02567 } 02568 02569 // Fall through to deal with other dependent record types (e.g., 02570 // anonymous unions in class templates). 02571 } 02572 02573 if (!ParentDC->isDependentContext()) 02574 return D; 02575 02576 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 02577 if (!ParentDC) 02578 return 0; 02579 02580 if (ParentDC != D->getDeclContext()) { 02581 // We performed some kind of instantiation in the parent context, 02582 // so now we need to look into the instantiated parent context to 02583 // find the instantiation of the declaration D. 02584 02585 // If our context used to be dependent, we may need to instantiate 02586 // it before performing lookup into that context. 02587 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 02588 if (!Spec->isDependentContext()) { 02589 QualType T = Context.getTypeDeclType(Spec); 02590 const RecordType *Tag = T->getAs<RecordType>(); 02591 assert(Tag && "type of non-dependent record is not a RecordType"); 02592 if (!Tag->isBeingDefined() && 02593 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 02594 return 0; 02595 } 02596 } 02597 02598 NamedDecl *Result = 0; 02599 if (D->getDeclName()) { 02600 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 02601 Result = findInstantiationOf(Context, D, Found.first, Found.second); 02602 } else { 02603 // Since we don't have a name for the entity we're looking for, 02604 // our only option is to walk through all of the declarations to 02605 // find that name. This will occur in a few cases: 02606 // 02607 // - anonymous struct/union within a template 02608 // - unnamed class/struct/union/enum within a template 02609 // 02610 // FIXME: Find a better way to find these instantiations! 02611 Result = findInstantiationOf(Context, D, 02612 ParentDC->decls_begin(), 02613 ParentDC->decls_end()); 02614 } 02615 02616 // UsingShadowDecls can instantiate to nothing because of using hiding. 02617 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() || 02618 cast<Decl>(ParentDC)->isInvalidDecl()) 02619 && "Unable to find instantiation of declaration!"); 02620 02621 D = Result; 02622 } 02623 02624 return D; 02625 } 02626 02627 /// \brief Performs template instantiation for all implicit template 02628 /// instantiations we have seen until this point. 02629 void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) { 02630 while (!PendingLocalImplicitInstantiations.empty() || 02631 (!LocalOnly && !PendingImplicitInstantiations.empty())) { 02632 PendingImplicitInstantiation Inst; 02633 02634 if (PendingLocalImplicitInstantiations.empty()) { 02635 Inst = PendingImplicitInstantiations.front(); 02636 PendingImplicitInstantiations.pop_front(); 02637 } else { 02638 Inst = PendingLocalImplicitInstantiations.front(); 02639 PendingLocalImplicitInstantiations.pop_front(); 02640 } 02641 02642 // Instantiate function definitions 02643 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 02644 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 02645 Function->getLocation(), *this, 02646 Context.getSourceManager(), 02647 "instantiating function definition"); 02648 02649 if (!Function->getBody()) 02650 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 02651 continue; 02652 } 02653 02654 // Instantiate static data member definitions. 02655 VarDecl *Var = cast<VarDecl>(Inst.first); 02656 assert(Var->isStaticDataMember() && "Not a static data member?"); 02657 02658 // Don't try to instantiate declarations if the most recent redeclaration 02659 // is invalid. 02660 if (Var->getMostRecentDeclaration()->isInvalidDecl()) 02661 continue; 02662 02663 // Check if the most recent declaration has changed the specialization kind 02664 // and removed the need for implicit instantiation. 02665 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) { 02666 case TSK_Undeclared: 02667 assert(false && "Cannot instantitiate an undeclared specialization."); 02668 case TSK_ExplicitInstantiationDeclaration: 02669 case TSK_ExplicitInstantiationDefinition: 02670 case TSK_ExplicitSpecialization: 02671 continue; // No longer need implicit instantiation. 02672 case TSK_ImplicitInstantiation: 02673 break; 02674 } 02675 02676 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 02677 Var->getLocation(), *this, 02678 Context.getSourceManager(), 02679 "instantiating static data member " 02680 "definition"); 02681 02682 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 02683 } 02684 } 02685 02686 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 02687 const MultiLevelTemplateArgumentList &TemplateArgs) { 02688 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 02689 E = Pattern->ddiag_end(); I != E; ++I) { 02690 DependentDiagnostic *DD = *I; 02691 02692 switch (DD->getKind()) { 02693 case DependentDiagnostic::Access: 02694 HandleDependentAccessCheck(*DD, TemplateArgs); 02695 break; 02696 } 02697 } 02698 }