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 "clang/Sema/SemaInternal.h" 00013 #include "clang/AST/ASTConsumer.h" 00014 #include "clang/AST/ASTContext.h" 00015 #include "clang/AST/ASTMutationListener.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/Sema/Lookup.h" 00023 #include "clang/Sema/PrettyDeclStackTrace.h" 00024 #include "clang/Sema/Template.h" 00025 00026 using namespace clang; 00027 00028 static bool isDeclWithinFunction(const Decl *D) { 00029 const DeclContext *DC = D->getDeclContext(); 00030 if (DC->isFunctionOrMethod()) 00031 return true; 00032 00033 if (DC->isRecord()) 00034 return cast<CXXRecordDecl>(DC)->isLocalClass(); 00035 00036 return false; 00037 } 00038 00039 template<typename DeclT> 00040 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, 00041 const MultiLevelTemplateArgumentList &TemplateArgs) { 00042 if (!OldDecl->getQualifierLoc()) 00043 return false; 00044 00045 assert((NewDecl->getFriendObjectKind() || 00046 !OldDecl->getLexicalDeclContext()->isDependentContext()) && 00047 "non-friend with qualified name defined in dependent context"); 00048 Sema::ContextRAII SavedContext( 00049 SemaRef, 00050 const_cast<DeclContext *>(NewDecl->getFriendObjectKind() 00051 ? NewDecl->getLexicalDeclContext() 00052 : OldDecl->getLexicalDeclContext())); 00053 00054 NestedNameSpecifierLoc NewQualifierLoc 00055 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 00056 TemplateArgs); 00057 00058 if (!NewQualifierLoc) 00059 return true; 00060 00061 NewDecl->setQualifierInfo(NewQualifierLoc); 00062 return false; 00063 } 00064 00065 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 00066 DeclaratorDecl *NewDecl) { 00067 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); 00068 } 00069 00070 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 00071 TagDecl *NewDecl) { 00072 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); 00073 } 00074 00075 // Include attribute instantiation code. 00076 #include "clang/Sema/AttrTemplateInstantiate.inc" 00077 00078 static void instantiateDependentAlignedAttr( 00079 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 00080 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { 00081 if (Aligned->isAlignmentExpr()) { 00082 // The alignment expression is a constant expression. 00083 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated); 00084 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs); 00085 if (!Result.isInvalid()) 00086 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(), 00087 Aligned->getSpellingListIndex(), IsPackExpansion); 00088 } else { 00089 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 00090 TemplateArgs, Aligned->getLocation(), 00091 DeclarationName()); 00092 if (Result) 00093 S.AddAlignedAttr(Aligned->getLocation(), New, Result, 00094 Aligned->getSpellingListIndex(), IsPackExpansion); 00095 } 00096 } 00097 00098 static void instantiateDependentAlignedAttr( 00099 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 00100 const AlignedAttr *Aligned, Decl *New) { 00101 if (!Aligned->isPackExpansion()) { 00102 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 00103 return; 00104 } 00105 00106 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 00107 if (Aligned->isAlignmentExpr()) 00108 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 00109 Unexpanded); 00110 else 00111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 00112 Unexpanded); 00113 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 00114 00115 // Determine whether we can expand this attribute pack yet. 00116 bool Expand = true, RetainExpansion = false; 00117 Optional<unsigned> NumExpansions; 00118 // FIXME: Use the actual location of the ellipsis. 00119 SourceLocation EllipsisLoc = Aligned->getLocation(); 00120 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 00121 Unexpanded, TemplateArgs, Expand, 00122 RetainExpansion, NumExpansions)) 00123 return; 00124 00125 if (!Expand) { 00126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 00127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 00128 } else { 00129 for (unsigned I = 0; I != *NumExpansions; ++I) { 00130 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 00131 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 00132 } 00133 } 00134 } 00135 00136 static void instantiateDependentAssumeAlignedAttr( 00137 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 00138 const AssumeAlignedAttr *Aligned, Decl *New) { 00139 // The alignment expression is a constant expression. 00140 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated); 00141 00142 Expr *E, *OE = nullptr; 00143 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 00144 if (Result.isInvalid()) 00145 return; 00146 E = Result.getAs<Expr>(); 00147 00148 if (Aligned->getOffset()) { 00149 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs); 00150 if (Result.isInvalid()) 00151 return; 00152 OE = Result.getAs<Expr>(); 00153 } 00154 00155 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE, 00156 Aligned->getSpellingListIndex()); 00157 } 00158 00159 static void instantiateDependentAlignValueAttr( 00160 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 00161 const AlignValueAttr *Aligned, Decl *New) { 00162 // The alignment expression is a constant expression. 00163 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated); 00164 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 00165 if (!Result.isInvalid()) 00166 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(), 00167 Aligned->getSpellingListIndex()); 00168 } 00169 00170 static void instantiateDependentEnableIfAttr( 00171 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 00172 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) { 00173 Expr *Cond = nullptr; 00174 { 00175 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 00176 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs); 00177 if (Result.isInvalid()) 00178 return; 00179 Cond = Result.getAs<Expr>(); 00180 } 00181 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) { 00182 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 00183 if (Converted.isInvalid()) 00184 return; 00185 Cond = Converted.get(); 00186 } 00187 00188 SmallVector<PartialDiagnosticAt, 8> Diags; 00189 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() && 00190 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl), 00191 Diags)) { 00192 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr); 00193 for (int I = 0, N = Diags.size(); I != N; ++I) 00194 S.Diag(Diags[I].first, Diags[I].second); 00195 return; 00196 } 00197 00198 EnableIfAttr *EIA = new (S.getASTContext()) 00199 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond, 00200 A->getMessage(), 00201 A->getSpellingListIndex()); 00202 New->addAttr(EIA); 00203 } 00204 00205 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 00206 const Decl *Tmpl, Decl *New, 00207 LateInstantiatedAttrVec *LateAttrs, 00208 LocalInstantiationScope *OuterMostScope) { 00209 for (const auto *TmplAttr : Tmpl->attrs()) { 00210 // FIXME: This should be generalized to more than just the AlignedAttr. 00211 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 00212 if (Aligned && Aligned->isAlignmentDependent()) { 00213 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 00214 continue; 00215 } 00216 00217 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr); 00218 if (AssumeAligned) { 00219 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New); 00220 continue; 00221 } 00222 00223 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr); 00224 if (AlignValue) { 00225 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New); 00226 continue; 00227 } 00228 00229 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr); 00230 if (EnableIf && EnableIf->getCond()->isValueDependent()) { 00231 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, 00232 New); 00233 continue; 00234 } 00235 00236 // Existing DLL attribute on the instantiation takes precedence. 00237 if (TmplAttr->getKind() == attr::DLLExport || 00238 TmplAttr->getKind() == attr::DLLImport) { 00239 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) { 00240 continue; 00241 } 00242 } 00243 00244 assert(!TmplAttr->isPackExpansion()); 00245 if (TmplAttr->isLateParsed() && LateAttrs) { 00246 // Late parsed attributes must be instantiated and attached after the 00247 // enclosing class has been instantiated. See Sema::InstantiateClass. 00248 LocalInstantiationScope *Saved = nullptr; 00249 if (CurrentInstantiationScope) 00250 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 00251 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 00252 } else { 00253 // Allow 'this' within late-parsed attributes. 00254 NamedDecl *ND = dyn_cast<NamedDecl>(New); 00255 CXXRecordDecl *ThisContext = 00256 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 00257 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0, 00258 ND && ND->isCXXInstanceMember()); 00259 00260 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 00261 *this, TemplateArgs); 00262 if (NewAttr) 00263 New->addAttr(NewAttr); 00264 } 00265 } 00266 } 00267 00268 /// Get the previous declaration of a declaration for the purposes of template 00269 /// instantiation. If this finds a previous declaration, then the previous 00270 /// declaration of the instantiation of D should be an instantiation of the 00271 /// result of this function. 00272 template<typename DeclT> 00273 static DeclT *getPreviousDeclForInstantiation(DeclT *D) { 00274 DeclT *Result = D->getPreviousDecl(); 00275 00276 // If the declaration is within a class, and the previous declaration was 00277 // merged from a different definition of that class, then we don't have a 00278 // previous declaration for the purpose of template instantiation. 00279 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) && 00280 D->getLexicalDeclContext() != Result->getLexicalDeclContext()) 00281 return nullptr; 00282 00283 return Result; 00284 } 00285 00286 Decl * 00287 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 00288 llvm_unreachable("Translation units cannot be instantiated"); 00289 } 00290 00291 Decl * 00292 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 00293 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 00294 D->getIdentifier()); 00295 Owner->addDecl(Inst); 00296 return Inst; 00297 } 00298 00299 Decl * 00300 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 00301 llvm_unreachable("Namespaces cannot be instantiated"); 00302 } 00303 00304 Decl * 00305 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 00306 NamespaceAliasDecl *Inst 00307 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 00308 D->getNamespaceLoc(), 00309 D->getAliasLoc(), 00310 D->getIdentifier(), 00311 D->getQualifierLoc(), 00312 D->getTargetNameLoc(), 00313 D->getNamespace()); 00314 Owner->addDecl(Inst); 00315 return Inst; 00316 } 00317 00318 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 00319 bool IsTypeAlias) { 00320 bool Invalid = false; 00321 TypeSourceInfo *DI = D->getTypeSourceInfo(); 00322 if (DI->getType()->isInstantiationDependentType() || 00323 DI->getType()->isVariablyModifiedType()) { 00324 DI = SemaRef.SubstType(DI, TemplateArgs, 00325 D->getLocation(), D->getDeclName()); 00326 if (!DI) { 00327 Invalid = true; 00328 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 00329 } 00330 } else { 00331 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 00332 } 00333 00334 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 00335 // libstdc++ relies upon this bug in its implementation of common_type. 00336 // If we happen to be processing that implementation, fake up the g++ ?: 00337 // semantics. See LWG issue 2141 for more information on the bug. 00338 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 00339 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 00340 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 00341 DT->isReferenceType() && 00342 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 00343 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 00344 D->getIdentifier() && D->getIdentifier()->isStr("type") && 00345 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart())) 00346 // Fold it to the (non-reference) type which g++ would have produced. 00347 DI = SemaRef.Context.getTrivialTypeSourceInfo( 00348 DI->getType().getNonReferenceType()); 00349 00350 // Create the new typedef 00351 TypedefNameDecl *Typedef; 00352 if (IsTypeAlias) 00353 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 00354 D->getLocation(), D->getIdentifier(), DI); 00355 else 00356 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 00357 D->getLocation(), D->getIdentifier(), DI); 00358 if (Invalid) 00359 Typedef->setInvalidDecl(); 00360 00361 // If the old typedef was the name for linkage purposes of an anonymous 00362 // tag decl, re-establish that relationship for the new typedef. 00363 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 00364 TagDecl *oldTag = oldTagType->getDecl(); 00365 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 00366 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 00367 assert(!newTag->hasNameForLinkage()); 00368 newTag->setTypedefNameForAnonDecl(Typedef); 00369 } 00370 } 00371 00372 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) { 00373 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 00374 TemplateArgs); 00375 if (!InstPrev) 00376 return nullptr; 00377 00378 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 00379 00380 // If the typedef types are not identical, reject them. 00381 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 00382 00383 Typedef->setPreviousDecl(InstPrevTypedef); 00384 } 00385 00386 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 00387 00388 Typedef->setAccess(D->getAccess()); 00389 00390 return Typedef; 00391 } 00392 00393 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 00394 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 00395 if (Typedef) 00396 Owner->addDecl(Typedef); 00397 return Typedef; 00398 } 00399 00400 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 00401 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 00402 if (Typedef) 00403 Owner->addDecl(Typedef); 00404 return Typedef; 00405 } 00406 00407 Decl * 00408 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 00409 // Create a local instantiation scope for this type alias template, which 00410 // will contain the instantiations of the template parameters. 00411 LocalInstantiationScope Scope(SemaRef); 00412 00413 TemplateParameterList *TempParams = D->getTemplateParameters(); 00414 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 00415 if (!InstParams) 00416 return nullptr; 00417 00418 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 00419 00420 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr; 00421 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) { 00422 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 00423 if (!Found.empty()) { 00424 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front()); 00425 } 00426 } 00427 00428 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 00429 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 00430 if (!AliasInst) 00431 return nullptr; 00432 00433 TypeAliasTemplateDecl *Inst 00434 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 00435 D->getDeclName(), InstParams, AliasInst); 00436 AliasInst->setDescribedAliasTemplate(Inst); 00437 if (PrevAliasTemplate) 00438 Inst->setPreviousDecl(PrevAliasTemplate); 00439 00440 Inst->setAccess(D->getAccess()); 00441 00442 if (!PrevAliasTemplate) 00443 Inst->setInstantiatedFromMemberTemplate(D); 00444 00445 Owner->addDecl(Inst); 00446 00447 return Inst; 00448 } 00449 00450 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 00451 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); 00452 } 00453 00454 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, 00455 bool InstantiatingVarTemplate) { 00456 00457 // If this is the variable for an anonymous struct or union, 00458 // instantiate the anonymous struct/union type first. 00459 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 00460 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 00461 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 00462 return nullptr; 00463 00464 // Do substitution on the type of the declaration 00465 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 00466 TemplateArgs, 00467 D->getTypeSpecStartLoc(), 00468 D->getDeclName()); 00469 if (!DI) 00470 return nullptr; 00471 00472 if (DI->getType()->isFunctionType()) { 00473 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 00474 << D->isStaticDataMember() << DI->getType(); 00475 return nullptr; 00476 } 00477 00478 DeclContext *DC = Owner; 00479 if (D->isLocalExternDecl()) 00480 SemaRef.adjustContextForLocalExternDecl(DC); 00481 00482 // Build the instantiated declaration. 00483 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 00484 D->getLocation(), D->getIdentifier(), 00485 DI->getType(), DI, D->getStorageClass()); 00486 00487 // In ARC, infer 'retaining' for variables of retainable type. 00488 if (SemaRef.getLangOpts().ObjCAutoRefCount && 00489 SemaRef.inferObjCARCLifetime(Var)) 00490 Var->setInvalidDecl(); 00491 00492 // Substitute the nested name specifier, if any. 00493 if (SubstQualifier(D, Var)) 00494 return nullptr; 00495 00496 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 00497 StartingScope, InstantiatingVarTemplate); 00498 00499 if (D->isNRVOVariable()) { 00500 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType(); 00501 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false)) 00502 Var->setNRVOVariable(true); 00503 } 00504 00505 Var->setImplicit(D->isImplicit()); 00506 00507 return Var; 00508 } 00509 00510 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 00511 AccessSpecDecl* AD 00512 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 00513 D->getAccessSpecifierLoc(), D->getColonLoc()); 00514 Owner->addHiddenDecl(AD); 00515 return AD; 00516 } 00517 00518 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 00519 bool Invalid = false; 00520 TypeSourceInfo *DI = D->getTypeSourceInfo(); 00521 if (DI->getType()->isInstantiationDependentType() || 00522 DI->getType()->isVariablyModifiedType()) { 00523 DI = SemaRef.SubstType(DI, TemplateArgs, 00524 D->getLocation(), D->getDeclName()); 00525 if (!DI) { 00526 DI = D->getTypeSourceInfo(); 00527 Invalid = true; 00528 } else if (DI->getType()->isFunctionType()) { 00529 // C++ [temp.arg.type]p3: 00530 // If a declaration acquires a function type through a type 00531 // dependent on a template-parameter and this causes a 00532 // declaration that does not use the syntactic form of a 00533 // function declarator to have function type, the program is 00534 // ill-formed. 00535 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 00536 << DI->getType(); 00537 Invalid = true; 00538 } 00539 } else { 00540 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 00541 } 00542 00543 Expr *BitWidth = D->getBitWidth(); 00544 if (Invalid) 00545 BitWidth = nullptr; 00546 else if (BitWidth) { 00547 // The bit-width expression is a constant expression. 00548 EnterExpressionEvaluationContext Unevaluated(SemaRef, 00549 Sema::ConstantEvaluated); 00550 00551 ExprResult InstantiatedBitWidth 00552 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 00553 if (InstantiatedBitWidth.isInvalid()) { 00554 Invalid = true; 00555 BitWidth = nullptr; 00556 } else 00557 BitWidth = InstantiatedBitWidth.getAs<Expr>(); 00558 } 00559 00560 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 00561 DI->getType(), DI, 00562 cast<RecordDecl>(Owner), 00563 D->getLocation(), 00564 D->isMutable(), 00565 BitWidth, 00566 D->getInClassInitStyle(), 00567 D->getInnerLocStart(), 00568 D->getAccess(), 00569 nullptr); 00570 if (!Field) { 00571 cast<Decl>(Owner)->setInvalidDecl(); 00572 return nullptr; 00573 } 00574 00575 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 00576 00577 if (Field->hasAttrs()) 00578 SemaRef.CheckAlignasUnderalignment(Field); 00579 00580 if (Invalid) 00581 Field->setInvalidDecl(); 00582 00583 if (!Field->getDeclName()) { 00584 // Keep track of where this decl came from. 00585 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 00586 } 00587 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 00588 if (Parent->isAnonymousStructOrUnion() && 00589 Parent->getRedeclContext()->isFunctionOrMethod()) 00590 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 00591 } 00592 00593 Field->setImplicit(D->isImplicit()); 00594 Field->setAccess(D->getAccess()); 00595 Owner->addDecl(Field); 00596 00597 return Field; 00598 } 00599 00600 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { 00601 bool Invalid = false; 00602 TypeSourceInfo *DI = D->getTypeSourceInfo(); 00603 00604 if (DI->getType()->isVariablyModifiedType()) { 00605 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) 00606 << D; 00607 Invalid = true; 00608 } else if (DI->getType()->isInstantiationDependentType()) { 00609 DI = SemaRef.SubstType(DI, TemplateArgs, 00610 D->getLocation(), D->getDeclName()); 00611 if (!DI) { 00612 DI = D->getTypeSourceInfo(); 00613 Invalid = true; 00614 } else if (DI->getType()->isFunctionType()) { 00615 // C++ [temp.arg.type]p3: 00616 // If a declaration acquires a function type through a type 00617 // dependent on a template-parameter and this causes a 00618 // declaration that does not use the syntactic form of a 00619 // function declarator to have function type, the program is 00620 // ill-formed. 00621 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 00622 << DI->getType(); 00623 Invalid = true; 00624 } 00625 } else { 00626 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 00627 } 00628 00629 MSPropertyDecl *Property = MSPropertyDecl::Create( 00630 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(), 00631 DI, D->getLocStart(), D->getGetterId(), D->getSetterId()); 00632 00633 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, 00634 StartingScope); 00635 00636 if (Invalid) 00637 Property->setInvalidDecl(); 00638 00639 Property->setAccess(D->getAccess()); 00640 Owner->addDecl(Property); 00641 00642 return Property; 00643 } 00644 00645 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 00646 NamedDecl **NamedChain = 00647 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 00648 00649 int i = 0; 00650 for (auto *PI : D->chain()) { 00651 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI, 00652 TemplateArgs); 00653 if (!Next) 00654 return nullptr; 00655 00656 NamedChain[i++] = Next; 00657 } 00658 00659 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 00660 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 00661 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T, 00662 NamedChain, D->getChainingSize()); 00663 00664 for (const auto *Attr : D->attrs()) 00665 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 00666 00667 IndirectField->setImplicit(D->isImplicit()); 00668 IndirectField->setAccess(D->getAccess()); 00669 Owner->addDecl(IndirectField); 00670 return IndirectField; 00671 } 00672 00673 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 00674 // Handle friend type expressions by simply substituting template 00675 // parameters into the pattern type and checking the result. 00676 if (TypeSourceInfo *Ty = D->getFriendType()) { 00677 TypeSourceInfo *InstTy; 00678 // If this is an unsupported friend, don't bother substituting template 00679 // arguments into it. The actual type referred to won't be used by any 00680 // parts of Clang, and may not be valid for instantiating. Just use the 00681 // same info for the instantiated friend. 00682 if (D->isUnsupportedFriend()) { 00683 InstTy = Ty; 00684 } else { 00685 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 00686 D->getLocation(), DeclarationName()); 00687 } 00688 if (!InstTy) 00689 return nullptr; 00690 00691 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(), 00692 D->getFriendLoc(), InstTy); 00693 if (!FD) 00694 return nullptr; 00695 00696 FD->setAccess(AS_public); 00697 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 00698 Owner->addDecl(FD); 00699 return FD; 00700 } 00701 00702 NamedDecl *ND = D->getFriendDecl(); 00703 assert(ND && "friend decl must be a decl or a type!"); 00704 00705 // All of the Visit implementations for the various potential friend 00706 // declarations have to be carefully written to work for friend 00707 // objects, with the most important detail being that the target 00708 // decl should almost certainly not be placed in Owner. 00709 Decl *NewND = Visit(ND); 00710 if (!NewND) return nullptr; 00711 00712 FriendDecl *FD = 00713 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 00714 cast<NamedDecl>(NewND), D->getFriendLoc()); 00715 FD->setAccess(AS_public); 00716 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 00717 Owner->addDecl(FD); 00718 return FD; 00719 } 00720 00721 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 00722 Expr *AssertExpr = D->getAssertExpr(); 00723 00724 // The expression in a static assertion is a constant expression. 00725 EnterExpressionEvaluationContext Unevaluated(SemaRef, 00726 Sema::ConstantEvaluated); 00727 00728 ExprResult InstantiatedAssertExpr 00729 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 00730 if (InstantiatedAssertExpr.isInvalid()) 00731 return nullptr; 00732 00733 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 00734 InstantiatedAssertExpr.get(), 00735 D->getMessage(), 00736 D->getRParenLoc(), 00737 D->isFailed()); 00738 } 00739 00740 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 00741 EnumDecl *PrevDecl = nullptr; 00742 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { 00743 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 00744 PatternPrev, 00745 TemplateArgs); 00746 if (!Prev) return nullptr; 00747 PrevDecl = cast<EnumDecl>(Prev); 00748 } 00749 00750 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 00751 D->getLocation(), D->getIdentifier(), 00752 PrevDecl, D->isScoped(), 00753 D->isScopedUsingClassTag(), D->isFixed()); 00754 if (D->isFixed()) { 00755 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 00756 // If we have type source information for the underlying type, it means it 00757 // has been explicitly set by the user. Perform substitution on it before 00758 // moving on. 00759 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 00760 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 00761 DeclarationName()); 00762 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 00763 Enum->setIntegerType(SemaRef.Context.IntTy); 00764 else 00765 Enum->setIntegerTypeSourceInfo(NewTI); 00766 } else { 00767 assert(!D->getIntegerType()->isDependentType() 00768 && "Dependent type without type source info"); 00769 Enum->setIntegerType(D->getIntegerType()); 00770 } 00771 } 00772 00773 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 00774 00775 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 00776 Enum->setAccess(D->getAccess()); 00777 // Forward the mangling number from the template to the instantiated decl. 00778 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); 00779 if (SubstQualifier(D, Enum)) return nullptr; 00780 Owner->addDecl(Enum); 00781 00782 EnumDecl *Def = D->getDefinition(); 00783 if (Def && Def != D) { 00784 // If this is an out-of-line definition of an enum member template, check 00785 // that the underlying types match in the instantiation of both 00786 // declarations. 00787 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 00788 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 00789 QualType DefnUnderlying = 00790 SemaRef.SubstType(TI->getType(), TemplateArgs, 00791 UnderlyingLoc, DeclarationName()); 00792 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 00793 DefnUnderlying, Enum); 00794 } 00795 } 00796 00797 // C++11 [temp.inst]p1: The implicit instantiation of a class template 00798 // specialization causes the implicit instantiation of the declarations, but 00799 // not the definitions of scoped member enumerations. 00800 // 00801 // DR1484 clarifies that enumeration definitions inside of a template 00802 // declaration aren't considered entities that can be separately instantiated 00803 // from the rest of the entity they are declared inside of. 00804 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { 00805 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 00806 InstantiateEnumDefinition(Enum, Def); 00807 } 00808 00809 return Enum; 00810 } 00811 00812 void TemplateDeclInstantiator::InstantiateEnumDefinition( 00813 EnumDecl *Enum, EnumDecl *Pattern) { 00814 Enum->startDefinition(); 00815 00816 // Update the location to refer to the definition. 00817 Enum->setLocation(Pattern->getLocation()); 00818 00819 SmallVector<Decl*, 4> Enumerators; 00820 00821 EnumConstantDecl *LastEnumConst = nullptr; 00822 for (auto *EC : Pattern->enumerators()) { 00823 // The specified value for the enumerator. 00824 ExprResult Value((Expr *)nullptr); 00825 if (Expr *UninstValue = EC->getInitExpr()) { 00826 // The enumerator's value expression is a constant expression. 00827 EnterExpressionEvaluationContext Unevaluated(SemaRef, 00828 Sema::ConstantEvaluated); 00829 00830 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 00831 } 00832 00833 // Drop the initial value and continue. 00834 bool isInvalid = false; 00835 if (Value.isInvalid()) { 00836 Value = nullptr; 00837 isInvalid = true; 00838 } 00839 00840 EnumConstantDecl *EnumConst 00841 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 00842 EC->getLocation(), EC->getIdentifier(), 00843 Value.get()); 00844 00845 if (isInvalid) { 00846 if (EnumConst) 00847 EnumConst->setInvalidDecl(); 00848 Enum->setInvalidDecl(); 00849 } 00850 00851 if (EnumConst) { 00852 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst); 00853 00854 EnumConst->setAccess(Enum->getAccess()); 00855 Enum->addDecl(EnumConst); 00856 Enumerators.push_back(EnumConst); 00857 LastEnumConst = EnumConst; 00858 00859 if (Pattern->getDeclContext()->isFunctionOrMethod() && 00860 !Enum->isScoped()) { 00861 // If the enumeration is within a function or method, record the enum 00862 // constant as a local. 00863 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst); 00864 } 00865 } 00866 } 00867 00868 // FIXME: Fixup LBraceLoc 00869 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), 00870 Enum->getRBraceLoc(), Enum, 00871 Enumerators, 00872 nullptr, nullptr); 00873 } 00874 00875 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 00876 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 00877 } 00878 00879 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 00880 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 00881 00882 // Create a local instantiation scope for this class template, which 00883 // will contain the instantiations of the template parameters. 00884 LocalInstantiationScope Scope(SemaRef); 00885 TemplateParameterList *TempParams = D->getTemplateParameters(); 00886 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 00887 if (!InstParams) 00888 return nullptr; 00889 00890 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 00891 00892 // Instantiate the qualifier. We have to do this first in case 00893 // we're a friend declaration, because if we are then we need to put 00894 // the new declaration in the appropriate context. 00895 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 00896 if (QualifierLoc) { 00897 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 00898 TemplateArgs); 00899 if (!QualifierLoc) 00900 return nullptr; 00901 } 00902 00903 CXXRecordDecl *PrevDecl = nullptr; 00904 ClassTemplateDecl *PrevClassTemplate = nullptr; 00905 00906 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) { 00907 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 00908 if (!Found.empty()) { 00909 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front()); 00910 if (PrevClassTemplate) 00911 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 00912 } 00913 } 00914 00915 // If this isn't a friend, then it's a member template, in which 00916 // case we just want to build the instantiation in the 00917 // specialization. If it is a friend, we want to build it in 00918 // the appropriate context. 00919 DeclContext *DC = Owner; 00920 if (isFriend) { 00921 if (QualifierLoc) { 00922 CXXScopeSpec SS; 00923 SS.Adopt(QualifierLoc); 00924 DC = SemaRef.computeDeclContext(SS); 00925 if (!DC) return nullptr; 00926 } else { 00927 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 00928 Pattern->getDeclContext(), 00929 TemplateArgs); 00930 } 00931 00932 // Look for a previous declaration of the template in the owning 00933 // context. 00934 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 00935 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 00936 SemaRef.LookupQualifiedName(R, DC); 00937 00938 if (R.isSingleResult()) { 00939 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 00940 if (PrevClassTemplate) 00941 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 00942 } 00943 00944 if (!PrevClassTemplate && QualifierLoc) { 00945 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 00946 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 00947 << QualifierLoc.getSourceRange(); 00948 return nullptr; 00949 } 00950 00951 bool AdoptedPreviousTemplateParams = false; 00952 if (PrevClassTemplate) { 00953 bool Complain = true; 00954 00955 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 00956 // template for struct std::tr1::__detail::_Map_base, where the 00957 // template parameters of the friend declaration don't match the 00958 // template parameters of the original declaration. In this one 00959 // case, we don't complain about the ill-formed friend 00960 // declaration. 00961 if (isFriend && Pattern->getIdentifier() && 00962 Pattern->getIdentifier()->isStr("_Map_base") && 00963 DC->isNamespace() && 00964 cast<NamespaceDecl>(DC)->getIdentifier() && 00965 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 00966 DeclContext *DCParent = DC->getParent(); 00967 if (DCParent->isNamespace() && 00968 cast<NamespaceDecl>(DCParent)->getIdentifier() && 00969 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 00970 if (cast<Decl>(DCParent)->isInStdNamespace()) 00971 Complain = false; 00972 } 00973 } 00974 00975 TemplateParameterList *PrevParams 00976 = PrevClassTemplate->getTemplateParameters(); 00977 00978 // Make sure the parameter lists match. 00979 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 00980 Complain, 00981 Sema::TPL_TemplateMatch)) { 00982 if (Complain) 00983 return nullptr; 00984 00985 AdoptedPreviousTemplateParams = true; 00986 InstParams = PrevParams; 00987 } 00988 00989 // Do some additional validation, then merge default arguments 00990 // from the existing declarations. 00991 if (!AdoptedPreviousTemplateParams && 00992 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 00993 Sema::TPC_ClassTemplate)) 00994 return nullptr; 00995 } 00996 } 00997 00998 CXXRecordDecl *RecordInst 00999 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 01000 Pattern->getLocStart(), Pattern->getLocation(), 01001 Pattern->getIdentifier(), PrevDecl, 01002 /*DelayTypeCreation=*/true); 01003 01004 if (QualifierLoc) 01005 RecordInst->setQualifierInfo(QualifierLoc); 01006 01007 ClassTemplateDecl *Inst 01008 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 01009 D->getIdentifier(), InstParams, RecordInst, 01010 PrevClassTemplate); 01011 RecordInst->setDescribedClassTemplate(Inst); 01012 01013 if (isFriend) { 01014 if (PrevClassTemplate) 01015 Inst->setAccess(PrevClassTemplate->getAccess()); 01016 else 01017 Inst->setAccess(D->getAccess()); 01018 01019 Inst->setObjectOfFriendDecl(); 01020 // TODO: do we want to track the instantiation progeny of this 01021 // friend target decl? 01022 } else { 01023 Inst->setAccess(D->getAccess()); 01024 if (!PrevClassTemplate) 01025 Inst->setInstantiatedFromMemberTemplate(D); 01026 } 01027 01028 // Trigger creation of the type for the instantiation. 01029 SemaRef.Context.getInjectedClassNameType(RecordInst, 01030 Inst->getInjectedClassNameSpecialization()); 01031 01032 // Finish handling of friends. 01033 if (isFriend) { 01034 DC->makeDeclVisibleInContext(Inst); 01035 Inst->setLexicalDeclContext(Owner); 01036 RecordInst->setLexicalDeclContext(Owner); 01037 return Inst; 01038 } 01039 01040 if (D->isOutOfLine()) { 01041 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 01042 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 01043 } 01044 01045 Owner->addDecl(Inst); 01046 01047 if (!PrevClassTemplate) { 01048 // Queue up any out-of-line partial specializations of this member 01049 // class template; the client will force their instantiation once 01050 // the enclosing class has been instantiated. 01051 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 01052 D->getPartialSpecializations(PartialSpecs); 01053 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 01054 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 01055 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 01056 } 01057 01058 return Inst; 01059 } 01060 01061 Decl * 01062 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 01063 ClassTemplatePartialSpecializationDecl *D) { 01064 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 01065 01066 // Lookup the already-instantiated declaration in the instantiation 01067 // of the class template and return that. 01068 DeclContext::lookup_result Found 01069 = Owner->lookup(ClassTemplate->getDeclName()); 01070 if (Found.empty()) 01071 return nullptr; 01072 01073 ClassTemplateDecl *InstClassTemplate 01074 = dyn_cast<ClassTemplateDecl>(Found.front()); 01075 if (!InstClassTemplate) 01076 return nullptr; 01077 01078 if (ClassTemplatePartialSpecializationDecl *Result 01079 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 01080 return Result; 01081 01082 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 01083 } 01084 01085 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { 01086 assert(D->getTemplatedDecl()->isStaticDataMember() && 01087 "Only static data member templates are allowed."); 01088 01089 // Create a local instantiation scope for this variable template, which 01090 // will contain the instantiations of the template parameters. 01091 LocalInstantiationScope Scope(SemaRef); 01092 TemplateParameterList *TempParams = D->getTemplateParameters(); 01093 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 01094 if (!InstParams) 01095 return nullptr; 01096 01097 VarDecl *Pattern = D->getTemplatedDecl(); 01098 VarTemplateDecl *PrevVarTemplate = nullptr; 01099 01100 if (getPreviousDeclForInstantiation(Pattern)) { 01101 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 01102 if (!Found.empty()) 01103 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 01104 } 01105 01106 VarDecl *VarInst = 01107 cast_or_null<VarDecl>(VisitVarDecl(Pattern, 01108 /*InstantiatingVarTemplate=*/true)); 01109 01110 DeclContext *DC = Owner; 01111 01112 VarTemplateDecl *Inst = VarTemplateDecl::Create( 01113 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams, 01114 VarInst); 01115 VarInst->setDescribedVarTemplate(Inst); 01116 Inst->setPreviousDecl(PrevVarTemplate); 01117 01118 Inst->setAccess(D->getAccess()); 01119 if (!PrevVarTemplate) 01120 Inst->setInstantiatedFromMemberTemplate(D); 01121 01122 if (D->isOutOfLine()) { 01123 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 01124 VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); 01125 } 01126 01127 Owner->addDecl(Inst); 01128 01129 if (!PrevVarTemplate) { 01130 // Queue up any out-of-line partial specializations of this member 01131 // variable template; the client will force their instantiation once 01132 // the enclosing class has been instantiated. 01133 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 01134 D->getPartialSpecializations(PartialSpecs); 01135 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 01136 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 01137 OutOfLineVarPartialSpecs.push_back( 01138 std::make_pair(Inst, PartialSpecs[I])); 01139 } 01140 01141 return Inst; 01142 } 01143 01144 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( 01145 VarTemplatePartialSpecializationDecl *D) { 01146 assert(D->isStaticDataMember() && 01147 "Only static data member templates are allowed."); 01148 01149 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 01150 01151 // Lookup the already-instantiated declaration and return that. 01152 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName()); 01153 assert(!Found.empty() && "Instantiation found nothing?"); 01154 01155 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 01156 assert(InstVarTemplate && "Instantiation did not find a variable template?"); 01157 01158 if (VarTemplatePartialSpecializationDecl *Result = 01159 InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) 01160 return Result; 01161 01162 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D); 01163 } 01164 01165 Decl * 01166 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 01167 // Create a local instantiation scope for this function template, which 01168 // will contain the instantiations of the template parameters and then get 01169 // merged with the local instantiation scope for the function template 01170 // itself. 01171 LocalInstantiationScope Scope(SemaRef); 01172 01173 TemplateParameterList *TempParams = D->getTemplateParameters(); 01174 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 01175 if (!InstParams) 01176 return nullptr; 01177 01178 FunctionDecl *Instantiated = nullptr; 01179 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 01180 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 01181 InstParams)); 01182 else 01183 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 01184 D->getTemplatedDecl(), 01185 InstParams)); 01186 01187 if (!Instantiated) 01188 return nullptr; 01189 01190 // Link the instantiated function template declaration to the function 01191 // template from which it was instantiated. 01192 FunctionTemplateDecl *InstTemplate 01193 = Instantiated->getDescribedFunctionTemplate(); 01194 InstTemplate->setAccess(D->getAccess()); 01195 assert(InstTemplate && 01196 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 01197 01198 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 01199 01200 // Link the instantiation back to the pattern *unless* this is a 01201 // non-definition friend declaration. 01202 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 01203 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 01204 InstTemplate->setInstantiatedFromMemberTemplate(D); 01205 01206 // Make declarations visible in the appropriate context. 01207 if (!isFriend) { 01208 Owner->addDecl(InstTemplate); 01209 } else if (InstTemplate->getDeclContext()->isRecord() && 01210 !getPreviousDeclForInstantiation(D)) { 01211 SemaRef.CheckFriendAccess(InstTemplate); 01212 } 01213 01214 return InstTemplate; 01215 } 01216 01217 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 01218 CXXRecordDecl *PrevDecl = nullptr; 01219 if (D->isInjectedClassName()) 01220 PrevDecl = cast<CXXRecordDecl>(Owner); 01221 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { 01222 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 01223 PatternPrev, 01224 TemplateArgs); 01225 if (!Prev) return nullptr; 01226 PrevDecl = cast<CXXRecordDecl>(Prev); 01227 } 01228 01229 CXXRecordDecl *Record 01230 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 01231 D->getLocStart(), D->getLocation(), 01232 D->getIdentifier(), PrevDecl); 01233 01234 // Substitute the nested name specifier, if any. 01235 if (SubstQualifier(D, Record)) 01236 return nullptr; 01237 01238 Record->setImplicit(D->isImplicit()); 01239 // FIXME: Check against AS_none is an ugly hack to work around the issue that 01240 // the tag decls introduced by friend class declarations don't have an access 01241 // specifier. Remove once this area of the code gets sorted out. 01242 if (D->getAccess() != AS_none) 01243 Record->setAccess(D->getAccess()); 01244 if (!D->isInjectedClassName()) 01245 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 01246 01247 // If the original function was part of a friend declaration, 01248 // inherit its namespace state. 01249 if (D->getFriendObjectKind()) 01250 Record->setObjectOfFriendDecl(); 01251 01252 // Make sure that anonymous structs and unions are recorded. 01253 if (D->isAnonymousStructOrUnion()) 01254 Record->setAnonymousStructOrUnion(true); 01255 01256 if (D->isLocalClass()) 01257 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 01258 01259 // Forward the mangling number from the template to the instantiated decl. 01260 SemaRef.Context.setManglingNumber(Record, 01261 SemaRef.Context.getManglingNumber(D)); 01262 01263 Owner->addDecl(Record); 01264 01265 // DR1484 clarifies that the members of a local class are instantiated as part 01266 // of the instantiation of their enclosing entity. 01267 if (D->isCompleteDefinition() && D->isLocalClass()) { 01268 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs, 01269 TSK_ImplicitInstantiation, 01270 /*Complain=*/true); 01271 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs, 01272 TSK_ImplicitInstantiation); 01273 } 01274 01275 SemaRef.DiagnoseUnusedNestedTypedefs(Record); 01276 01277 return Record; 01278 } 01279 01280 /// \brief Adjust the given function type for an instantiation of the 01281 /// given declaration, to cope with modifications to the function's type that 01282 /// aren't reflected in the type-source information. 01283 /// 01284 /// \param D The declaration we're instantiating. 01285 /// \param TInfo The already-instantiated type. 01286 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, 01287 FunctionDecl *D, 01288 TypeSourceInfo *TInfo) { 01289 const FunctionProtoType *OrigFunc 01290 = D->getType()->castAs<FunctionProtoType>(); 01291 const FunctionProtoType *NewFunc 01292 = TInfo->getType()->castAs<FunctionProtoType>(); 01293 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) 01294 return TInfo->getType(); 01295 01296 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); 01297 NewEPI.ExtInfo = OrigFunc->getExtInfo(); 01298 return Context.getFunctionType(NewFunc->getReturnType(), 01299 NewFunc->getParamTypes(), NewEPI); 01300 } 01301 01302 /// Normal class members are of more specific types and therefore 01303 /// don't make it here. This function serves two purposes: 01304 /// 1) instantiating function templates 01305 /// 2) substituting friend declarations 01306 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 01307 TemplateParameterList *TemplateParams) { 01308 // Check whether there is already a function template specialization for 01309 // this declaration. 01310 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 01311 if (FunctionTemplate && !TemplateParams) { 01312 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 01313 01314 void *InsertPos = nullptr; 01315 FunctionDecl *SpecFunc 01316 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 01317 01318 // If we already have a function template specialization, return it. 01319 if (SpecFunc) 01320 return SpecFunc; 01321 } 01322 01323 bool isFriend; 01324 if (FunctionTemplate) 01325 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 01326 else 01327 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 01328 01329 bool MergeWithParentScope = (TemplateParams != nullptr) || 01330 Owner->isFunctionOrMethod() || 01331 !(isa<Decl>(Owner) && 01332 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 01333 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 01334 01335 SmallVector<ParmVarDecl *, 4> Params; 01336 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 01337 if (!TInfo) 01338 return nullptr; 01339 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 01340 01341 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 01342 if (QualifierLoc) { 01343 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 01344 TemplateArgs); 01345 if (!QualifierLoc) 01346 return nullptr; 01347 } 01348 01349 // If we're instantiating a local function declaration, put the result 01350 // in the enclosing namespace; otherwise we need to find the instantiated 01351 // context. 01352 DeclContext *DC; 01353 if (D->isLocalExternDecl()) { 01354 DC = Owner; 01355 SemaRef.adjustContextForLocalExternDecl(DC); 01356 } else if (isFriend && QualifierLoc) { 01357 CXXScopeSpec SS; 01358 SS.Adopt(QualifierLoc); 01359 DC = SemaRef.computeDeclContext(SS); 01360 if (!DC) return nullptr; 01361 } else { 01362 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 01363 TemplateArgs); 01364 } 01365 01366 FunctionDecl *Function = 01367 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 01368 D->getNameInfo(), T, TInfo, 01369 D->getCanonicalDecl()->getStorageClass(), 01370 D->isInlineSpecified(), D->hasWrittenPrototype(), 01371 D->isConstexpr()); 01372 Function->setRangeEnd(D->getSourceRange().getEnd()); 01373 01374 if (D->isInlined()) 01375 Function->setImplicitlyInline(); 01376 01377 if (QualifierLoc) 01378 Function->setQualifierInfo(QualifierLoc); 01379 01380 if (D->isLocalExternDecl()) 01381 Function->setLocalExternDecl(); 01382 01383 DeclContext *LexicalDC = Owner; 01384 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 01385 assert(D->getDeclContext()->isFileContext()); 01386 LexicalDC = D->getDeclContext(); 01387 } 01388 01389 Function->setLexicalDeclContext(LexicalDC); 01390 01391 // Attach the parameters 01392 for (unsigned P = 0; P < Params.size(); ++P) 01393 if (Params[P]) 01394 Params[P]->setOwningFunction(Function); 01395 Function->setParams(Params); 01396 01397 SourceLocation InstantiateAtPOI; 01398 if (TemplateParams) { 01399 // Our resulting instantiation is actually a function template, since we 01400 // are substituting only the outer template parameters. For example, given 01401 // 01402 // template<typename T> 01403 // struct X { 01404 // template<typename U> friend void f(T, U); 01405 // }; 01406 // 01407 // X<int> x; 01408 // 01409 // We are instantiating the friend function template "f" within X<int>, 01410 // which means substituting int for T, but leaving "f" as a friend function 01411 // template. 01412 // Build the function template itself. 01413 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 01414 Function->getLocation(), 01415 Function->getDeclName(), 01416 TemplateParams, Function); 01417 Function->setDescribedFunctionTemplate(FunctionTemplate); 01418 01419 FunctionTemplate->setLexicalDeclContext(LexicalDC); 01420 01421 if (isFriend && D->isThisDeclarationADefinition()) { 01422 // TODO: should we remember this connection regardless of whether 01423 // the friend declaration provided a body? 01424 FunctionTemplate->setInstantiatedFromMemberTemplate( 01425 D->getDescribedFunctionTemplate()); 01426 } 01427 } else if (FunctionTemplate) { 01428 // Record this function template specialization. 01429 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 01430 Function->setFunctionTemplateSpecialization(FunctionTemplate, 01431 TemplateArgumentList::CreateCopy(SemaRef.Context, 01432 Innermost.begin(), 01433 Innermost.size()), 01434 /*InsertPos=*/nullptr); 01435 } else if (isFriend) { 01436 // Note, we need this connection even if the friend doesn't have a body. 01437 // Its body may exist but not have been attached yet due to deferred 01438 // parsing. 01439 // FIXME: It might be cleaner to set this when attaching the body to the 01440 // friend function declaration, however that would require finding all the 01441 // instantiations and modifying them. 01442 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 01443 } 01444 01445 if (InitFunctionInstantiation(Function, D)) 01446 Function->setInvalidDecl(); 01447 01448 bool isExplicitSpecialization = false; 01449 01450 LookupResult Previous( 01451 SemaRef, Function->getDeclName(), SourceLocation(), 01452 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 01453 : Sema::LookupOrdinaryName, 01454 Sema::ForRedeclaration); 01455 01456 if (DependentFunctionTemplateSpecializationInfo *Info 01457 = D->getDependentSpecializationInfo()) { 01458 assert(isFriend && "non-friend has dependent specialization info?"); 01459 01460 // This needs to be set now for future sanity. 01461 Function->setObjectOfFriendDecl(); 01462 01463 // Instantiate the explicit template arguments. 01464 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 01465 Info->getRAngleLoc()); 01466 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 01467 ExplicitArgs, TemplateArgs)) 01468 return nullptr; 01469 01470 // Map the candidate templates to their instantiations. 01471 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 01472 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 01473 Info->getTemplate(I), 01474 TemplateArgs); 01475 if (!Temp) return nullptr; 01476 01477 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 01478 } 01479 01480 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 01481 &ExplicitArgs, 01482 Previous)) 01483 Function->setInvalidDecl(); 01484 01485 isExplicitSpecialization = true; 01486 01487 } else if (TemplateParams || !FunctionTemplate) { 01488 // Look only into the namespace where the friend would be declared to 01489 // find a previous declaration. This is the innermost enclosing namespace, 01490 // as described in ActOnFriendFunctionDecl. 01491 SemaRef.LookupQualifiedName(Previous, DC); 01492 01493 // In C++, the previous declaration we find might be a tag type 01494 // (class or enum). In this case, the new declaration will hide the 01495 // tag type. Note that this does does not apply if we're declaring a 01496 // typedef (C++ [dcl.typedef]p4). 01497 if (Previous.isSingleTagDecl()) 01498 Previous.clear(); 01499 } 01500 01501 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous, 01502 isExplicitSpecialization); 01503 01504 NamedDecl *PrincipalDecl = (TemplateParams 01505 ? cast<NamedDecl>(FunctionTemplate) 01506 : Function); 01507 01508 // If the original function was part of a friend declaration, 01509 // inherit its namespace state and add it to the owner. 01510 if (isFriend) { 01511 PrincipalDecl->setObjectOfFriendDecl(); 01512 DC->makeDeclVisibleInContext(PrincipalDecl); 01513 01514 bool QueuedInstantiation = false; 01515 01516 // C++11 [temp.friend]p4 (DR329): 01517 // When a function is defined in a friend function declaration in a class 01518 // template, the function is instantiated when the function is odr-used. 01519 // The same restrictions on multiple declarations and definitions that 01520 // apply to non-template function declarations and definitions also apply 01521 // to these implicit definitions. 01522 if (D->isThisDeclarationADefinition()) { 01523 // Check for a function body. 01524 const FunctionDecl *Definition = nullptr; 01525 if (Function->isDefined(Definition) && 01526 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 01527 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 01528 << Function->getDeclName(); 01529 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 01530 } 01531 // Check for redefinitions due to other instantiations of this or 01532 // a similar friend function. 01533 else for (auto R : Function->redecls()) { 01534 if (R == Function) 01535 continue; 01536 01537 // If some prior declaration of this function has been used, we need 01538 // to instantiate its definition. 01539 if (!QueuedInstantiation && R->isUsed(false)) { 01540 if (MemberSpecializationInfo *MSInfo = 01541 Function->getMemberSpecializationInfo()) { 01542 if (MSInfo->getPointOfInstantiation().isInvalid()) { 01543 SourceLocation Loc = R->getLocation(); // FIXME 01544 MSInfo->setPointOfInstantiation(Loc); 01545 SemaRef.PendingLocalImplicitInstantiations.push_back( 01546 std::make_pair(Function, Loc)); 01547 QueuedInstantiation = true; 01548 } 01549 } 01550 } 01551 01552 // If some prior declaration of this function was a friend with an 01553 // uninstantiated definition, reject it. 01554 if (R->getFriendObjectKind()) { 01555 if (const FunctionDecl *RPattern = 01556 R->getTemplateInstantiationPattern()) { 01557 if (RPattern->isDefined(RPattern)) { 01558 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 01559 << Function->getDeclName(); 01560 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 01561 break; 01562 } 01563 } 01564 } 01565 } 01566 } 01567 } 01568 01569 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 01570 DC->makeDeclVisibleInContext(PrincipalDecl); 01571 01572 if (Function->isOverloadedOperator() && !DC->isRecord() && 01573 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 01574 PrincipalDecl->setNonMemberOperator(); 01575 01576 assert(!D->isDefaulted() && "only methods should be defaulted"); 01577 return Function; 01578 } 01579 01580 Decl * 01581 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 01582 TemplateParameterList *TemplateParams, 01583 bool IsClassScopeSpecialization) { 01584 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 01585 if (FunctionTemplate && !TemplateParams) { 01586 // We are creating a function template specialization from a function 01587 // template. Check whether there is already a function template 01588 // specialization for this particular set of template arguments. 01589 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 01590 01591 void *InsertPos = nullptr; 01592 FunctionDecl *SpecFunc 01593 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 01594 01595 // If we already have a function template specialization, return it. 01596 if (SpecFunc) 01597 return SpecFunc; 01598 } 01599 01600 bool isFriend; 01601 if (FunctionTemplate) 01602 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 01603 else 01604 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 01605 01606 bool MergeWithParentScope = (TemplateParams != nullptr) || 01607 !(isa<Decl>(Owner) && 01608 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 01609 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 01610 01611 // Instantiate enclosing template arguments for friends. 01612 SmallVector<TemplateParameterList *, 4> TempParamLists; 01613 unsigned NumTempParamLists = 0; 01614 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 01615 TempParamLists.set_size(NumTempParamLists); 01616 for (unsigned I = 0; I != NumTempParamLists; ++I) { 01617 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 01618 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 01619 if (!InstParams) 01620 return nullptr; 01621 TempParamLists[I] = InstParams; 01622 } 01623 } 01624 01625 SmallVector<ParmVarDecl *, 4> Params; 01626 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 01627 if (!TInfo) 01628 return nullptr; 01629 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 01630 01631 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 01632 if (QualifierLoc) { 01633 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 01634 TemplateArgs); 01635 if (!QualifierLoc) 01636 return nullptr; 01637 } 01638 01639 DeclContext *DC = Owner; 01640 if (isFriend) { 01641 if (QualifierLoc) { 01642 CXXScopeSpec SS; 01643 SS.Adopt(QualifierLoc); 01644 DC = SemaRef.computeDeclContext(SS); 01645 01646 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 01647 return nullptr; 01648 } else { 01649 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 01650 D->getDeclContext(), 01651 TemplateArgs); 01652 } 01653 if (!DC) return nullptr; 01654 } 01655 01656 // Build the instantiated method declaration. 01657 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 01658 CXXMethodDecl *Method = nullptr; 01659 01660 SourceLocation StartLoc = D->getInnerLocStart(); 01661 DeclarationNameInfo NameInfo 01662 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 01663 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 01664 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 01665 StartLoc, NameInfo, T, TInfo, 01666 Constructor->isExplicit(), 01667 Constructor->isInlineSpecified(), 01668 false, Constructor->isConstexpr()); 01669 01670 // Claim that the instantiation of a constructor or constructor template 01671 // inherits the same constructor that the template does. 01672 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>( 01673 Constructor->getInheritedConstructor())) { 01674 // If we're instantiating a specialization of a function template, our 01675 // "inherited constructor" will actually itself be a function template. 01676 // Instantiate a declaration of it, too. 01677 if (FunctionTemplate) { 01678 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() && 01679 !Inh->getParent()->isDependentContext() && 01680 "inheriting constructor template in dependent context?"); 01681 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(), 01682 Inh); 01683 if (Inst.isInvalid()) 01684 return nullptr; 01685 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext()); 01686 LocalInstantiationScope LocalScope(SemaRef); 01687 01688 // Use the same template arguments that we deduced for the inheriting 01689 // constructor. There's no way they could be deduced differently. 01690 MultiLevelTemplateArgumentList InheritedArgs; 01691 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost()); 01692 Inh = cast_or_null<CXXConstructorDecl>( 01693 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs)); 01694 if (!Inh) 01695 return nullptr; 01696 } 01697 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh); 01698 } 01699 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 01700 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 01701 StartLoc, NameInfo, T, TInfo, 01702 Destructor->isInlineSpecified(), 01703 false); 01704 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 01705 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 01706 StartLoc, NameInfo, T, TInfo, 01707 Conversion->isInlineSpecified(), 01708 Conversion->isExplicit(), 01709 Conversion->isConstexpr(), 01710 Conversion->getLocEnd()); 01711 } else { 01712 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 01713 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 01714 StartLoc, NameInfo, T, TInfo, 01715 SC, D->isInlineSpecified(), 01716 D->isConstexpr(), D->getLocEnd()); 01717 } 01718 01719 if (D->isInlined()) 01720 Method->setImplicitlyInline(); 01721 01722 if (QualifierLoc) 01723 Method->setQualifierInfo(QualifierLoc); 01724 01725 if (TemplateParams) { 01726 // Our resulting instantiation is actually a function template, since we 01727 // are substituting only the outer template parameters. For example, given 01728 // 01729 // template<typename T> 01730 // struct X { 01731 // template<typename U> void f(T, U); 01732 // }; 01733 // 01734 // X<int> x; 01735 // 01736 // We are instantiating the member template "f" within X<int>, which means 01737 // substituting int for T, but leaving "f" as a member function template. 01738 // Build the function template itself. 01739 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 01740 Method->getLocation(), 01741 Method->getDeclName(), 01742 TemplateParams, Method); 01743 if (isFriend) { 01744 FunctionTemplate->setLexicalDeclContext(Owner); 01745 FunctionTemplate->setObjectOfFriendDecl(); 01746 } else if (D->isOutOfLine()) 01747 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 01748 Method->setDescribedFunctionTemplate(FunctionTemplate); 01749 } else if (FunctionTemplate) { 01750 // Record this function template specialization. 01751 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 01752 Method->setFunctionTemplateSpecialization(FunctionTemplate, 01753 TemplateArgumentList::CreateCopy(SemaRef.Context, 01754 Innermost.begin(), 01755 Innermost.size()), 01756 /*InsertPos=*/nullptr); 01757 } else if (!isFriend) { 01758 // Record that this is an instantiation of a member function. 01759 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 01760 } 01761 01762 // If we are instantiating a member function defined 01763 // out-of-line, the instantiation will have the same lexical 01764 // context (which will be a namespace scope) as the template. 01765 if (isFriend) { 01766 if (NumTempParamLists) 01767 Method->setTemplateParameterListsInfo(SemaRef.Context, 01768 NumTempParamLists, 01769 TempParamLists.data()); 01770 01771 Method->setLexicalDeclContext(Owner); 01772 Method->setObjectOfFriendDecl(); 01773 } else if (D->isOutOfLine()) 01774 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 01775 01776 // Attach the parameters 01777 for (unsigned P = 0; P < Params.size(); ++P) 01778 Params[P]->setOwningFunction(Method); 01779 Method->setParams(Params); 01780 01781 if (InitMethodInstantiation(Method, D)) 01782 Method->setInvalidDecl(); 01783 01784 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 01785 Sema::ForRedeclaration); 01786 01787 if (!FunctionTemplate || TemplateParams || isFriend) { 01788 SemaRef.LookupQualifiedName(Previous, Record); 01789 01790 // In C++, the previous declaration we find might be a tag type 01791 // (class or enum). In this case, the new declaration will hide the 01792 // tag type. Note that this does does not apply if we're declaring a 01793 // typedef (C++ [dcl.typedef]p4). 01794 if (Previous.isSingleTagDecl()) 01795 Previous.clear(); 01796 } 01797 01798 if (!IsClassScopeSpecialization) 01799 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false); 01800 01801 if (D->isPure()) 01802 SemaRef.CheckPureMethod(Method, SourceRange()); 01803 01804 // Propagate access. For a non-friend declaration, the access is 01805 // whatever we're propagating from. For a friend, it should be the 01806 // previous declaration we just found. 01807 if (isFriend && Method->getPreviousDecl()) 01808 Method->setAccess(Method->getPreviousDecl()->getAccess()); 01809 else 01810 Method->setAccess(D->getAccess()); 01811 if (FunctionTemplate) 01812 FunctionTemplate->setAccess(Method->getAccess()); 01813 01814 SemaRef.CheckOverrideControl(Method); 01815 01816 // If a function is defined as defaulted or deleted, mark it as such now. 01817 if (D->isExplicitlyDefaulted()) 01818 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 01819 if (D->isDeletedAsWritten()) 01820 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 01821 01822 // If there's a function template, let our caller handle it. 01823 if (FunctionTemplate) { 01824 // do nothing 01825 01826 // Don't hide a (potentially) valid declaration with an invalid one. 01827 } else if (Method->isInvalidDecl() && !Previous.empty()) { 01828 // do nothing 01829 01830 // Otherwise, check access to friends and make them visible. 01831 } else if (isFriend) { 01832 // We only need to re-check access for methods which we didn't 01833 // manage to match during parsing. 01834 if (!D->getPreviousDecl()) 01835 SemaRef.CheckFriendAccess(Method); 01836 01837 Record->makeDeclVisibleInContext(Method); 01838 01839 // Otherwise, add the declaration. We don't need to do this for 01840 // class-scope specializations because we'll have matched them with 01841 // the appropriate template. 01842 } else if (!IsClassScopeSpecialization) { 01843 Owner->addDecl(Method); 01844 } 01845 01846 return Method; 01847 } 01848 01849 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 01850 return VisitCXXMethodDecl(D); 01851 } 01852 01853 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 01854 return VisitCXXMethodDecl(D); 01855 } 01856 01857 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 01858 return VisitCXXMethodDecl(D); 01859 } 01860 01861 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 01862 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 01863 /*ExpectParameterPack=*/ false); 01864 } 01865 01866 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 01867 TemplateTypeParmDecl *D) { 01868 // TODO: don't always clone when decls are refcounted. 01869 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 01870 01871 TemplateTypeParmDecl *Inst = 01872 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 01873 D->getLocStart(), D->getLocation(), 01874 D->getDepth() - TemplateArgs.getNumLevels(), 01875 D->getIndex(), D->getIdentifier(), 01876 D->wasDeclaredWithTypename(), 01877 D->isParameterPack()); 01878 Inst->setAccess(AS_public); 01879 01880 if (D->hasDefaultArgument()) { 01881 TypeSourceInfo *InstantiatedDefaultArg = 01882 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 01883 D->getDefaultArgumentLoc(), D->getDeclName()); 01884 if (InstantiatedDefaultArg) 01885 Inst->setDefaultArgument(InstantiatedDefaultArg, false); 01886 } 01887 01888 // Introduce this template parameter's instantiation into the instantiation 01889 // scope. 01890 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 01891 01892 return Inst; 01893 } 01894 01895 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 01896 NonTypeTemplateParmDecl *D) { 01897 // Substitute into the type of the non-type template parameter. 01898 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 01899 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 01900 SmallVector<QualType, 4> ExpandedParameterPackTypes; 01901 bool IsExpandedParameterPack = false; 01902 TypeSourceInfo *DI; 01903 QualType T; 01904 bool Invalid = false; 01905 01906 if (D->isExpandedParameterPack()) { 01907 // The non-type template parameter pack is an already-expanded pack 01908 // expansion of types. Substitute into each of the expanded types. 01909 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 01910 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 01911 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 01912 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 01913 TemplateArgs, 01914 D->getLocation(), 01915 D->getDeclName()); 01916 if (!NewDI) 01917 return nullptr; 01918 01919 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 01920 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 01921 D->getLocation()); 01922 if (NewT.isNull()) 01923 return nullptr; 01924 ExpandedParameterPackTypes.push_back(NewT); 01925 } 01926 01927 IsExpandedParameterPack = true; 01928 DI = D->getTypeSourceInfo(); 01929 T = DI->getType(); 01930 } else if (D->isPackExpansion()) { 01931 // The non-type template parameter pack's type is a pack expansion of types. 01932 // Determine whether we need to expand this parameter pack into separate 01933 // types. 01934 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 01935 TypeLoc Pattern = Expansion.getPatternLoc(); 01936 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 01937 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 01938 01939 // Determine whether the set of unexpanded parameter packs can and should 01940 // be expanded. 01941 bool Expand = true; 01942 bool RetainExpansion = false; 01943 Optional<unsigned> OrigNumExpansions 01944 = Expansion.getTypePtr()->getNumExpansions(); 01945 Optional<unsigned> NumExpansions = OrigNumExpansions; 01946 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 01947 Pattern.getSourceRange(), 01948 Unexpanded, 01949 TemplateArgs, 01950 Expand, RetainExpansion, 01951 NumExpansions)) 01952 return nullptr; 01953 01954 if (Expand) { 01955 for (unsigned I = 0; I != *NumExpansions; ++I) { 01956 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 01957 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 01958 D->getLocation(), 01959 D->getDeclName()); 01960 if (!NewDI) 01961 return nullptr; 01962 01963 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 01964 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 01965 NewDI->getType(), 01966 D->getLocation()); 01967 if (NewT.isNull()) 01968 return nullptr; 01969 ExpandedParameterPackTypes.push_back(NewT); 01970 } 01971 01972 // Note that we have an expanded parameter pack. The "type" of this 01973 // expanded parameter pack is the original expansion type, but callers 01974 // will end up using the expanded parameter pack types for type-checking. 01975 IsExpandedParameterPack = true; 01976 DI = D->getTypeSourceInfo(); 01977 T = DI->getType(); 01978 } else { 01979 // We cannot fully expand the pack expansion now, so substitute into the 01980 // pattern and create a new pack expansion type. 01981 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 01982 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 01983 D->getLocation(), 01984 D->getDeclName()); 01985 if (!NewPattern) 01986 return nullptr; 01987 01988 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 01989 NumExpansions); 01990 if (!DI) 01991 return nullptr; 01992 01993 T = DI->getType(); 01994 } 01995 } else { 01996 // Simple case: substitution into a parameter that is not a parameter pack. 01997 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 01998 D->getLocation(), D->getDeclName()); 01999 if (!DI) 02000 return nullptr; 02001 02002 // Check that this type is acceptable for a non-type template parameter. 02003 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 02004 D->getLocation()); 02005 if (T.isNull()) { 02006 T = SemaRef.Context.IntTy; 02007 Invalid = true; 02008 } 02009 } 02010 02011 NonTypeTemplateParmDecl *Param; 02012 if (IsExpandedParameterPack) 02013 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 02014 D->getInnerLocStart(), 02015 D->getLocation(), 02016 D->getDepth() - TemplateArgs.getNumLevels(), 02017 D->getPosition(), 02018 D->getIdentifier(), T, 02019 DI, 02020 ExpandedParameterPackTypes.data(), 02021 ExpandedParameterPackTypes.size(), 02022 ExpandedParameterPackTypesAsWritten.data()); 02023 else 02024 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 02025 D->getInnerLocStart(), 02026 D->getLocation(), 02027 D->getDepth() - TemplateArgs.getNumLevels(), 02028 D->getPosition(), 02029 D->getIdentifier(), T, 02030 D->isParameterPack(), DI); 02031 02032 Param->setAccess(AS_public); 02033 if (Invalid) 02034 Param->setInvalidDecl(); 02035 02036 if (D->hasDefaultArgument()) { 02037 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 02038 if (!Value.isInvalid()) 02039 Param->setDefaultArgument(Value.get(), false); 02040 } 02041 02042 // Introduce this template parameter's instantiation into the instantiation 02043 // scope. 02044 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 02045 return Param; 02046 } 02047 02048 static void collectUnexpandedParameterPacks( 02049 Sema &S, 02050 TemplateParameterList *Params, 02051 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 02052 for (TemplateParameterList::const_iterator I = Params->begin(), 02053 E = Params->end(); I != E; ++I) { 02054 if ((*I)->isTemplateParameterPack()) 02055 continue; 02056 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I)) 02057 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 02058 Unexpanded); 02059 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I)) 02060 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 02061 Unexpanded); 02062 } 02063 } 02064 02065 Decl * 02066 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 02067 TemplateTemplateParmDecl *D) { 02068 // Instantiate the template parameter list of the template template parameter. 02069 TemplateParameterList *TempParams = D->getTemplateParameters(); 02070 TemplateParameterList *InstParams; 02071 SmallVector<TemplateParameterList*, 8> ExpandedParams; 02072 02073 bool IsExpandedParameterPack = false; 02074 02075 if (D->isExpandedParameterPack()) { 02076 // The template template parameter pack is an already-expanded pack 02077 // expansion of template parameters. Substitute into each of the expanded 02078 // parameters. 02079 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 02080 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 02081 I != N; ++I) { 02082 LocalInstantiationScope Scope(SemaRef); 02083 TemplateParameterList *Expansion = 02084 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 02085 if (!Expansion) 02086 return nullptr; 02087 ExpandedParams.push_back(Expansion); 02088 } 02089 02090 IsExpandedParameterPack = true; 02091 InstParams = TempParams; 02092 } else if (D->isPackExpansion()) { 02093 // The template template parameter pack expands to a pack of template 02094 // template parameters. Determine whether we need to expand this parameter 02095 // pack into separate parameters. 02096 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 02097 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 02098 Unexpanded); 02099 02100 // Determine whether the set of unexpanded parameter packs can and should 02101 // be expanded. 02102 bool Expand = true; 02103 bool RetainExpansion = false; 02104 Optional<unsigned> NumExpansions; 02105 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 02106 TempParams->getSourceRange(), 02107 Unexpanded, 02108 TemplateArgs, 02109 Expand, RetainExpansion, 02110 NumExpansions)) 02111 return nullptr; 02112 02113 if (Expand) { 02114 for (unsigned I = 0; I != *NumExpansions; ++I) { 02115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 02116 LocalInstantiationScope Scope(SemaRef); 02117 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 02118 if (!Expansion) 02119 return nullptr; 02120 ExpandedParams.push_back(Expansion); 02121 } 02122 02123 // Note that we have an expanded parameter pack. The "type" of this 02124 // expanded parameter pack is the original expansion type, but callers 02125 // will end up using the expanded parameter pack types for type-checking. 02126 IsExpandedParameterPack = true; 02127 InstParams = TempParams; 02128 } else { 02129 // We cannot fully expand the pack expansion now, so just substitute 02130 // into the pattern. 02131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 02132 02133 LocalInstantiationScope Scope(SemaRef); 02134 InstParams = SubstTemplateParams(TempParams); 02135 if (!InstParams) 02136 return nullptr; 02137 } 02138 } else { 02139 // Perform the actual substitution of template parameters within a new, 02140 // local instantiation scope. 02141 LocalInstantiationScope Scope(SemaRef); 02142 InstParams = SubstTemplateParams(TempParams); 02143 if (!InstParams) 02144 return nullptr; 02145 } 02146 02147 // Build the template template parameter. 02148 TemplateTemplateParmDecl *Param; 02149 if (IsExpandedParameterPack) 02150 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 02151 D->getLocation(), 02152 D->getDepth() - TemplateArgs.getNumLevels(), 02153 D->getPosition(), 02154 D->getIdentifier(), InstParams, 02155 ExpandedParams); 02156 else 02157 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 02158 D->getLocation(), 02159 D->getDepth() - TemplateArgs.getNumLevels(), 02160 D->getPosition(), 02161 D->isParameterPack(), 02162 D->getIdentifier(), InstParams); 02163 if (D->hasDefaultArgument()) { 02164 NestedNameSpecifierLoc QualifierLoc = 02165 D->getDefaultArgument().getTemplateQualifierLoc(); 02166 QualifierLoc = 02167 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 02168 TemplateName TName = SemaRef.SubstTemplateName( 02169 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 02170 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 02171 if (!TName.isNull()) 02172 Param->setDefaultArgument( 02173 TemplateArgumentLoc(TemplateArgument(TName), 02174 D->getDefaultArgument().getTemplateQualifierLoc(), 02175 D->getDefaultArgument().getTemplateNameLoc()), 02176 false); 02177 } 02178 Param->setAccess(AS_public); 02179 02180 // Introduce this template parameter's instantiation into the instantiation 02181 // scope. 02182 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 02183 02184 return Param; 02185 } 02186 02187 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 02188 // Using directives are never dependent (and never contain any types or 02189 // expressions), so they require no explicit instantiation work. 02190 02191 UsingDirectiveDecl *Inst 02192 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 02193 D->getNamespaceKeyLocation(), 02194 D->getQualifierLoc(), 02195 D->getIdentLocation(), 02196 D->getNominatedNamespace(), 02197 D->getCommonAncestor()); 02198 02199 // Add the using directive to its declaration context 02200 // only if this is not a function or method. 02201 if (!Owner->isFunctionOrMethod()) 02202 Owner->addDecl(Inst); 02203 02204 return Inst; 02205 } 02206 02207 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 02208 02209 // The nested name specifier may be dependent, for example 02210 // template <typename T> struct t { 02211 // struct s1 { T f1(); }; 02212 // struct s2 : s1 { using s1::f1; }; 02213 // }; 02214 // template struct t<int>; 02215 // Here, in using s1::f1, s1 refers to t<T>::s1; 02216 // we need to substitute for t<int>::s1. 02217 NestedNameSpecifierLoc QualifierLoc 02218 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 02219 TemplateArgs); 02220 if (!QualifierLoc) 02221 return nullptr; 02222 02223 // The name info is non-dependent, so no transformation 02224 // is required. 02225 DeclarationNameInfo NameInfo = D->getNameInfo(); 02226 02227 // We only need to do redeclaration lookups if we're in a class 02228 // scope (in fact, it's not really even possible in non-class 02229 // scopes). 02230 bool CheckRedeclaration = Owner->isRecord(); 02231 02232 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 02233 Sema::ForRedeclaration); 02234 02235 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 02236 D->getUsingLoc(), 02237 QualifierLoc, 02238 NameInfo, 02239 D->hasTypename()); 02240 02241 CXXScopeSpec SS; 02242 SS.Adopt(QualifierLoc); 02243 if (CheckRedeclaration) { 02244 Prev.setHideTags(false); 02245 SemaRef.LookupQualifiedName(Prev, Owner); 02246 02247 // Check for invalid redeclarations. 02248 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 02249 D->hasTypename(), SS, 02250 D->getLocation(), Prev)) 02251 NewUD->setInvalidDecl(); 02252 02253 } 02254 02255 if (!NewUD->isInvalidDecl() && 02256 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo, 02257 D->getLocation())) 02258 NewUD->setInvalidDecl(); 02259 02260 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 02261 NewUD->setAccess(D->getAccess()); 02262 Owner->addDecl(NewUD); 02263 02264 // Don't process the shadow decls for an invalid decl. 02265 if (NewUD->isInvalidDecl()) 02266 return NewUD; 02267 02268 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 02269 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 02270 return NewUD; 02271 } 02272 02273 bool isFunctionScope = Owner->isFunctionOrMethod(); 02274 02275 // Process the shadow decls. 02276 for (auto *Shadow : D->shadows()) { 02277 NamedDecl *InstTarget = 02278 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 02279 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs)); 02280 if (!InstTarget) 02281 return nullptr; 02282 02283 UsingShadowDecl *PrevDecl = nullptr; 02284 if (CheckRedeclaration) { 02285 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 02286 continue; 02287 } else if (UsingShadowDecl *OldPrev = 02288 getPreviousDeclForInstantiation(Shadow)) { 02289 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 02290 Shadow->getLocation(), OldPrev, TemplateArgs)); 02291 } 02292 02293 UsingShadowDecl *InstShadow = 02294 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget, 02295 PrevDecl); 02296 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 02297 02298 if (isFunctionScope) 02299 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 02300 } 02301 02302 return NewUD; 02303 } 02304 02305 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 02306 // Ignore these; we handle them in bulk when processing the UsingDecl. 02307 return nullptr; 02308 } 02309 02310 Decl * TemplateDeclInstantiator 02311 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 02312 NestedNameSpecifierLoc QualifierLoc 02313 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 02314 TemplateArgs); 02315 if (!QualifierLoc) 02316 return nullptr; 02317 02318 CXXScopeSpec SS; 02319 SS.Adopt(QualifierLoc); 02320 02321 // Since NameInfo refers to a typename, it cannot be a C++ special name. 02322 // Hence, no transformation is required for it. 02323 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 02324 NamedDecl *UD = 02325 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(), 02326 D->getUsingLoc(), SS, NameInfo, nullptr, 02327 /*instantiation*/ true, 02328 /*typename*/ true, D->getTypenameLoc()); 02329 if (UD) 02330 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 02331 02332 return UD; 02333 } 02334 02335 Decl * TemplateDeclInstantiator 02336 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 02337 NestedNameSpecifierLoc QualifierLoc 02338 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 02339 if (!QualifierLoc) 02340 return nullptr; 02341 02342 CXXScopeSpec SS; 02343 SS.Adopt(QualifierLoc); 02344 02345 DeclarationNameInfo NameInfo 02346 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 02347 02348 NamedDecl *UD = 02349 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(), 02350 D->getUsingLoc(), SS, NameInfo, nullptr, 02351 /*instantiation*/ true, 02352 /*typename*/ false, SourceLocation()); 02353 if (UD) 02354 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 02355 02356 return UD; 02357 } 02358 02359 02360 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 02361 ClassScopeFunctionSpecializationDecl *Decl) { 02362 CXXMethodDecl *OldFD = Decl->getSpecialization(); 02363 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 02364 nullptr, true)); 02365 02366 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName, 02367 Sema::ForRedeclaration); 02368 02369 TemplateArgumentListInfo TemplateArgs; 02370 TemplateArgumentListInfo *TemplateArgsPtr = nullptr; 02371 if (Decl->hasExplicitTemplateArgs()) { 02372 TemplateArgs = Decl->templateArgs(); 02373 TemplateArgsPtr = &TemplateArgs; 02374 } 02375 02376 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext); 02377 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr, 02378 Previous)) { 02379 NewFD->setInvalidDecl(); 02380 return NewFD; 02381 } 02382 02383 // Associate the specialization with the pattern. 02384 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl()); 02385 assert(Specialization && "Class scope Specialization is null"); 02386 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD); 02387 02388 return NewFD; 02389 } 02390 02391 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 02392 OMPThreadPrivateDecl *D) { 02393 SmallVector<Expr *, 5> Vars; 02394 for (auto *I : D->varlists()) { 02395 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 02396 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 02397 Vars.push_back(Var); 02398 } 02399 02400 OMPThreadPrivateDecl *TD = 02401 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 02402 02403 TD->setAccess(AS_public); 02404 Owner->addDecl(TD); 02405 02406 return TD; 02407 } 02408 02409 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 02410 return VisitFunctionDecl(D, nullptr); 02411 } 02412 02413 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 02414 return VisitCXXMethodDecl(D, nullptr); 02415 } 02416 02417 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 02418 llvm_unreachable("There are only CXXRecordDecls in C++"); 02419 } 02420 02421 Decl * 02422 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 02423 ClassTemplateSpecializationDecl *D) { 02424 // As a MS extension, we permit class-scope explicit specialization 02425 // of member class templates. 02426 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 02427 assert(ClassTemplate->getDeclContext()->isRecord() && 02428 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 02429 "can only instantiate an explicit specialization " 02430 "for a member class template"); 02431 02432 // Lookup the already-instantiated declaration in the instantiation 02433 // of the class template. FIXME: Diagnose or assert if this fails? 02434 DeclContext::lookup_result Found 02435 = Owner->lookup(ClassTemplate->getDeclName()); 02436 if (Found.empty()) 02437 return nullptr; 02438 ClassTemplateDecl *InstClassTemplate 02439 = dyn_cast<ClassTemplateDecl>(Found.front()); 02440 if (!InstClassTemplate) 02441 return nullptr; 02442 02443 // Substitute into the template arguments of the class template explicit 02444 // specialization. 02445 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 02446 castAs<TemplateSpecializationTypeLoc>(); 02447 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 02448 Loc.getRAngleLoc()); 02449 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 02450 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 02451 ArgLocs.push_back(Loc.getArgLoc(I)); 02452 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 02453 InstTemplateArgs, TemplateArgs)) 02454 return nullptr; 02455 02456 // Check that the template argument list is well-formed for this 02457 // class template. 02458 SmallVector<TemplateArgument, 4> Converted; 02459 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 02460 D->getLocation(), 02461 InstTemplateArgs, 02462 false, 02463 Converted)) 02464 return nullptr; 02465 02466 // Figure out where to insert this class template explicit specialization 02467 // in the member template's set of class template explicit specializations. 02468 void *InsertPos = nullptr; 02469 ClassTemplateSpecializationDecl *PrevDecl = 02470 InstClassTemplate->findSpecialization(Converted, InsertPos); 02471 02472 // Check whether we've already seen a conflicting instantiation of this 02473 // declaration (for instance, if there was a prior implicit instantiation). 02474 bool Ignored; 02475 if (PrevDecl && 02476 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 02477 D->getSpecializationKind(), 02478 PrevDecl, 02479 PrevDecl->getSpecializationKind(), 02480 PrevDecl->getPointOfInstantiation(), 02481 Ignored)) 02482 return nullptr; 02483 02484 // If PrevDecl was a definition and D is also a definition, diagnose. 02485 // This happens in cases like: 02486 // 02487 // template<typename T, typename U> 02488 // struct Outer { 02489 // template<typename X> struct Inner; 02490 // template<> struct Inner<T> {}; 02491 // template<> struct Inner<U> {}; 02492 // }; 02493 // 02494 // Outer<int, int> outer; // error: the explicit specializations of Inner 02495 // // have the same signature. 02496 if (PrevDecl && PrevDecl->getDefinition() && 02497 D->isThisDeclarationADefinition()) { 02498 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 02499 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 02500 diag::note_previous_definition); 02501 return nullptr; 02502 } 02503 02504 // Create the class template partial specialization declaration. 02505 ClassTemplateSpecializationDecl *InstD 02506 = ClassTemplateSpecializationDecl::Create(SemaRef.Context, 02507 D->getTagKind(), 02508 Owner, 02509 D->getLocStart(), 02510 D->getLocation(), 02511 InstClassTemplate, 02512 Converted.data(), 02513 Converted.size(), 02514 PrevDecl); 02515 02516 // Add this partial specialization to the set of class template partial 02517 // specializations. 02518 if (!PrevDecl) 02519 InstClassTemplate->AddSpecialization(InstD, InsertPos); 02520 02521 // Substitute the nested name specifier, if any. 02522 if (SubstQualifier(D, InstD)) 02523 return nullptr; 02524 02525 // Build the canonical type that describes the converted template 02526 // arguments of the class template explicit specialization. 02527 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 02528 TemplateName(InstClassTemplate), Converted.data(), Converted.size(), 02529 SemaRef.Context.getRecordType(InstD)); 02530 02531 // Build the fully-sugared type for this class template 02532 // specialization as the user wrote in the specialization 02533 // itself. This means that we'll pretty-print the type retrieved 02534 // from the specialization's declaration the way that the user 02535 // actually wrote the specialization, rather than formatting the 02536 // name based on the "canonical" representation used to store the 02537 // template arguments in the specialization. 02538 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 02539 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 02540 CanonType); 02541 02542 InstD->setAccess(D->getAccess()); 02543 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 02544 InstD->setSpecializationKind(D->getSpecializationKind()); 02545 InstD->setTypeAsWritten(WrittenTy); 02546 InstD->setExternLoc(D->getExternLoc()); 02547 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 02548 02549 Owner->addDecl(InstD); 02550 02551 // Instantiate the members of the class-scope explicit specialization eagerly. 02552 // We don't have support for lazy instantiation of an explicit specialization 02553 // yet, and MSVC eagerly instantiates in this case. 02554 if (D->isThisDeclarationADefinition() && 02555 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 02556 TSK_ImplicitInstantiation, 02557 /*Complain=*/true)) 02558 return nullptr; 02559 02560 return InstD; 02561 } 02562 02563 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 02564 VarTemplateSpecializationDecl *D) { 02565 02566 TemplateArgumentListInfo VarTemplateArgsInfo; 02567 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 02568 assert(VarTemplate && 02569 "A template specialization without specialized template?"); 02570 02571 // Substitute the current template arguments. 02572 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 02573 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 02574 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 02575 02576 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 02577 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 02578 return nullptr; 02579 02580 // Check that the template argument list is well-formed for this template. 02581 SmallVector<TemplateArgument, 4> Converted; 02582 if (SemaRef.CheckTemplateArgumentList( 02583 VarTemplate, VarTemplate->getLocStart(), 02584 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false, 02585 Converted)) 02586 return nullptr; 02587 02588 // Find the variable template specialization declaration that 02589 // corresponds to these arguments. 02590 void *InsertPos = nullptr; 02591 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization( 02592 Converted, InsertPos)) 02593 // If we already have a variable template specialization, return it. 02594 return VarSpec; 02595 02596 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos, 02597 VarTemplateArgsInfo, Converted); 02598 } 02599 02600 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 02601 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 02602 const TemplateArgumentListInfo &TemplateArgsInfo, 02603 ArrayRef<TemplateArgument> Converted) { 02604 02605 // If this is the variable for an anonymous struct or union, 02606 // instantiate the anonymous struct/union type first. 02607 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 02608 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 02609 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 02610 return nullptr; 02611 02612 // Do substitution on the type of the declaration 02613 TypeSourceInfo *DI = 02614 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 02615 D->getTypeSpecStartLoc(), D->getDeclName()); 02616 if (!DI) 02617 return nullptr; 02618 02619 if (DI->getType()->isFunctionType()) { 02620 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 02621 << D->isStaticDataMember() << DI->getType(); 02622 return nullptr; 02623 } 02624 02625 // Build the instantiated declaration 02626 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 02627 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 02628 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(), 02629 Converted.size()); 02630 Var->setTemplateArgsInfo(TemplateArgsInfo); 02631 if (InsertPos) 02632 VarTemplate->AddSpecialization(Var, InsertPos); 02633 02634 // Substitute the nested name specifier, if any. 02635 if (SubstQualifier(D, Var)) 02636 return nullptr; 02637 02638 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, 02639 Owner, StartingScope); 02640 02641 return Var; 02642 } 02643 02644 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 02645 llvm_unreachable("@defs is not supported in Objective-C++"); 02646 } 02647 02648 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 02649 // FIXME: We need to be able to instantiate FriendTemplateDecls. 02650 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 02651 DiagnosticsEngine::Error, 02652 "cannot instantiate %0 yet"); 02653 SemaRef.Diag(D->getLocation(), DiagID) 02654 << D->getDeclKindName(); 02655 02656 return nullptr; 02657 } 02658 02659 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 02660 llvm_unreachable("Unexpected decl"); 02661 } 02662 02663 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 02664 const MultiLevelTemplateArgumentList &TemplateArgs) { 02665 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 02666 if (D->isInvalidDecl()) 02667 return nullptr; 02668 02669 return Instantiator.Visit(D); 02670 } 02671 02672 /// \brief Instantiates a nested template parameter list in the current 02673 /// instantiation context. 02674 /// 02675 /// \param L The parameter list to instantiate 02676 /// 02677 /// \returns NULL if there was an error 02678 TemplateParameterList * 02679 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 02680 // Get errors for all the parameters before bailing out. 02681 bool Invalid = false; 02682 02683 unsigned N = L->size(); 02684 typedef SmallVector<NamedDecl *, 8> ParamVector; 02685 ParamVector Params; 02686 Params.reserve(N); 02687 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 02688 PI != PE; ++PI) { 02689 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 02690 Params.push_back(D); 02691 Invalid = Invalid || !D || D->isInvalidDecl(); 02692 } 02693 02694 // Clean up if we had an error. 02695 if (Invalid) 02696 return nullptr; 02697 02698 TemplateParameterList *InstL 02699 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 02700 L->getLAngleLoc(), &Params.front(), N, 02701 L->getRAngleLoc()); 02702 return InstL; 02703 } 02704 02705 /// \brief Instantiate the declaration of a class template partial 02706 /// specialization. 02707 /// 02708 /// \param ClassTemplate the (instantiated) class template that is partially 02709 // specialized by the instantiation of \p PartialSpec. 02710 /// 02711 /// \param PartialSpec the (uninstantiated) class template partial 02712 /// specialization that we are instantiating. 02713 /// 02714 /// \returns The instantiated partial specialization, if successful; otherwise, 02715 /// NULL to indicate an error. 02716 ClassTemplatePartialSpecializationDecl * 02717 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 02718 ClassTemplateDecl *ClassTemplate, 02719 ClassTemplatePartialSpecializationDecl *PartialSpec) { 02720 // Create a local instantiation scope for this class template partial 02721 // specialization, which will contain the instantiations of the template 02722 // parameters. 02723 LocalInstantiationScope Scope(SemaRef); 02724 02725 // Substitute into the template parameters of the class template partial 02726 // specialization. 02727 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 02728 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 02729 if (!InstParams) 02730 return nullptr; 02731 02732 // Substitute into the template arguments of the class template partial 02733 // specialization. 02734 const ASTTemplateArgumentListInfo *TemplArgInfo 02735 = PartialSpec->getTemplateArgsAsWritten(); 02736 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 02737 TemplArgInfo->RAngleLoc); 02738 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 02739 TemplArgInfo->NumTemplateArgs, 02740 InstTemplateArgs, TemplateArgs)) 02741 return nullptr; 02742 02743 // Check that the template argument list is well-formed for this 02744 // class template. 02745 SmallVector<TemplateArgument, 4> Converted; 02746 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 02747 PartialSpec->getLocation(), 02748 InstTemplateArgs, 02749 false, 02750 Converted)) 02751 return nullptr; 02752 02753 // Figure out where to insert this class template partial specialization 02754 // in the member template's set of class template partial specializations. 02755 void *InsertPos = nullptr; 02756 ClassTemplateSpecializationDecl *PrevDecl 02757 = ClassTemplate->findPartialSpecialization(Converted, InsertPos); 02758 02759 // Build the canonical type that describes the converted template 02760 // arguments of the class template partial specialization. 02761 QualType CanonType 02762 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 02763 Converted.data(), 02764 Converted.size()); 02765 02766 // Build the fully-sugared type for this class template 02767 // specialization as the user wrote in the specialization 02768 // itself. This means that we'll pretty-print the type retrieved 02769 // from the specialization's declaration the way that the user 02770 // actually wrote the specialization, rather than formatting the 02771 // name based on the "canonical" representation used to store the 02772 // template arguments in the specialization. 02773 TypeSourceInfo *WrittenTy 02774 = SemaRef.Context.getTemplateSpecializationTypeInfo( 02775 TemplateName(ClassTemplate), 02776 PartialSpec->getLocation(), 02777 InstTemplateArgs, 02778 CanonType); 02779 02780 if (PrevDecl) { 02781 // We've already seen a partial specialization with the same template 02782 // parameters and template arguments. This can happen, for example, when 02783 // substituting the outer template arguments ends up causing two 02784 // class template partial specializations of a member class template 02785 // to have identical forms, e.g., 02786 // 02787 // template<typename T, typename U> 02788 // struct Outer { 02789 // template<typename X, typename Y> struct Inner; 02790 // template<typename Y> struct Inner<T, Y>; 02791 // template<typename Y> struct Inner<U, Y>; 02792 // }; 02793 // 02794 // Outer<int, int> outer; // error: the partial specializations of Inner 02795 // // have the same signature. 02796 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 02797 << WrittenTy->getType(); 02798 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 02799 << SemaRef.Context.getTypeDeclType(PrevDecl); 02800 return nullptr; 02801 } 02802 02803 02804 // Create the class template partial specialization declaration. 02805 ClassTemplatePartialSpecializationDecl *InstPartialSpec 02806 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 02807 PartialSpec->getTagKind(), 02808 Owner, 02809 PartialSpec->getLocStart(), 02810 PartialSpec->getLocation(), 02811 InstParams, 02812 ClassTemplate, 02813 Converted.data(), 02814 Converted.size(), 02815 InstTemplateArgs, 02816 CanonType, 02817 nullptr); 02818 // Substitute the nested name specifier, if any. 02819 if (SubstQualifier(PartialSpec, InstPartialSpec)) 02820 return nullptr; 02821 02822 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 02823 InstPartialSpec->setTypeAsWritten(WrittenTy); 02824 02825 // Add this partial specialization to the set of class template partial 02826 // specializations. 02827 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 02828 /*InsertPos=*/nullptr); 02829 return InstPartialSpec; 02830 } 02831 02832 /// \brief Instantiate the declaration of a variable template partial 02833 /// specialization. 02834 /// 02835 /// \param VarTemplate the (instantiated) variable template that is partially 02836 /// specialized by the instantiation of \p PartialSpec. 02837 /// 02838 /// \param PartialSpec the (uninstantiated) variable template partial 02839 /// specialization that we are instantiating. 02840 /// 02841 /// \returns The instantiated partial specialization, if successful; otherwise, 02842 /// NULL to indicate an error. 02843 VarTemplatePartialSpecializationDecl * 02844 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 02845 VarTemplateDecl *VarTemplate, 02846 VarTemplatePartialSpecializationDecl *PartialSpec) { 02847 // Create a local instantiation scope for this variable template partial 02848 // specialization, which will contain the instantiations of the template 02849 // parameters. 02850 LocalInstantiationScope Scope(SemaRef); 02851 02852 // Substitute into the template parameters of the variable template partial 02853 // specialization. 02854 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 02855 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 02856 if (!InstParams) 02857 return nullptr; 02858 02859 // Substitute into the template arguments of the variable template partial 02860 // specialization. 02861 const ASTTemplateArgumentListInfo *TemplArgInfo 02862 = PartialSpec->getTemplateArgsAsWritten(); 02863 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 02864 TemplArgInfo->RAngleLoc); 02865 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 02866 TemplArgInfo->NumTemplateArgs, 02867 InstTemplateArgs, TemplateArgs)) 02868 return nullptr; 02869 02870 // Check that the template argument list is well-formed for this 02871 // class template. 02872 SmallVector<TemplateArgument, 4> Converted; 02873 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 02874 InstTemplateArgs, false, Converted)) 02875 return nullptr; 02876 02877 // Figure out where to insert this variable template partial specialization 02878 // in the member template's set of variable template partial specializations. 02879 void *InsertPos = nullptr; 02880 VarTemplateSpecializationDecl *PrevDecl = 02881 VarTemplate->findPartialSpecialization(Converted, InsertPos); 02882 02883 // Build the canonical type that describes the converted template 02884 // arguments of the variable template partial specialization. 02885 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 02886 TemplateName(VarTemplate), Converted.data(), Converted.size()); 02887 02888 // Build the fully-sugared type for this variable template 02889 // specialization as the user wrote in the specialization 02890 // itself. This means that we'll pretty-print the type retrieved 02891 // from the specialization's declaration the way that the user 02892 // actually wrote the specialization, rather than formatting the 02893 // name based on the "canonical" representation used to store the 02894 // template arguments in the specialization. 02895 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 02896 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 02897 CanonType); 02898 02899 if (PrevDecl) { 02900 // We've already seen a partial specialization with the same template 02901 // parameters and template arguments. This can happen, for example, when 02902 // substituting the outer template arguments ends up causing two 02903 // variable template partial specializations of a member variable template 02904 // to have identical forms, e.g., 02905 // 02906 // template<typename T, typename U> 02907 // struct Outer { 02908 // template<typename X, typename Y> pair<X,Y> p; 02909 // template<typename Y> pair<T, Y> p; 02910 // template<typename Y> pair<U, Y> p; 02911 // }; 02912 // 02913 // Outer<int, int> outer; // error: the partial specializations of Inner 02914 // // have the same signature. 02915 SemaRef.Diag(PartialSpec->getLocation(), 02916 diag::err_var_partial_spec_redeclared) 02917 << WrittenTy->getType(); 02918 SemaRef.Diag(PrevDecl->getLocation(), 02919 diag::note_var_prev_partial_spec_here); 02920 return nullptr; 02921 } 02922 02923 // Do substitution on the type of the declaration 02924 TypeSourceInfo *DI = SemaRef.SubstType( 02925 PartialSpec->getTypeSourceInfo(), TemplateArgs, 02926 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 02927 if (!DI) 02928 return nullptr; 02929 02930 if (DI->getType()->isFunctionType()) { 02931 SemaRef.Diag(PartialSpec->getLocation(), 02932 diag::err_variable_instantiates_to_function) 02933 << PartialSpec->isStaticDataMember() << DI->getType(); 02934 return nullptr; 02935 } 02936 02937 // Create the variable template partial specialization declaration. 02938 VarTemplatePartialSpecializationDecl *InstPartialSpec = 02939 VarTemplatePartialSpecializationDecl::Create( 02940 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 02941 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 02942 DI, PartialSpec->getStorageClass(), Converted.data(), 02943 Converted.size(), InstTemplateArgs); 02944 02945 // Substitute the nested name specifier, if any. 02946 if (SubstQualifier(PartialSpec, InstPartialSpec)) 02947 return nullptr; 02948 02949 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 02950 InstPartialSpec->setTypeAsWritten(WrittenTy); 02951 02952 // Add this partial specialization to the set of variable template partial 02953 // specializations. The instantiation of the initializer is not necessary. 02954 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 02955 02956 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 02957 LateAttrs, Owner, StartingScope); 02958 02959 return InstPartialSpec; 02960 } 02961 02962 TypeSourceInfo* 02963 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 02964 SmallVectorImpl<ParmVarDecl *> &Params) { 02965 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 02966 assert(OldTInfo && "substituting function without type source info"); 02967 assert(Params.empty() && "parameter vector is non-empty at start"); 02968 02969 CXXRecordDecl *ThisContext = nullptr; 02970 unsigned ThisTypeQuals = 0; 02971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 02972 ThisContext = cast<CXXRecordDecl>(Owner); 02973 ThisTypeQuals = Method->getTypeQualifiers(); 02974 } 02975 02976 TypeSourceInfo *NewTInfo 02977 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 02978 D->getTypeSpecStartLoc(), 02979 D->getDeclName(), 02980 ThisContext, ThisTypeQuals); 02981 if (!NewTInfo) 02982 return nullptr; 02983 02984 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 02985 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 02986 if (NewTInfo != OldTInfo) { 02987 // Get parameters from the new type info. 02988 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 02989 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 02990 unsigned NewIdx = 0; 02991 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 02992 OldIdx != NumOldParams; ++OldIdx) { 02993 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 02994 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 02995 02996 Optional<unsigned> NumArgumentsInExpansion; 02997 if (OldParam->isParameterPack()) 02998 NumArgumentsInExpansion = 02999 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 03000 TemplateArgs); 03001 if (!NumArgumentsInExpansion) { 03002 // Simple case: normal parameter, or a parameter pack that's 03003 // instantiated to a (still-dependent) parameter pack. 03004 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 03005 Params.push_back(NewParam); 03006 Scope->InstantiatedLocal(OldParam, NewParam); 03007 } else { 03008 // Parameter pack expansion: make the instantiation an argument pack. 03009 Scope->MakeInstantiatedLocalArgPack(OldParam); 03010 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 03011 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 03012 Params.push_back(NewParam); 03013 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 03014 } 03015 } 03016 } 03017 } else { 03018 // The function type itself was not dependent and therefore no 03019 // substitution occurred. However, we still need to instantiate 03020 // the function parameters themselves. 03021 const FunctionProtoType *OldProto = 03022 cast<FunctionProtoType>(OldProtoLoc.getType()); 03023 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 03024 ++i) { 03025 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 03026 if (!OldParam) { 03027 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 03028 D, D->getLocation(), OldProto->getParamType(i))); 03029 continue; 03030 } 03031 03032 ParmVarDecl *Parm = 03033 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 03034 if (!Parm) 03035 return nullptr; 03036 Params.push_back(Parm); 03037 } 03038 } 03039 } else { 03040 // If the type of this function, after ignoring parentheses, is not 03041 // *directly* a function type, then we're instantiating a function that 03042 // was declared via a typedef or with attributes, e.g., 03043 // 03044 // typedef int functype(int, int); 03045 // functype func; 03046 // int __cdecl meth(int, int); 03047 // 03048 // In this case, we'll just go instantiate the ParmVarDecls that we 03049 // synthesized in the method declaration. 03050 SmallVector<QualType, 4> ParamTypes; 03051 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 03052 D->getNumParams(), TemplateArgs, ParamTypes, 03053 &Params)) 03054 return nullptr; 03055 } 03056 03057 return NewTInfo; 03058 } 03059 03060 /// Introduce the instantiated function parameters into the local 03061 /// instantiation scope, and set the parameter names to those used 03062 /// in the template. 03063 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 03064 const FunctionDecl *PatternDecl, 03065 LocalInstantiationScope &Scope, 03066 const MultiLevelTemplateArgumentList &TemplateArgs) { 03067 unsigned FParamIdx = 0; 03068 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 03069 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 03070 if (!PatternParam->isParameterPack()) { 03071 // Simple case: not a parameter pack. 03072 assert(FParamIdx < Function->getNumParams()); 03073 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 03074 FunctionParam->setDeclName(PatternParam->getDeclName()); 03075 // If the parameter's type is not dependent, update it to match the type 03076 // in the pattern. They can differ in top-level cv-qualifiers, and we want 03077 // the pattern's type here. If the type is dependent, they can't differ, 03078 // per core issue 1668. Substitute into the type from the pattern, in case 03079 // it's instantiation-dependent. 03080 // FIXME: Updating the type to work around this is at best fragile. 03081 if (!PatternDecl->getType()->isDependentType()) { 03082 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs, 03083 FunctionParam->getLocation(), 03084 FunctionParam->getDeclName()); 03085 if (T.isNull()) 03086 return true; 03087 FunctionParam->setType(T); 03088 } 03089 03090 Scope.InstantiatedLocal(PatternParam, FunctionParam); 03091 ++FParamIdx; 03092 continue; 03093 } 03094 03095 // Expand the parameter pack. 03096 Scope.MakeInstantiatedLocalArgPack(PatternParam); 03097 Optional<unsigned> NumArgumentsInExpansion 03098 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 03099 assert(NumArgumentsInExpansion && 03100 "should only be called when all template arguments are known"); 03101 QualType PatternType = 03102 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 03103 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 03104 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 03105 FunctionParam->setDeclName(PatternParam->getDeclName()); 03106 if (!PatternDecl->getType()->isDependentType()) { 03107 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg); 03108 QualType T = S.SubstType(PatternType, TemplateArgs, 03109 FunctionParam->getLocation(), 03110 FunctionParam->getDeclName()); 03111 if (T.isNull()) 03112 return true; 03113 FunctionParam->setType(T); 03114 } 03115 03116 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 03117 ++FParamIdx; 03118 } 03119 } 03120 03121 return false; 03122 } 03123 03124 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 03125 FunctionDecl *Decl) { 03126 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 03127 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 03128 return; 03129 03130 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 03131 InstantiatingTemplate::ExceptionSpecification()); 03132 if (Inst.isInvalid()) { 03133 // We hit the instantiation depth limit. Clear the exception specification 03134 // so that our callers don't have to cope with EST_Uninstantiated. 03135 UpdateExceptionSpec(Decl, EST_None); 03136 return; 03137 } 03138 03139 // Enter the scope of this instantiation. We don't use 03140 // PushDeclContext because we don't have a scope. 03141 Sema::ContextRAII savedContext(*this, Decl); 03142 LocalInstantiationScope Scope(*this); 03143 03144 MultiLevelTemplateArgumentList TemplateArgs = 03145 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 03146 03147 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 03148 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 03149 TemplateArgs)) { 03150 UpdateExceptionSpec(Decl, EST_None); 03151 return; 03152 } 03153 03154 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 03155 TemplateArgs); 03156 } 03157 03158 /// \brief Initializes the common fields of an instantiation function 03159 /// declaration (New) from the corresponding fields of its template (Tmpl). 03160 /// 03161 /// \returns true if there was an error 03162 bool 03163 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 03164 FunctionDecl *Tmpl) { 03165 if (Tmpl->isDeleted()) 03166 New->setDeletedAsWritten(); 03167 03168 // Forward the mangling number from the template to the instantiated decl. 03169 SemaRef.Context.setManglingNumber(New, 03170 SemaRef.Context.getManglingNumber(Tmpl)); 03171 03172 // If we are performing substituting explicitly-specified template arguments 03173 // or deduced template arguments into a function template and we reach this 03174 // point, we are now past the point where SFINAE applies and have committed 03175 // to keeping the new function template specialization. We therefore 03176 // convert the active template instantiation for the function template 03177 // into a template instantiation for this specific function template 03178 // specialization, which is not a SFINAE context, so that we diagnose any 03179 // further errors in the declaration itself. 03180 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 03181 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 03182 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 03183 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 03184 if (FunctionTemplateDecl *FunTmpl 03185 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 03186 assert(FunTmpl->getTemplatedDecl() == Tmpl && 03187 "Deduction from the wrong function template?"); 03188 (void) FunTmpl; 03189 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 03190 ActiveInst.Entity = New; 03191 } 03192 } 03193 03194 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 03195 assert(Proto && "Function template without prototype?"); 03196 03197 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 03198 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 03199 03200 // DR1330: In C++11, defer instantiation of a non-trivial 03201 // exception specification. 03202 if (SemaRef.getLangOpts().CPlusPlus11 && 03203 EPI.ExceptionSpec.Type != EST_None && 03204 EPI.ExceptionSpec.Type != EST_DynamicNone && 03205 EPI.ExceptionSpec.Type != EST_BasicNoexcept) { 03206 FunctionDecl *ExceptionSpecTemplate = Tmpl; 03207 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 03208 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 03209 ExceptionSpecificationType NewEST = EST_Uninstantiated; 03210 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 03211 NewEST = EST_Unevaluated; 03212 03213 // Mark the function has having an uninstantiated exception specification. 03214 const FunctionProtoType *NewProto 03215 = New->getType()->getAs<FunctionProtoType>(); 03216 assert(NewProto && "Template instantiation without function prototype?"); 03217 EPI = NewProto->getExtProtoInfo(); 03218 EPI.ExceptionSpec.Type = NewEST; 03219 EPI.ExceptionSpec.SourceDecl = New; 03220 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 03221 New->setType(SemaRef.Context.getFunctionType( 03222 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 03223 } else { 03224 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 03225 } 03226 } 03227 03228 // Get the definition. Leaves the variable unchanged if undefined. 03229 const FunctionDecl *Definition = Tmpl; 03230 Tmpl->isDefined(Definition); 03231 03232 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 03233 LateAttrs, StartingScope); 03234 03235 return false; 03236 } 03237 03238 /// \brief Initializes common fields of an instantiated method 03239 /// declaration (New) from the corresponding fields of its template 03240 /// (Tmpl). 03241 /// 03242 /// \returns true if there was an error 03243 bool 03244 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 03245 CXXMethodDecl *Tmpl) { 03246 if (InitFunctionInstantiation(New, Tmpl)) 03247 return true; 03248 03249 New->setAccess(Tmpl->getAccess()); 03250 if (Tmpl->isVirtualAsWritten()) 03251 New->setVirtualAsWritten(true); 03252 03253 // FIXME: New needs a pointer to Tmpl 03254 return false; 03255 } 03256 03257 /// \brief Instantiate the definition of the given function from its 03258 /// template. 03259 /// 03260 /// \param PointOfInstantiation the point at which the instantiation was 03261 /// required. Note that this is not precisely a "point of instantiation" 03262 /// for the function, but it's close. 03263 /// 03264 /// \param Function the already-instantiated declaration of a 03265 /// function template specialization or member function of a class template 03266 /// specialization. 03267 /// 03268 /// \param Recursive if true, recursively instantiates any functions that 03269 /// are required by this instantiation. 03270 /// 03271 /// \param DefinitionRequired if true, then we are performing an explicit 03272 /// instantiation where the body of the function is required. Complain if 03273 /// there is no such body. 03274 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 03275 FunctionDecl *Function, 03276 bool Recursive, 03277 bool DefinitionRequired) { 03278 if (Function->isInvalidDecl() || Function->isDefined()) 03279 return; 03280 03281 // Never instantiate an explicit specialization except if it is a class scope 03282 // explicit specialization. 03283 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 03284 !Function->getClassScopeSpecializationPattern()) 03285 return; 03286 03287 // Find the function body that we'll be substituting. 03288 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 03289 assert(PatternDecl && "instantiating a non-template"); 03290 03291 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 03292 assert(PatternDecl && "template definition is not a template"); 03293 if (!Pattern) { 03294 // Try to find a defaulted definition 03295 PatternDecl->isDefined(PatternDecl); 03296 } 03297 assert(PatternDecl && "template definition is not a template"); 03298 03299 // Postpone late parsed template instantiations. 03300 if (PatternDecl->isLateTemplateParsed() && 03301 !LateTemplateParser) { 03302 PendingInstantiations.push_back( 03303 std::make_pair(Function, PointOfInstantiation)); 03304 return; 03305 } 03306 03307 // If we're performing recursive template instantiation, create our own 03308 // queue of pending implicit instantiations that we will instantiate later, 03309 // while we're still within our own instantiation context. 03310 // This has to happen before LateTemplateParser below is called, so that 03311 // it marks vtables used in late parsed templates as used. 03312 SavePendingLocalImplicitInstantiationsRAII 03313 SavedPendingLocalImplicitInstantiations(*this); 03314 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII> 03315 SavePendingInstantiationsAndVTableUses; 03316 if (Recursive) { 03317 SavePendingInstantiationsAndVTableUses.reset( 03318 new SavePendingInstantiationsAndVTableUsesRAII(*this)); 03319 } 03320 03321 // Call the LateTemplateParser callback if there is a need to late parse 03322 // a templated function definition. 03323 if (!Pattern && PatternDecl->isLateTemplateParsed() && 03324 LateTemplateParser) { 03325 // FIXME: Optimize to allow individual templates to be deserialized. 03326 if (PatternDecl->isFromASTFile()) 03327 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 03328 03329 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl); 03330 assert(LPT && "missing LateParsedTemplate"); 03331 LateTemplateParser(OpaqueParser, *LPT); 03332 Pattern = PatternDecl->getBody(PatternDecl); 03333 } 03334 03335 if (!Pattern && !PatternDecl->isDefaulted()) { 03336 if (DefinitionRequired) { 03337 if (Function->getPrimaryTemplate()) 03338 Diag(PointOfInstantiation, 03339 diag::err_explicit_instantiation_undefined_func_template) 03340 << Function->getPrimaryTemplate(); 03341 else 03342 Diag(PointOfInstantiation, 03343 diag::err_explicit_instantiation_undefined_member) 03344 << 1 << Function->getDeclName() << Function->getDeclContext(); 03345 03346 if (PatternDecl) 03347 Diag(PatternDecl->getLocation(), 03348 diag::note_explicit_instantiation_here); 03349 Function->setInvalidDecl(); 03350 } else if (Function->getTemplateSpecializationKind() 03351 == TSK_ExplicitInstantiationDefinition) { 03352 assert(!Recursive); 03353 PendingInstantiations.push_back( 03354 std::make_pair(Function, PointOfInstantiation)); 03355 } 03356 03357 return; 03358 } 03359 03360 // C++1y [temp.explicit]p10: 03361 // Except for inline functions, declarations with types deduced from their 03362 // initializer or return value, and class template specializations, other 03363 // explicit instantiation declarations have the effect of suppressing the 03364 // implicit instantiation of the entity to which they refer. 03365 if (Function->getTemplateSpecializationKind() == 03366 TSK_ExplicitInstantiationDeclaration && 03367 !PatternDecl->isInlined() && 03368 !PatternDecl->getReturnType()->getContainedAutoType()) 03369 return; 03370 03371 if (PatternDecl->isInlined()) { 03372 // Function, and all later redeclarations of it (from imported modules, 03373 // for instance), are now implicitly inline. 03374 for (auto *D = Function->getMostRecentDecl(); /**/; 03375 D = D->getPreviousDecl()) { 03376 D->setImplicitlyInline(); 03377 if (D == Function) 03378 break; 03379 } 03380 } 03381 03382 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 03383 if (Inst.isInvalid()) 03384 return; 03385 03386 // Copy the inner loc start from the pattern. 03387 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 03388 03389 EnterExpressionEvaluationContext EvalContext(*this, 03390 Sema::PotentiallyEvaluated); 03391 03392 // Introduce a new scope where local variable instantiations will be 03393 // recorded, unless we're actually a member function within a local 03394 // class, in which case we need to merge our results with the parent 03395 // scope (of the enclosing function). 03396 bool MergeWithParentScope = false; 03397 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 03398 MergeWithParentScope = Rec->isLocalClass(); 03399 03400 LocalInstantiationScope Scope(*this, MergeWithParentScope); 03401 03402 if (PatternDecl->isDefaulted()) 03403 SetDeclDefaulted(Function, PatternDecl->getLocation()); 03404 else { 03405 MultiLevelTemplateArgumentList TemplateArgs = 03406 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 03407 03408 // Substitute into the qualifier; we can get a substitution failure here 03409 // through evil use of alias templates. 03410 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 03411 // of the) lexical context of the pattern? 03412 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 03413 03414 ActOnStartOfFunctionDef(nullptr, Function); 03415 03416 // Enter the scope of this instantiation. We don't use 03417 // PushDeclContext because we don't have a scope. 03418 Sema::ContextRAII savedContext(*this, Function); 03419 03420 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 03421 TemplateArgs)) 03422 return; 03423 03424 // If this is a constructor, instantiate the member initializers. 03425 if (const CXXConstructorDecl *Ctor = 03426 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 03427 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 03428 TemplateArgs); 03429 } 03430 03431 // Instantiate the function body. 03432 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 03433 03434 if (Body.isInvalid()) 03435 Function->setInvalidDecl(); 03436 03437 ActOnFinishFunctionBody(Function, Body.get(), 03438 /*IsInstantiation=*/true); 03439 03440 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 03441 03442 if (auto *Listener = getASTMutationListener()) 03443 Listener->FunctionDefinitionInstantiated(Function); 03444 03445 savedContext.pop(); 03446 } 03447 03448 DeclGroupRef DG(Function); 03449 Consumer.HandleTopLevelDecl(DG); 03450 03451 // This class may have local implicit instantiations that need to be 03452 // instantiation within this scope. 03453 PerformPendingInstantiations(/*LocalOnly=*/true); 03454 Scope.Exit(); 03455 03456 if (Recursive) { 03457 // Define any pending vtables. 03458 DefineUsedVTables(); 03459 03460 // Instantiate any pending implicit instantiations found during the 03461 // instantiation of this template. 03462 PerformPendingInstantiations(); 03463 03464 // Restore PendingInstantiations and VTableUses. 03465 SavePendingInstantiationsAndVTableUses.reset(); 03466 } 03467 } 03468 03469 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 03470 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 03471 const TemplateArgumentList &TemplateArgList, 03472 const TemplateArgumentListInfo &TemplateArgsInfo, 03473 SmallVectorImpl<TemplateArgument> &Converted, 03474 SourceLocation PointOfInstantiation, void *InsertPos, 03475 LateInstantiatedAttrVec *LateAttrs, 03476 LocalInstantiationScope *StartingScope) { 03477 if (FromVar->isInvalidDecl()) 03478 return nullptr; 03479 03480 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 03481 if (Inst.isInvalid()) 03482 return nullptr; 03483 03484 MultiLevelTemplateArgumentList TemplateArgLists; 03485 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 03486 03487 // Instantiate the first declaration of the variable template: for a partial 03488 // specialization of a static data member template, the first declaration may 03489 // or may not be the declaration in the class; if it's in the class, we want 03490 // to instantiate a member in the class (a declaration), and if it's outside, 03491 // we want to instantiate a definition. 03492 // 03493 // If we're instantiating an explicitly-specialized member template or member 03494 // partial specialization, don't do this. The member specialization completely 03495 // replaces the original declaration in this case. 03496 bool IsMemberSpec = false; 03497 if (VarTemplatePartialSpecializationDecl *PartialSpec = 03498 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 03499 IsMemberSpec = PartialSpec->isMemberSpecialization(); 03500 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 03501 IsMemberSpec = FromTemplate->isMemberSpecialization(); 03502 if (!IsMemberSpec) 03503 FromVar = FromVar->getFirstDecl(); 03504 03505 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 03506 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 03507 MultiLevelList); 03508 03509 // TODO: Set LateAttrs and StartingScope ... 03510 03511 return cast_or_null<VarTemplateSpecializationDecl>( 03512 Instantiator.VisitVarTemplateSpecializationDecl( 03513 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 03514 } 03515 03516 /// \brief Instantiates a variable template specialization by completing it 03517 /// with appropriate type information and initializer. 03518 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 03519 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 03520 const MultiLevelTemplateArgumentList &TemplateArgs) { 03521 03522 // Do substitution on the type of the declaration 03523 TypeSourceInfo *DI = 03524 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 03525 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 03526 if (!DI) 03527 return nullptr; 03528 03529 // Update the type of this variable template specialization. 03530 VarSpec->setType(DI->getType()); 03531 03532 // Instantiate the initializer. 03533 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 03534 03535 return VarSpec; 03536 } 03537 03538 /// BuildVariableInstantiation - Used after a new variable has been created. 03539 /// Sets basic variable data and decides whether to postpone the 03540 /// variable instantiation. 03541 void Sema::BuildVariableInstantiation( 03542 VarDecl *NewVar, VarDecl *OldVar, 03543 const MultiLevelTemplateArgumentList &TemplateArgs, 03544 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 03545 LocalInstantiationScope *StartingScope, 03546 bool InstantiatingVarTemplate) { 03547 03548 // If we are instantiating a local extern declaration, the 03549 // instantiation belongs lexically to the containing function. 03550 // If we are instantiating a static data member defined 03551 // out-of-line, the instantiation will have the same lexical 03552 // context (which will be a namespace scope) as the template. 03553 if (OldVar->isLocalExternDecl()) { 03554 NewVar->setLocalExternDecl(); 03555 NewVar->setLexicalDeclContext(Owner); 03556 } else if (OldVar->isOutOfLine()) 03557 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 03558 NewVar->setTSCSpec(OldVar->getTSCSpec()); 03559 NewVar->setInitStyle(OldVar->getInitStyle()); 03560 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 03561 NewVar->setConstexpr(OldVar->isConstexpr()); 03562 NewVar->setInitCapture(OldVar->isInitCapture()); 03563 NewVar->setPreviousDeclInSameBlockScope( 03564 OldVar->isPreviousDeclInSameBlockScope()); 03565 NewVar->setAccess(OldVar->getAccess()); 03566 03567 if (!OldVar->isStaticDataMember()) { 03568 if (OldVar->isUsed(false)) 03569 NewVar->setIsUsed(); 03570 NewVar->setReferenced(OldVar->isReferenced()); 03571 } 03572 03573 // See if the old variable had a type-specifier that defined an anonymous tag. 03574 // If it did, mark the new variable as being the declarator for the new 03575 // anonymous tag. 03576 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) { 03577 TagDecl *OldTag = OldTagType->getDecl(); 03578 if (OldTag->getDeclaratorForAnonDecl() == OldVar) { 03579 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl(); 03580 assert(!NewTag->hasNameForLinkage() && 03581 !NewTag->hasDeclaratorForAnonDecl()); 03582 NewTag->setDeclaratorForAnonDecl(NewVar); 03583 } 03584 } 03585 03586 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 03587 03588 LookupResult Previous( 03589 *this, NewVar->getDeclName(), NewVar->getLocation(), 03590 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 03591 : Sema::LookupOrdinaryName, 03592 Sema::ForRedeclaration); 03593 03594 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 03595 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 03596 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 03597 // We have a previous declaration. Use that one, so we merge with the 03598 // right type. 03599 if (NamedDecl *NewPrev = FindInstantiatedDecl( 03600 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 03601 Previous.addDecl(NewPrev); 03602 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 03603 OldVar->hasLinkage()) 03604 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 03605 CheckVariableDeclaration(NewVar, Previous); 03606 03607 if (!InstantiatingVarTemplate) { 03608 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 03609 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 03610 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 03611 } 03612 03613 if (!OldVar->isOutOfLine()) { 03614 if (NewVar->getDeclContext()->isFunctionOrMethod()) 03615 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 03616 } 03617 03618 // Link instantiations of static data members back to the template from 03619 // which they were instantiated. 03620 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate) 03621 NewVar->setInstantiationOfStaticDataMember(OldVar, 03622 TSK_ImplicitInstantiation); 03623 03624 // Forward the mangling number from the template to the instantiated decl. 03625 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 03626 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 03627 03628 // Delay instantiation of the initializer for variable templates until a 03629 // definition of the variable is needed. We need it right away if the type 03630 // contains 'auto'. 03631 if ((!isa<VarTemplateSpecializationDecl>(NewVar) && 03632 !InstantiatingVarTemplate) || 03633 NewVar->getType()->isUndeducedType()) 03634 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 03635 03636 // Diagnose unused local variables with dependent types, where the diagnostic 03637 // will have been deferred. 03638 if (!NewVar->isInvalidDecl() && 03639 NewVar->getDeclContext()->isFunctionOrMethod() && 03640 OldVar->getType()->isDependentType()) 03641 DiagnoseUnusedDecl(NewVar); 03642 } 03643 03644 /// \brief Instantiate the initializer of a variable. 03645 void Sema::InstantiateVariableInitializer( 03646 VarDecl *Var, VarDecl *OldVar, 03647 const MultiLevelTemplateArgumentList &TemplateArgs) { 03648 03649 if (Var->getAnyInitializer()) 03650 // We already have an initializer in the class. 03651 return; 03652 03653 if (OldVar->getInit()) { 03654 if (Var->isStaticDataMember() && !OldVar->isOutOfLine()) 03655 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar); 03656 else 03657 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar); 03658 03659 // Instantiate the initializer. 03660 ExprResult Init = 03661 SubstInitializer(OldVar->getInit(), TemplateArgs, 03662 OldVar->getInitStyle() == VarDecl::CallInit); 03663 if (!Init.isInvalid()) { 03664 bool TypeMayContainAuto = true; 03665 Expr *InitExpr = Init.get(); 03666 03667 if (Var->hasAttr<DLLImportAttr>() && 03668 (!InitExpr || 03669 !InitExpr->isConstantInitializer(getASTContext(), false))) { 03670 // Do not dynamically initialize dllimport variables. 03671 } else if (InitExpr) { 03672 bool DirectInit = OldVar->isDirectInit(); 03673 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto); 03674 } else 03675 ActOnUninitializedDecl(Var, TypeMayContainAuto); 03676 } else { 03677 // FIXME: Not too happy about invalidating the declaration 03678 // because of a bogus initializer. 03679 Var->setInvalidDecl(); 03680 } 03681 03682 PopExpressionEvaluationContext(); 03683 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 03684 !Var->isCXXForRangeDecl()) 03685 ActOnUninitializedDecl(Var, false); 03686 } 03687 03688 /// \brief Instantiate the definition of the given variable from its 03689 /// template. 03690 /// 03691 /// \param PointOfInstantiation the point at which the instantiation was 03692 /// required. Note that this is not precisely a "point of instantiation" 03693 /// for the function, but it's close. 03694 /// 03695 /// \param Var the already-instantiated declaration of a static member 03696 /// variable of a class template specialization. 03697 /// 03698 /// \param Recursive if true, recursively instantiates any functions that 03699 /// are required by this instantiation. 03700 /// 03701 /// \param DefinitionRequired if true, then we are performing an explicit 03702 /// instantiation where an out-of-line definition of the member variable 03703 /// is required. Complain if there is no such definition. 03704 void Sema::InstantiateStaticDataMemberDefinition( 03705 SourceLocation PointOfInstantiation, 03706 VarDecl *Var, 03707 bool Recursive, 03708 bool DefinitionRequired) { 03709 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive, 03710 DefinitionRequired); 03711 } 03712 03713 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 03714 VarDecl *Var, bool Recursive, 03715 bool DefinitionRequired) { 03716 if (Var->isInvalidDecl()) 03717 return; 03718 03719 VarTemplateSpecializationDecl *VarSpec = 03720 dyn_cast<VarTemplateSpecializationDecl>(Var); 03721 VarDecl *PatternDecl = nullptr, *Def = nullptr; 03722 MultiLevelTemplateArgumentList TemplateArgs = 03723 getTemplateInstantiationArgs(Var); 03724 03725 if (VarSpec) { 03726 // If this is a variable template specialization, make sure that it is 03727 // non-dependent, then find its instantiation pattern. 03728 bool InstantiationDependent = false; 03729 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 03730 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 03731 "Only instantiate variable template specializations that are " 03732 "not type-dependent"); 03733 (void)InstantiationDependent; 03734 03735 // Find the variable initialization that we'll be substituting. If the 03736 // pattern was instantiated from a member template, look back further to 03737 // find the real pattern. 03738 assert(VarSpec->getSpecializedTemplate() && 03739 "Specialization without specialized template?"); 03740 llvm::PointerUnion<VarTemplateDecl *, 03741 VarTemplatePartialSpecializationDecl *> PatternPtr = 03742 VarSpec->getSpecializedTemplateOrPartial(); 03743 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) { 03744 VarTemplatePartialSpecializationDecl *Tmpl = 03745 PatternPtr.get<VarTemplatePartialSpecializationDecl *>(); 03746 while (VarTemplatePartialSpecializationDecl *From = 03747 Tmpl->getInstantiatedFromMember()) { 03748 if (Tmpl->isMemberSpecialization()) 03749 break; 03750 03751 Tmpl = From; 03752 } 03753 PatternDecl = Tmpl; 03754 } else { 03755 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>(); 03756 while (VarTemplateDecl *From = 03757 Tmpl->getInstantiatedFromMemberTemplate()) { 03758 if (Tmpl->isMemberSpecialization()) 03759 break; 03760 03761 Tmpl = From; 03762 } 03763 PatternDecl = Tmpl->getTemplatedDecl(); 03764 } 03765 03766 // If this is a static data member template, there might be an 03767 // uninstantiated initializer on the declaration. If so, instantiate 03768 // it now. 03769 if (PatternDecl->isStaticDataMember() && 03770 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 03771 !Var->hasInit()) { 03772 // FIXME: Factor out the duplicated instantiation context setup/tear down 03773 // code here. 03774 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 03775 if (Inst.isInvalid()) 03776 return; 03777 03778 // If we're performing recursive template instantiation, create our own 03779 // queue of pending implicit instantiations that we will instantiate 03780 // later, while we're still within our own instantiation context. 03781 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII> 03782 SavePendingInstantiationsAndVTableUses; 03783 if (Recursive) { 03784 SavePendingInstantiationsAndVTableUses.reset( 03785 new SavePendingInstantiationsAndVTableUsesRAII(*this)); 03786 } 03787 03788 LocalInstantiationScope Local(*this); 03789 03790 // Enter the scope of this instantiation. We don't use 03791 // PushDeclContext because we don't have a scope. 03792 ContextRAII PreviousContext(*this, Var->getDeclContext()); 03793 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 03794 PreviousContext.pop(); 03795 03796 // FIXME: Need to inform the ASTConsumer that we instantiated the 03797 // initializer? 03798 03799 // This variable may have local implicit instantiations that need to be 03800 // instantiated within this scope. 03801 PerformPendingInstantiations(/*LocalOnly=*/true); 03802 03803 Local.Exit(); 03804 03805 if (Recursive) { 03806 // Define any newly required vtables. 03807 DefineUsedVTables(); 03808 03809 // Instantiate any pending implicit instantiations found during the 03810 // instantiation of this template. 03811 PerformPendingInstantiations(); 03812 03813 // Restore PendingInstantiations and VTableUses. 03814 SavePendingInstantiationsAndVTableUses.reset(); 03815 } 03816 } 03817 03818 // Find actual definition 03819 Def = PatternDecl->getDefinition(getASTContext()); 03820 } else { 03821 // If this is a static data member, find its out-of-line definition. 03822 assert(Var->isStaticDataMember() && "not a static data member?"); 03823 PatternDecl = Var->getInstantiatedFromStaticDataMember(); 03824 03825 assert(PatternDecl && "data member was not instantiated from a template?"); 03826 assert(PatternDecl->isStaticDataMember() && "not a static data member?"); 03827 Def = PatternDecl->getOutOfLineDefinition(); 03828 } 03829 03830 // If we don't have a definition of the variable template, we won't perform 03831 // any instantiation. Rather, we rely on the user to instantiate this 03832 // definition (or provide a specialization for it) in another translation 03833 // unit. 03834 if (!Def) { 03835 if (DefinitionRequired) { 03836 if (VarSpec) 03837 Diag(PointOfInstantiation, 03838 diag::err_explicit_instantiation_undefined_var_template) << Var; 03839 else 03840 Diag(PointOfInstantiation, 03841 diag::err_explicit_instantiation_undefined_member) 03842 << 2 << Var->getDeclName() << Var->getDeclContext(); 03843 Diag(PatternDecl->getLocation(), 03844 diag::note_explicit_instantiation_here); 03845 if (VarSpec) 03846 Var->setInvalidDecl(); 03847 } else if (Var->getTemplateSpecializationKind() 03848 == TSK_ExplicitInstantiationDefinition) { 03849 PendingInstantiations.push_back( 03850 std::make_pair(Var, PointOfInstantiation)); 03851 } 03852 03853 return; 03854 } 03855 03856 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 03857 03858 // Never instantiate an explicit specialization. 03859 if (TSK == TSK_ExplicitSpecialization) 03860 return; 03861 03862 // C++11 [temp.explicit]p10: 03863 // Except for inline functions, [...] explicit instantiation declarations 03864 // have the effect of suppressing the implicit instantiation of the entity 03865 // to which they refer. 03866 if (TSK == TSK_ExplicitInstantiationDeclaration) 03867 return; 03868 03869 // Make sure to pass the instantiated variable to the consumer at the end. 03870 struct PassToConsumerRAII { 03871 ASTConsumer &Consumer; 03872 VarDecl *Var; 03873 03874 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 03875 : Consumer(Consumer), Var(Var) { } 03876 03877 ~PassToConsumerRAII() { 03878 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 03879 } 03880 } PassToConsumerRAII(Consumer, Var); 03881 03882 // If we already have a definition, we're done. 03883 if (VarDecl *Def = Var->getDefinition()) { 03884 // We may be explicitly instantiating something we've already implicitly 03885 // instantiated. 03886 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 03887 PointOfInstantiation); 03888 return; 03889 } 03890 03891 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 03892 if (Inst.isInvalid()) 03893 return; 03894 03895 // If we're performing recursive template instantiation, create our own 03896 // queue of pending implicit instantiations that we will instantiate later, 03897 // while we're still within our own instantiation context. 03898 SavePendingLocalImplicitInstantiationsRAII 03899 SavedPendingLocalImplicitInstantiations(*this); 03900 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII> 03901 SavePendingInstantiationsAndVTableUses; 03902 if (Recursive) { 03903 SavePendingInstantiationsAndVTableUses.reset( 03904 new SavePendingInstantiationsAndVTableUsesRAII(*this)); 03905 } 03906 03907 // Enter the scope of this instantiation. We don't use 03908 // PushDeclContext because we don't have a scope. 03909 ContextRAII PreviousContext(*this, Var->getDeclContext()); 03910 LocalInstantiationScope Local(*this); 03911 03912 VarDecl *OldVar = Var; 03913 if (!VarSpec) 03914 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 03915 TemplateArgs)); 03916 else if (Var->isStaticDataMember() && 03917 Var->getLexicalDeclContext()->isRecord()) { 03918 // We need to instantiate the definition of a static data member template, 03919 // and all we have is the in-class declaration of it. Instantiate a separate 03920 // declaration of the definition. 03921 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 03922 TemplateArgs); 03923 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 03924 VarSpec->getSpecializedTemplate(), Def, nullptr, 03925 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 03926 if (Var) { 03927 llvm::PointerUnion<VarTemplateDecl *, 03928 VarTemplatePartialSpecializationDecl *> PatternPtr = 03929 VarSpec->getSpecializedTemplateOrPartial(); 03930 if (VarTemplatePartialSpecializationDecl *Partial = 03931 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 03932 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 03933 Partial, &VarSpec->getTemplateInstantiationArgs()); 03934 03935 // Merge the definition with the declaration. 03936 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 03937 LookupOrdinaryName, ForRedeclaration); 03938 R.addDecl(OldVar); 03939 MergeVarDecl(Var, R); 03940 03941 // Attach the initializer. 03942 InstantiateVariableInitializer(Var, Def, TemplateArgs); 03943 } 03944 } else 03945 // Complete the existing variable's definition with an appropriately 03946 // substituted type and initializer. 03947 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 03948 03949 PreviousContext.pop(); 03950 03951 if (Var) { 03952 PassToConsumerRAII.Var = Var; 03953 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 03954 OldVar->getPointOfInstantiation()); 03955 } 03956 03957 // This variable may have local implicit instantiations that need to be 03958 // instantiated within this scope. 03959 PerformPendingInstantiations(/*LocalOnly=*/true); 03960 03961 Local.Exit(); 03962 03963 if (Recursive) { 03964 // Define any newly required vtables. 03965 DefineUsedVTables(); 03966 03967 // Instantiate any pending implicit instantiations found during the 03968 // instantiation of this template. 03969 PerformPendingInstantiations(); 03970 03971 // Restore PendingInstantiations and VTableUses. 03972 SavePendingInstantiationsAndVTableUses.reset(); 03973 } 03974 } 03975 03976 void 03977 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 03978 const CXXConstructorDecl *Tmpl, 03979 const MultiLevelTemplateArgumentList &TemplateArgs) { 03980 03981 SmallVector<CXXCtorInitializer*, 4> NewInits; 03982 bool AnyErrors = Tmpl->isInvalidDecl(); 03983 03984 // Instantiate all the initializers. 03985 for (const auto *Init : Tmpl->inits()) { 03986 // Only instantiate written initializers, let Sema re-construct implicit 03987 // ones. 03988 if (!Init->isWritten()) 03989 continue; 03990 03991 SourceLocation EllipsisLoc; 03992 03993 if (Init->isPackExpansion()) { 03994 // This is a pack expansion. We should expand it now. 03995 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 03996 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 03997 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 03998 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 03999 bool ShouldExpand = false; 04000 bool RetainExpansion = false; 04001 Optional<unsigned> NumExpansions; 04002 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 04003 BaseTL.getSourceRange(), 04004 Unexpanded, 04005 TemplateArgs, ShouldExpand, 04006 RetainExpansion, 04007 NumExpansions)) { 04008 AnyErrors = true; 04009 New->setInvalidDecl(); 04010 continue; 04011 } 04012 assert(ShouldExpand && "Partial instantiation of base initializer?"); 04013 04014 // Loop over all of the arguments in the argument pack(s), 04015 for (unsigned I = 0; I != *NumExpansions; ++I) { 04016 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 04017 04018 // Instantiate the initializer. 04019 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 04020 /*CXXDirectInit=*/true); 04021 if (TempInit.isInvalid()) { 04022 AnyErrors = true; 04023 break; 04024 } 04025 04026 // Instantiate the base type. 04027 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 04028 TemplateArgs, 04029 Init->getSourceLocation(), 04030 New->getDeclName()); 04031 if (!BaseTInfo) { 04032 AnyErrors = true; 04033 break; 04034 } 04035 04036 // Build the initializer. 04037 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 04038 BaseTInfo, TempInit.get(), 04039 New->getParent(), 04040 SourceLocation()); 04041 if (NewInit.isInvalid()) { 04042 AnyErrors = true; 04043 break; 04044 } 04045 04046 NewInits.push_back(NewInit.get()); 04047 } 04048 04049 continue; 04050 } 04051 04052 // Instantiate the initializer. 04053 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 04054 /*CXXDirectInit=*/true); 04055 if (TempInit.isInvalid()) { 04056 AnyErrors = true; 04057 continue; 04058 } 04059 04060 MemInitResult NewInit; 04061 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 04062 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 04063 TemplateArgs, 04064 Init->getSourceLocation(), 04065 New->getDeclName()); 04066 if (!TInfo) { 04067 AnyErrors = true; 04068 New->setInvalidDecl(); 04069 continue; 04070 } 04071 04072 if (Init->isBaseInitializer()) 04073 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 04074 New->getParent(), EllipsisLoc); 04075 else 04076 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 04077 cast<CXXRecordDecl>(CurContext->getParent())); 04078 } else if (Init->isMemberInitializer()) { 04079 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 04080 Init->getMemberLocation(), 04081 Init->getMember(), 04082 TemplateArgs)); 04083 if (!Member) { 04084 AnyErrors = true; 04085 New->setInvalidDecl(); 04086 continue; 04087 } 04088 04089 NewInit = BuildMemberInitializer(Member, TempInit.get(), 04090 Init->getSourceLocation()); 04091 } else if (Init->isIndirectMemberInitializer()) { 04092 IndirectFieldDecl *IndirectMember = 04093 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 04094 Init->getMemberLocation(), 04095 Init->getIndirectMember(), TemplateArgs)); 04096 04097 if (!IndirectMember) { 04098 AnyErrors = true; 04099 New->setInvalidDecl(); 04100 continue; 04101 } 04102 04103 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 04104 Init->getSourceLocation()); 04105 } 04106 04107 if (NewInit.isInvalid()) { 04108 AnyErrors = true; 04109 New->setInvalidDecl(); 04110 } else { 04111 NewInits.push_back(NewInit.get()); 04112 } 04113 } 04114 04115 // Assign all the initializers to the new constructor. 04116 ActOnMemInitializers(New, 04117 /*FIXME: ColonLoc */ 04118 SourceLocation(), 04119 NewInits, 04120 AnyErrors); 04121 } 04122 04123 // TODO: this could be templated if the various decl types used the 04124 // same method name. 04125 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 04126 ClassTemplateDecl *Instance) { 04127 Pattern = Pattern->getCanonicalDecl(); 04128 04129 do { 04130 Instance = Instance->getCanonicalDecl(); 04131 if (Pattern == Instance) return true; 04132 Instance = Instance->getInstantiatedFromMemberTemplate(); 04133 } while (Instance); 04134 04135 return false; 04136 } 04137 04138 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 04139 FunctionTemplateDecl *Instance) { 04140 Pattern = Pattern->getCanonicalDecl(); 04141 04142 do { 04143 Instance = Instance->getCanonicalDecl(); 04144 if (Pattern == Instance) return true; 04145 Instance = Instance->getInstantiatedFromMemberTemplate(); 04146 } while (Instance); 04147 04148 return false; 04149 } 04150 04151 static bool 04152 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 04153 ClassTemplatePartialSpecializationDecl *Instance) { 04154 Pattern 04155 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 04156 do { 04157 Instance = cast<ClassTemplatePartialSpecializationDecl>( 04158 Instance->getCanonicalDecl()); 04159 if (Pattern == Instance) 04160 return true; 04161 Instance = Instance->getInstantiatedFromMember(); 04162 } while (Instance); 04163 04164 return false; 04165 } 04166 04167 static bool isInstantiationOf(CXXRecordDecl *Pattern, 04168 CXXRecordDecl *Instance) { 04169 Pattern = Pattern->getCanonicalDecl(); 04170 04171 do { 04172 Instance = Instance->getCanonicalDecl(); 04173 if (Pattern == Instance) return true; 04174 Instance = Instance->getInstantiatedFromMemberClass(); 04175 } while (Instance); 04176 04177 return false; 04178 } 04179 04180 static bool isInstantiationOf(FunctionDecl *Pattern, 04181 FunctionDecl *Instance) { 04182 Pattern = Pattern->getCanonicalDecl(); 04183 04184 do { 04185 Instance = Instance->getCanonicalDecl(); 04186 if (Pattern == Instance) return true; 04187 Instance = Instance->getInstantiatedFromMemberFunction(); 04188 } while (Instance); 04189 04190 return false; 04191 } 04192 04193 static bool isInstantiationOf(EnumDecl *Pattern, 04194 EnumDecl *Instance) { 04195 Pattern = Pattern->getCanonicalDecl(); 04196 04197 do { 04198 Instance = Instance->getCanonicalDecl(); 04199 if (Pattern == Instance) return true; 04200 Instance = Instance->getInstantiatedFromMemberEnum(); 04201 } while (Instance); 04202 04203 return false; 04204 } 04205 04206 static bool isInstantiationOf(UsingShadowDecl *Pattern, 04207 UsingShadowDecl *Instance, 04208 ASTContext &C) { 04209 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 04210 Pattern); 04211 } 04212 04213 static bool isInstantiationOf(UsingDecl *Pattern, 04214 UsingDecl *Instance, 04215 ASTContext &C) { 04216 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 04217 } 04218 04219 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 04220 UsingDecl *Instance, 04221 ASTContext &C) { 04222 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 04223 } 04224 04225 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 04226 UsingDecl *Instance, 04227 ASTContext &C) { 04228 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 04229 } 04230 04231 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 04232 VarDecl *Instance) { 04233 assert(Instance->isStaticDataMember()); 04234 04235 Pattern = Pattern->getCanonicalDecl(); 04236 04237 do { 04238 Instance = Instance->getCanonicalDecl(); 04239 if (Pattern == Instance) return true; 04240 Instance = Instance->getInstantiatedFromStaticDataMember(); 04241 } while (Instance); 04242 04243 return false; 04244 } 04245 04246 // Other is the prospective instantiation 04247 // D is the prospective pattern 04248 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 04249 if (D->getKind() != Other->getKind()) { 04250 if (UnresolvedUsingTypenameDecl *UUD 04251 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 04252 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 04253 return isInstantiationOf(UUD, UD, Ctx); 04254 } 04255 } 04256 04257 if (UnresolvedUsingValueDecl *UUD 04258 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 04259 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 04260 return isInstantiationOf(UUD, UD, Ctx); 04261 } 04262 } 04263 04264 return false; 04265 } 04266 04267 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 04268 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 04269 04270 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 04271 return isInstantiationOf(cast<FunctionDecl>(D), Function); 04272 04273 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 04274 return isInstantiationOf(cast<EnumDecl>(D), Enum); 04275 04276 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 04277 if (Var->isStaticDataMember()) 04278 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 04279 04280 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 04281 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 04282 04283 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 04284 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 04285 04286 if (ClassTemplatePartialSpecializationDecl *PartialSpec 04287 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 04288 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 04289 PartialSpec); 04290 04291 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 04292 if (!Field->getDeclName()) { 04293 // This is an unnamed field. 04294 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 04295 cast<FieldDecl>(D)); 04296 } 04297 } 04298 04299 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 04300 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 04301 04302 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 04303 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 04304 04305 return D->getDeclName() && isa<NamedDecl>(Other) && 04306 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 04307 } 04308 04309 template<typename ForwardIterator> 04310 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 04311 NamedDecl *D, 04312 ForwardIterator first, 04313 ForwardIterator last) { 04314 for (; first != last; ++first) 04315 if (isInstantiationOf(Ctx, D, *first)) 04316 return cast<NamedDecl>(*first); 04317 04318 return nullptr; 04319 } 04320 04321 /// \brief Finds the instantiation of the given declaration context 04322 /// within the current instantiation. 04323 /// 04324 /// \returns NULL if there was an error 04325 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 04326 const MultiLevelTemplateArgumentList &TemplateArgs) { 04327 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 04328 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 04329 return cast_or_null<DeclContext>(ID); 04330 } else return DC; 04331 } 04332 04333 /// \brief Find the instantiation of the given declaration within the 04334 /// current instantiation. 04335 /// 04336 /// This routine is intended to be used when \p D is a declaration 04337 /// referenced from within a template, that needs to mapped into the 04338 /// corresponding declaration within an instantiation. For example, 04339 /// given: 04340 /// 04341 /// \code 04342 /// template<typename T> 04343 /// struct X { 04344 /// enum Kind { 04345 /// KnownValue = sizeof(T) 04346 /// }; 04347 /// 04348 /// bool getKind() const { return KnownValue; } 04349 /// }; 04350 /// 04351 /// template struct X<int>; 04352 /// \endcode 04353 /// 04354 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 04355 /// \p EnumConstantDecl for \p KnownValue (which refers to 04356 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 04357 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 04358 /// this mapping from within the instantiation of <tt>X<int></tt>. 04359 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 04360 const MultiLevelTemplateArgumentList &TemplateArgs) { 04361 DeclContext *ParentDC = D->getDeclContext(); 04362 // FIXME: Parmeters of pointer to functions (y below) that are themselves 04363 // parameters (p below) can have their ParentDC set to the translation-unit 04364 // - thus we can not consistently check if the ParentDC of such a parameter 04365 // is Dependent or/and a FunctionOrMethod. 04366 // For e.g. this code, during Template argument deduction tries to 04367 // find an instantiated decl for (T y) when the ParentDC for y is 04368 // the translation unit. 04369 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 04370 // float baz(float(*)()) { return 0.0; } 04371 // Foo(baz); 04372 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 04373 // it gets here, always has a FunctionOrMethod as its ParentDC?? 04374 // For now: 04375 // - as long as we have a ParmVarDecl whose parent is non-dependent and 04376 // whose type is not instantiation dependent, do nothing to the decl 04377 // - otherwise find its instantiated decl. 04378 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 04379 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 04380 return D; 04381 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 04382 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 04383 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 04384 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 04385 // D is a local of some kind. Look into the map of local 04386 // declarations to their instantiations. 04387 if (CurrentInstantiationScope) { 04388 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 04389 if (Decl *FD = Found->dyn_cast<Decl *>()) 04390 return cast<NamedDecl>(FD); 04391 04392 int PackIdx = ArgumentPackSubstitutionIndex; 04393 assert(PackIdx != -1 && 04394 "found declaration pack but not pack expanding"); 04395 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 04396 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 04397 } 04398 } 04399 04400 // If we're performing a partial substitution during template argument 04401 // deduction, we may not have values for template parameters yet. They 04402 // just map to themselves. 04403 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 04404 isa<TemplateTemplateParmDecl>(D)) 04405 return D; 04406 04407 if (D->isInvalidDecl()) 04408 return nullptr; 04409 04410 // If we didn't find the decl, then we must have a label decl that hasn't 04411 // been found yet. Lazily instantiate it and return it now. 04412 assert(isa<LabelDecl>(D)); 04413 04414 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 04415 assert(Inst && "Failed to instantiate label??"); 04416 04417 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 04418 return cast<LabelDecl>(Inst); 04419 } 04420 04421 // For variable template specializations, update those that are still 04422 // type-dependent. 04423 if (VarTemplateSpecializationDecl *VarSpec = 04424 dyn_cast<VarTemplateSpecializationDecl>(D)) { 04425 bool InstantiationDependent = false; 04426 const TemplateArgumentListInfo &VarTemplateArgs = 04427 VarSpec->getTemplateArgsInfo(); 04428 if (TemplateSpecializationType::anyDependentTemplateArguments( 04429 VarTemplateArgs, InstantiationDependent)) 04430 D = cast<NamedDecl>( 04431 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 04432 return D; 04433 } 04434 04435 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 04436 if (!Record->isDependentContext()) 04437 return D; 04438 04439 // Determine whether this record is the "templated" declaration describing 04440 // a class template or class template partial specialization. 04441 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 04442 if (ClassTemplate) 04443 ClassTemplate = ClassTemplate->getCanonicalDecl(); 04444 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 04445 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 04446 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 04447 04448 // Walk the current context to find either the record or an instantiation of 04449 // it. 04450 DeclContext *DC = CurContext; 04451 while (!DC->isFileContext()) { 04452 // If we're performing substitution while we're inside the template 04453 // definition, we'll find our own context. We're done. 04454 if (DC->Equals(Record)) 04455 return Record; 04456 04457 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 04458 // Check whether we're in the process of instantiating a class template 04459 // specialization of the template we're mapping. 04460 if (ClassTemplateSpecializationDecl *InstSpec 04461 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 04462 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 04463 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 04464 return InstRecord; 04465 } 04466 04467 // Check whether we're in the process of instantiating a member class. 04468 if (isInstantiationOf(Record, InstRecord)) 04469 return InstRecord; 04470 } 04471 04472 // Move to the outer template scope. 04473 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 04474 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 04475 DC = FD->getLexicalDeclContext(); 04476 continue; 04477 } 04478 } 04479 04480 DC = DC->getParent(); 04481 } 04482 04483 // Fall through to deal with other dependent record types (e.g., 04484 // anonymous unions in class templates). 04485 } 04486 04487 if (!ParentDC->isDependentContext()) 04488 return D; 04489 04490 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 04491 if (!ParentDC) 04492 return nullptr; 04493 04494 if (ParentDC != D->getDeclContext()) { 04495 // We performed some kind of instantiation in the parent context, 04496 // so now we need to look into the instantiated parent context to 04497 // find the instantiation of the declaration D. 04498 04499 // If our context used to be dependent, we may need to instantiate 04500 // it before performing lookup into that context. 04501 bool IsBeingInstantiated = false; 04502 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 04503 if (!Spec->isDependentContext()) { 04504 QualType T = Context.getTypeDeclType(Spec); 04505 const RecordType *Tag = T->getAs<RecordType>(); 04506 assert(Tag && "type of non-dependent record is not a RecordType"); 04507 if (Tag->isBeingDefined()) 04508 IsBeingInstantiated = true; 04509 if (!Tag->isBeingDefined() && 04510 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 04511 return nullptr; 04512 04513 ParentDC = Tag->getDecl(); 04514 } 04515 } 04516 04517 NamedDecl *Result = nullptr; 04518 if (D->getDeclName()) { 04519 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 04520 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 04521 } else { 04522 // Since we don't have a name for the entity we're looking for, 04523 // our only option is to walk through all of the declarations to 04524 // find that name. This will occur in a few cases: 04525 // 04526 // - anonymous struct/union within a template 04527 // - unnamed class/struct/union/enum within a template 04528 // 04529 // FIXME: Find a better way to find these instantiations! 04530 Result = findInstantiationOf(Context, D, 04531 ParentDC->decls_begin(), 04532 ParentDC->decls_end()); 04533 } 04534 04535 if (!Result) { 04536 if (isa<UsingShadowDecl>(D)) { 04537 // UsingShadowDecls can instantiate to nothing because of using hiding. 04538 } else if (Diags.hasErrorOccurred()) { 04539 // We've already complained about something, so most likely this 04540 // declaration failed to instantiate. There's no point in complaining 04541 // further, since this is normal in invalid code. 04542 } else if (IsBeingInstantiated) { 04543 // The class in which this member exists is currently being 04544 // instantiated, and we haven't gotten around to instantiating this 04545 // member yet. This can happen when the code uses forward declarations 04546 // of member classes, and introduces ordering dependencies via 04547 // template instantiation. 04548 Diag(Loc, diag::err_member_not_yet_instantiated) 04549 << D->getDeclName() 04550 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 04551 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 04552 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 04553 // This enumeration constant was found when the template was defined, 04554 // but can't be found in the instantiation. This can happen if an 04555 // unscoped enumeration member is explicitly specialized. 04556 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 04557 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 04558 TemplateArgs)); 04559 assert(Spec->getTemplateSpecializationKind() == 04560 TSK_ExplicitSpecialization); 04561 Diag(Loc, diag::err_enumerator_does_not_exist) 04562 << D->getDeclName() 04563 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 04564 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 04565 << Context.getTypeDeclType(Spec); 04566 } else { 04567 // We should have found something, but didn't. 04568 llvm_unreachable("Unable to find instantiation of declaration!"); 04569 } 04570 } 04571 04572 D = Result; 04573 } 04574 04575 return D; 04576 } 04577 04578 /// \brief Performs template instantiation for all implicit template 04579 /// instantiations we have seen until this point. 04580 void Sema::PerformPendingInstantiations(bool LocalOnly) { 04581 while (!PendingLocalImplicitInstantiations.empty() || 04582 (!LocalOnly && !PendingInstantiations.empty())) { 04583 PendingImplicitInstantiation Inst; 04584 04585 if (PendingLocalImplicitInstantiations.empty()) { 04586 Inst = PendingInstantiations.front(); 04587 PendingInstantiations.pop_front(); 04588 } else { 04589 Inst = PendingLocalImplicitInstantiations.front(); 04590 PendingLocalImplicitInstantiations.pop_front(); 04591 } 04592 04593 // Instantiate function definitions 04594 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 04595 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 04596 "instantiating function definition"); 04597 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 04598 TSK_ExplicitInstantiationDefinition; 04599 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 04600 DefinitionRequired); 04601 continue; 04602 } 04603 04604 // Instantiate variable definitions 04605 VarDecl *Var = cast<VarDecl>(Inst.first); 04606 04607 assert((Var->isStaticDataMember() || 04608 isa<VarTemplateSpecializationDecl>(Var)) && 04609 "Not a static data member, nor a variable template" 04610 " specialization?"); 04611 04612 // Don't try to instantiate declarations if the most recent redeclaration 04613 // is invalid. 04614 if (Var->getMostRecentDecl()->isInvalidDecl()) 04615 continue; 04616 04617 // Check if the most recent declaration has changed the specialization kind 04618 // and removed the need for implicit instantiation. 04619 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 04620 case TSK_Undeclared: 04621 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 04622 case TSK_ExplicitInstantiationDeclaration: 04623 case TSK_ExplicitSpecialization: 04624 continue; // No longer need to instantiate this type. 04625 case TSK_ExplicitInstantiationDefinition: 04626 // We only need an instantiation if the pending instantiation *is* the 04627 // explicit instantiation. 04628 if (Var != Var->getMostRecentDecl()) continue; 04629 case TSK_ImplicitInstantiation: 04630 break; 04631 } 04632 04633 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 04634 "instantiating variable definition"); 04635 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 04636 TSK_ExplicitInstantiationDefinition; 04637 04638 // Instantiate static data member definitions or variable template 04639 // specializations. 04640 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 04641 DefinitionRequired); 04642 } 04643 } 04644 04645 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 04646 const MultiLevelTemplateArgumentList &TemplateArgs) { 04647 for (auto DD : Pattern->ddiags()) { 04648 switch (DD->getKind()) { 04649 case DependentDiagnostic::Access: 04650 HandleDependentAccessCheck(*DD, TemplateArgs); 04651 break; 04652 } 04653 } 04654 }