xref: /aosp_15_r20/external/clang/lib/Sema/SemaTemplate.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //===----------------------------------------------------------------------===//
8*67e74705SXin Li //
9*67e74705SXin Li //  This file implements semantic analysis for C++ templates.
10*67e74705SXin Li //===----------------------------------------------------------------------===//
11*67e74705SXin Li 
12*67e74705SXin Li #include "TreeTransform.h"
13*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
14*67e74705SXin Li #include "clang/AST/ASTContext.h"
15*67e74705SXin Li #include "clang/AST/DeclFriend.h"
16*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
17*67e74705SXin Li #include "clang/AST/Expr.h"
18*67e74705SXin Li #include "clang/AST/ExprCXX.h"
19*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
20*67e74705SXin Li #include "clang/AST/TypeVisitor.h"
21*67e74705SXin Li #include "clang/Basic/Builtins.h"
22*67e74705SXin Li #include "clang/Basic/LangOptions.h"
23*67e74705SXin Li #include "clang/Basic/PartialDiagnostic.h"
24*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
25*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
26*67e74705SXin Li #include "clang/Sema/Lookup.h"
27*67e74705SXin Li #include "clang/Sema/ParsedTemplate.h"
28*67e74705SXin Li #include "clang/Sema/Scope.h"
29*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
30*67e74705SXin Li #include "clang/Sema/Template.h"
31*67e74705SXin Li #include "clang/Sema/TemplateDeduction.h"
32*67e74705SXin Li #include "llvm/ADT/SmallBitVector.h"
33*67e74705SXin Li #include "llvm/ADT/SmallString.h"
34*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
35*67e74705SXin Li 
36*67e74705SXin Li #include <iterator>
37*67e74705SXin Li using namespace clang;
38*67e74705SXin Li using namespace sema;
39*67e74705SXin Li 
40*67e74705SXin Li // Exported for use by Parser.
41*67e74705SXin Li SourceRange
getTemplateParamsRange(TemplateParameterList const * const * Ps,unsigned N)42*67e74705SXin Li clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43*67e74705SXin Li                               unsigned N) {
44*67e74705SXin Li   if (!N) return SourceRange();
45*67e74705SXin Li   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46*67e74705SXin Li }
47*67e74705SXin Li 
48*67e74705SXin Li /// \brief Determine whether the declaration found is acceptable as the name
49*67e74705SXin Li /// of a template and, if so, return that template declaration. Otherwise,
50*67e74705SXin Li /// returns NULL.
isAcceptableTemplateName(ASTContext & Context,NamedDecl * Orig,bool AllowFunctionTemplates)51*67e74705SXin Li static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
52*67e74705SXin Li                                            NamedDecl *Orig,
53*67e74705SXin Li                                            bool AllowFunctionTemplates) {
54*67e74705SXin Li   NamedDecl *D = Orig->getUnderlyingDecl();
55*67e74705SXin Li 
56*67e74705SXin Li   if (isa<TemplateDecl>(D)) {
57*67e74705SXin Li     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
58*67e74705SXin Li       return nullptr;
59*67e74705SXin Li 
60*67e74705SXin Li     return Orig;
61*67e74705SXin Li   }
62*67e74705SXin Li 
63*67e74705SXin Li   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
64*67e74705SXin Li     // C++ [temp.local]p1:
65*67e74705SXin Li     //   Like normal (non-template) classes, class templates have an
66*67e74705SXin Li     //   injected-class-name (Clause 9). The injected-class-name
67*67e74705SXin Li     //   can be used with or without a template-argument-list. When
68*67e74705SXin Li     //   it is used without a template-argument-list, it is
69*67e74705SXin Li     //   equivalent to the injected-class-name followed by the
70*67e74705SXin Li     //   template-parameters of the class template enclosed in
71*67e74705SXin Li     //   <>. When it is used with a template-argument-list, it
72*67e74705SXin Li     //   refers to the specified class template specialization,
73*67e74705SXin Li     //   which could be the current specialization or another
74*67e74705SXin Li     //   specialization.
75*67e74705SXin Li     if (Record->isInjectedClassName()) {
76*67e74705SXin Li       Record = cast<CXXRecordDecl>(Record->getDeclContext());
77*67e74705SXin Li       if (Record->getDescribedClassTemplate())
78*67e74705SXin Li         return Record->getDescribedClassTemplate();
79*67e74705SXin Li 
80*67e74705SXin Li       if (ClassTemplateSpecializationDecl *Spec
81*67e74705SXin Li             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
82*67e74705SXin Li         return Spec->getSpecializedTemplate();
83*67e74705SXin Li     }
84*67e74705SXin Li 
85*67e74705SXin Li     return nullptr;
86*67e74705SXin Li   }
87*67e74705SXin Li 
88*67e74705SXin Li   return nullptr;
89*67e74705SXin Li }
90*67e74705SXin Li 
FilterAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates)91*67e74705SXin Li void Sema::FilterAcceptableTemplateNames(LookupResult &R,
92*67e74705SXin Li                                          bool AllowFunctionTemplates) {
93*67e74705SXin Li   // The set of class templates we've already seen.
94*67e74705SXin Li   llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
95*67e74705SXin Li   LookupResult::Filter filter = R.makeFilter();
96*67e74705SXin Li   while (filter.hasNext()) {
97*67e74705SXin Li     NamedDecl *Orig = filter.next();
98*67e74705SXin Li     NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
99*67e74705SXin Li                                                AllowFunctionTemplates);
100*67e74705SXin Li     if (!Repl)
101*67e74705SXin Li       filter.erase();
102*67e74705SXin Li     else if (Repl != Orig) {
103*67e74705SXin Li 
104*67e74705SXin Li       // C++ [temp.local]p3:
105*67e74705SXin Li       //   A lookup that finds an injected-class-name (10.2) can result in an
106*67e74705SXin Li       //   ambiguity in certain cases (for example, if it is found in more than
107*67e74705SXin Li       //   one base class). If all of the injected-class-names that are found
108*67e74705SXin Li       //   refer to specializations of the same class template, and if the name
109*67e74705SXin Li       //   is used as a template-name, the reference refers to the class
110*67e74705SXin Li       //   template itself and not a specialization thereof, and is not
111*67e74705SXin Li       //   ambiguous.
112*67e74705SXin Li       if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
113*67e74705SXin Li         if (!ClassTemplates.insert(ClassTmpl).second) {
114*67e74705SXin Li           filter.erase();
115*67e74705SXin Li           continue;
116*67e74705SXin Li         }
117*67e74705SXin Li 
118*67e74705SXin Li       // FIXME: we promote access to public here as a workaround to
119*67e74705SXin Li       // the fact that LookupResult doesn't let us remember that we
120*67e74705SXin Li       // found this template through a particular injected class name,
121*67e74705SXin Li       // which means we end up doing nasty things to the invariants.
122*67e74705SXin Li       // Pretending that access is public is *much* safer.
123*67e74705SXin Li       filter.replace(Repl, AS_public);
124*67e74705SXin Li     }
125*67e74705SXin Li   }
126*67e74705SXin Li   filter.done();
127*67e74705SXin Li }
128*67e74705SXin Li 
hasAnyAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates)129*67e74705SXin Li bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
130*67e74705SXin Li                                          bool AllowFunctionTemplates) {
131*67e74705SXin Li   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
132*67e74705SXin Li     if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
133*67e74705SXin Li       return true;
134*67e74705SXin Li 
135*67e74705SXin Li   return false;
136*67e74705SXin Li }
137*67e74705SXin Li 
isTemplateName(Scope * S,CXXScopeSpec & SS,bool hasTemplateKeyword,UnqualifiedId & Name,ParsedType ObjectTypePtr,bool EnteringContext,TemplateTy & TemplateResult,bool & MemberOfUnknownSpecialization)138*67e74705SXin Li TemplateNameKind Sema::isTemplateName(Scope *S,
139*67e74705SXin Li                                       CXXScopeSpec &SS,
140*67e74705SXin Li                                       bool hasTemplateKeyword,
141*67e74705SXin Li                                       UnqualifiedId &Name,
142*67e74705SXin Li                                       ParsedType ObjectTypePtr,
143*67e74705SXin Li                                       bool EnteringContext,
144*67e74705SXin Li                                       TemplateTy &TemplateResult,
145*67e74705SXin Li                                       bool &MemberOfUnknownSpecialization) {
146*67e74705SXin Li   assert(getLangOpts().CPlusPlus && "No template names in C!");
147*67e74705SXin Li 
148*67e74705SXin Li   DeclarationName TName;
149*67e74705SXin Li   MemberOfUnknownSpecialization = false;
150*67e74705SXin Li 
151*67e74705SXin Li   switch (Name.getKind()) {
152*67e74705SXin Li   case UnqualifiedId::IK_Identifier:
153*67e74705SXin Li     TName = DeclarationName(Name.Identifier);
154*67e74705SXin Li     break;
155*67e74705SXin Li 
156*67e74705SXin Li   case UnqualifiedId::IK_OperatorFunctionId:
157*67e74705SXin Li     TName = Context.DeclarationNames.getCXXOperatorName(
158*67e74705SXin Li                                               Name.OperatorFunctionId.Operator);
159*67e74705SXin Li     break;
160*67e74705SXin Li 
161*67e74705SXin Li   case UnqualifiedId::IK_LiteralOperatorId:
162*67e74705SXin Li     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163*67e74705SXin Li     break;
164*67e74705SXin Li 
165*67e74705SXin Li   default:
166*67e74705SXin Li     return TNK_Non_template;
167*67e74705SXin Li   }
168*67e74705SXin Li 
169*67e74705SXin Li   QualType ObjectType = ObjectTypePtr.get();
170*67e74705SXin Li 
171*67e74705SXin Li   LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
172*67e74705SXin Li   LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
173*67e74705SXin Li                      MemberOfUnknownSpecialization);
174*67e74705SXin Li   if (R.empty()) return TNK_Non_template;
175*67e74705SXin Li   if (R.isAmbiguous()) {
176*67e74705SXin Li     // Suppress diagnostics;  we'll redo this lookup later.
177*67e74705SXin Li     R.suppressDiagnostics();
178*67e74705SXin Li 
179*67e74705SXin Li     // FIXME: we might have ambiguous templates, in which case we
180*67e74705SXin Li     // should at least parse them properly!
181*67e74705SXin Li     return TNK_Non_template;
182*67e74705SXin Li   }
183*67e74705SXin Li 
184*67e74705SXin Li   TemplateName Template;
185*67e74705SXin Li   TemplateNameKind TemplateKind;
186*67e74705SXin Li 
187*67e74705SXin Li   unsigned ResultCount = R.end() - R.begin();
188*67e74705SXin Li   if (ResultCount > 1) {
189*67e74705SXin Li     // We assume that we'll preserve the qualifier from a function
190*67e74705SXin Li     // template name in other ways.
191*67e74705SXin Li     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
192*67e74705SXin Li     TemplateKind = TNK_Function_template;
193*67e74705SXin Li 
194*67e74705SXin Li     // We'll do this lookup again later.
195*67e74705SXin Li     R.suppressDiagnostics();
196*67e74705SXin Li   } else {
197*67e74705SXin Li     TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
198*67e74705SXin Li 
199*67e74705SXin Li     if (SS.isSet() && !SS.isInvalid()) {
200*67e74705SXin Li       NestedNameSpecifier *Qualifier = SS.getScopeRep();
201*67e74705SXin Li       Template = Context.getQualifiedTemplateName(Qualifier,
202*67e74705SXin Li                                                   hasTemplateKeyword, TD);
203*67e74705SXin Li     } else {
204*67e74705SXin Li       Template = TemplateName(TD);
205*67e74705SXin Li     }
206*67e74705SXin Li 
207*67e74705SXin Li     if (isa<FunctionTemplateDecl>(TD)) {
208*67e74705SXin Li       TemplateKind = TNK_Function_template;
209*67e74705SXin Li 
210*67e74705SXin Li       // We'll do this lookup again later.
211*67e74705SXin Li       R.suppressDiagnostics();
212*67e74705SXin Li     } else {
213*67e74705SXin Li       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
214*67e74705SXin Li              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
215*67e74705SXin Li              isa<BuiltinTemplateDecl>(TD));
216*67e74705SXin Li       TemplateKind =
217*67e74705SXin Li           isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
218*67e74705SXin Li     }
219*67e74705SXin Li   }
220*67e74705SXin Li 
221*67e74705SXin Li   TemplateResult = TemplateTy::make(Template);
222*67e74705SXin Li   return TemplateKind;
223*67e74705SXin Li }
224*67e74705SXin Li 
DiagnoseUnknownTemplateName(const IdentifierInfo & II,SourceLocation IILoc,Scope * S,const CXXScopeSpec * SS,TemplateTy & SuggestedTemplate,TemplateNameKind & SuggestedKind)225*67e74705SXin Li bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
226*67e74705SXin Li                                        SourceLocation IILoc,
227*67e74705SXin Li                                        Scope *S,
228*67e74705SXin Li                                        const CXXScopeSpec *SS,
229*67e74705SXin Li                                        TemplateTy &SuggestedTemplate,
230*67e74705SXin Li                                        TemplateNameKind &SuggestedKind) {
231*67e74705SXin Li   // We can't recover unless there's a dependent scope specifier preceding the
232*67e74705SXin Li   // template name.
233*67e74705SXin Li   // FIXME: Typo correction?
234*67e74705SXin Li   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
235*67e74705SXin Li       computeDeclContext(*SS))
236*67e74705SXin Li     return false;
237*67e74705SXin Li 
238*67e74705SXin Li   // The code is missing a 'template' keyword prior to the dependent template
239*67e74705SXin Li   // name.
240*67e74705SXin Li   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
241*67e74705SXin Li   Diag(IILoc, diag::err_template_kw_missing)
242*67e74705SXin Li     << Qualifier << II.getName()
243*67e74705SXin Li     << FixItHint::CreateInsertion(IILoc, "template ");
244*67e74705SXin Li   SuggestedTemplate
245*67e74705SXin Li     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
246*67e74705SXin Li   SuggestedKind = TNK_Dependent_template_name;
247*67e74705SXin Li   return true;
248*67e74705SXin Li }
249*67e74705SXin Li 
LookupTemplateName(LookupResult & Found,Scope * S,CXXScopeSpec & SS,QualType ObjectType,bool EnteringContext,bool & MemberOfUnknownSpecialization)250*67e74705SXin Li void Sema::LookupTemplateName(LookupResult &Found,
251*67e74705SXin Li                               Scope *S, CXXScopeSpec &SS,
252*67e74705SXin Li                               QualType ObjectType,
253*67e74705SXin Li                               bool EnteringContext,
254*67e74705SXin Li                               bool &MemberOfUnknownSpecialization) {
255*67e74705SXin Li   // Determine where to perform name lookup
256*67e74705SXin Li   MemberOfUnknownSpecialization = false;
257*67e74705SXin Li   DeclContext *LookupCtx = nullptr;
258*67e74705SXin Li   bool isDependent = false;
259*67e74705SXin Li   if (!ObjectType.isNull()) {
260*67e74705SXin Li     // This nested-name-specifier occurs in a member access expression, e.g.,
261*67e74705SXin Li     // x->B::f, and we are looking into the type of the object.
262*67e74705SXin Li     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
263*67e74705SXin Li     LookupCtx = computeDeclContext(ObjectType);
264*67e74705SXin Li     isDependent = ObjectType->isDependentType();
265*67e74705SXin Li     assert((isDependent || !ObjectType->isIncompleteType() ||
266*67e74705SXin Li             ObjectType->castAs<TagType>()->isBeingDefined()) &&
267*67e74705SXin Li            "Caller should have completed object type");
268*67e74705SXin Li 
269*67e74705SXin Li     // Template names cannot appear inside an Objective-C class or object type.
270*67e74705SXin Li     if (ObjectType->isObjCObjectOrInterfaceType()) {
271*67e74705SXin Li       Found.clear();
272*67e74705SXin Li       return;
273*67e74705SXin Li     }
274*67e74705SXin Li   } else if (SS.isSet()) {
275*67e74705SXin Li     // This nested-name-specifier occurs after another nested-name-specifier,
276*67e74705SXin Li     // so long into the context associated with the prior nested-name-specifier.
277*67e74705SXin Li     LookupCtx = computeDeclContext(SS, EnteringContext);
278*67e74705SXin Li     isDependent = isDependentScopeSpecifier(SS);
279*67e74705SXin Li 
280*67e74705SXin Li     // The declaration context must be complete.
281*67e74705SXin Li     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
282*67e74705SXin Li       return;
283*67e74705SXin Li   }
284*67e74705SXin Li 
285*67e74705SXin Li   bool ObjectTypeSearchedInScope = false;
286*67e74705SXin Li   bool AllowFunctionTemplatesInLookup = true;
287*67e74705SXin Li   if (LookupCtx) {
288*67e74705SXin Li     // Perform "qualified" name lookup into the declaration context we
289*67e74705SXin Li     // computed, which is either the type of the base of a member access
290*67e74705SXin Li     // expression or the declaration context associated with a prior
291*67e74705SXin Li     // nested-name-specifier.
292*67e74705SXin Li     LookupQualifiedName(Found, LookupCtx);
293*67e74705SXin Li     if (!ObjectType.isNull() && Found.empty()) {
294*67e74705SXin Li       // C++ [basic.lookup.classref]p1:
295*67e74705SXin Li       //   In a class member access expression (5.2.5), if the . or -> token is
296*67e74705SXin Li       //   immediately followed by an identifier followed by a <, the
297*67e74705SXin Li       //   identifier must be looked up to determine whether the < is the
298*67e74705SXin Li       //   beginning of a template argument list (14.2) or a less-than operator.
299*67e74705SXin Li       //   The identifier is first looked up in the class of the object
300*67e74705SXin Li       //   expression. If the identifier is not found, it is then looked up in
301*67e74705SXin Li       //   the context of the entire postfix-expression and shall name a class
302*67e74705SXin Li       //   or function template.
303*67e74705SXin Li       if (S) LookupName(Found, S);
304*67e74705SXin Li       ObjectTypeSearchedInScope = true;
305*67e74705SXin Li       AllowFunctionTemplatesInLookup = false;
306*67e74705SXin Li     }
307*67e74705SXin Li   } else if (isDependent && (!S || ObjectType.isNull())) {
308*67e74705SXin Li     // We cannot look into a dependent object type or nested nme
309*67e74705SXin Li     // specifier.
310*67e74705SXin Li     MemberOfUnknownSpecialization = true;
311*67e74705SXin Li     return;
312*67e74705SXin Li   } else {
313*67e74705SXin Li     // Perform unqualified name lookup in the current scope.
314*67e74705SXin Li     LookupName(Found, S);
315*67e74705SXin Li 
316*67e74705SXin Li     if (!ObjectType.isNull())
317*67e74705SXin Li       AllowFunctionTemplatesInLookup = false;
318*67e74705SXin Li   }
319*67e74705SXin Li 
320*67e74705SXin Li   if (Found.empty() && !isDependent) {
321*67e74705SXin Li     // If we did not find any names, attempt to correct any typos.
322*67e74705SXin Li     DeclarationName Name = Found.getLookupName();
323*67e74705SXin Li     Found.clear();
324*67e74705SXin Li     // Simple filter callback that, for keywords, only accepts the C++ *_cast
325*67e74705SXin Li     auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
326*67e74705SXin Li     FilterCCC->WantTypeSpecifiers = false;
327*67e74705SXin Li     FilterCCC->WantExpressionKeywords = false;
328*67e74705SXin Li     FilterCCC->WantRemainingKeywords = false;
329*67e74705SXin Li     FilterCCC->WantCXXNamedCasts = true;
330*67e74705SXin Li     if (TypoCorrection Corrected = CorrectTypo(
331*67e74705SXin Li             Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
332*67e74705SXin Li             std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
333*67e74705SXin Li       Found.setLookupName(Corrected.getCorrection());
334*67e74705SXin Li       if (auto *ND = Corrected.getFoundDecl())
335*67e74705SXin Li         Found.addDecl(ND);
336*67e74705SXin Li       FilterAcceptableTemplateNames(Found);
337*67e74705SXin Li       if (!Found.empty()) {
338*67e74705SXin Li         if (LookupCtx) {
339*67e74705SXin Li           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
340*67e74705SXin Li           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
341*67e74705SXin Li                                   Name.getAsString() == CorrectedStr;
342*67e74705SXin Li           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
343*67e74705SXin Li                                     << Name << LookupCtx << DroppedSpecifier
344*67e74705SXin Li                                     << SS.getRange());
345*67e74705SXin Li         } else {
346*67e74705SXin Li           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
347*67e74705SXin Li         }
348*67e74705SXin Li       }
349*67e74705SXin Li     } else {
350*67e74705SXin Li       Found.setLookupName(Name);
351*67e74705SXin Li     }
352*67e74705SXin Li   }
353*67e74705SXin Li 
354*67e74705SXin Li   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
355*67e74705SXin Li   if (Found.empty()) {
356*67e74705SXin Li     if (isDependent)
357*67e74705SXin Li       MemberOfUnknownSpecialization = true;
358*67e74705SXin Li     return;
359*67e74705SXin Li   }
360*67e74705SXin Li 
361*67e74705SXin Li   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
362*67e74705SXin Li       !getLangOpts().CPlusPlus11) {
363*67e74705SXin Li     // C++03 [basic.lookup.classref]p1:
364*67e74705SXin Li     //   [...] If the lookup in the class of the object expression finds a
365*67e74705SXin Li     //   template, the name is also looked up in the context of the entire
366*67e74705SXin Li     //   postfix-expression and [...]
367*67e74705SXin Li     //
368*67e74705SXin Li     // Note: C++11 does not perform this second lookup.
369*67e74705SXin Li     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
370*67e74705SXin Li                             LookupOrdinaryName);
371*67e74705SXin Li     LookupName(FoundOuter, S);
372*67e74705SXin Li     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
373*67e74705SXin Li 
374*67e74705SXin Li     if (FoundOuter.empty()) {
375*67e74705SXin Li       //   - if the name is not found, the name found in the class of the
376*67e74705SXin Li       //     object expression is used, otherwise
377*67e74705SXin Li     } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
378*67e74705SXin Li                FoundOuter.isAmbiguous()) {
379*67e74705SXin Li       //   - if the name is found in the context of the entire
380*67e74705SXin Li       //     postfix-expression and does not name a class template, the name
381*67e74705SXin Li       //     found in the class of the object expression is used, otherwise
382*67e74705SXin Li       FoundOuter.clear();
383*67e74705SXin Li     } else if (!Found.isSuppressingDiagnostics()) {
384*67e74705SXin Li       //   - if the name found is a class template, it must refer to the same
385*67e74705SXin Li       //     entity as the one found in the class of the object expression,
386*67e74705SXin Li       //     otherwise the program is ill-formed.
387*67e74705SXin Li       if (!Found.isSingleResult() ||
388*67e74705SXin Li           Found.getFoundDecl()->getCanonicalDecl()
389*67e74705SXin Li             != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
390*67e74705SXin Li         Diag(Found.getNameLoc(),
391*67e74705SXin Li              diag::ext_nested_name_member_ref_lookup_ambiguous)
392*67e74705SXin Li           << Found.getLookupName()
393*67e74705SXin Li           << ObjectType;
394*67e74705SXin Li         Diag(Found.getRepresentativeDecl()->getLocation(),
395*67e74705SXin Li              diag::note_ambig_member_ref_object_type)
396*67e74705SXin Li           << ObjectType;
397*67e74705SXin Li         Diag(FoundOuter.getFoundDecl()->getLocation(),
398*67e74705SXin Li              diag::note_ambig_member_ref_scope);
399*67e74705SXin Li 
400*67e74705SXin Li         // Recover by taking the template that we found in the object
401*67e74705SXin Li         // expression's type.
402*67e74705SXin Li       }
403*67e74705SXin Li     }
404*67e74705SXin Li   }
405*67e74705SXin Li }
406*67e74705SXin Li 
407*67e74705SXin Li /// ActOnDependentIdExpression - Handle a dependent id-expression that
408*67e74705SXin Li /// was just parsed.  This is only possible with an explicit scope
409*67e74705SXin Li /// specifier naming a dependent type.
410*67e74705SXin Li ExprResult
ActOnDependentIdExpression(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,bool isAddressOfOperand,const TemplateArgumentListInfo * TemplateArgs)411*67e74705SXin Li Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
412*67e74705SXin Li                                  SourceLocation TemplateKWLoc,
413*67e74705SXin Li                                  const DeclarationNameInfo &NameInfo,
414*67e74705SXin Li                                  bool isAddressOfOperand,
415*67e74705SXin Li                            const TemplateArgumentListInfo *TemplateArgs) {
416*67e74705SXin Li   DeclContext *DC = getFunctionLevelDeclContext();
417*67e74705SXin Li 
418*67e74705SXin Li   // C++11 [expr.prim.general]p12:
419*67e74705SXin Li   //   An id-expression that denotes a non-static data member or non-static
420*67e74705SXin Li   //   member function of a class can only be used:
421*67e74705SXin Li   //   (...)
422*67e74705SXin Li   //   - if that id-expression denotes a non-static data member and it
423*67e74705SXin Li   //     appears in an unevaluated operand.
424*67e74705SXin Li   //
425*67e74705SXin Li   // If this might be the case, form a DependentScopeDeclRefExpr instead of a
426*67e74705SXin Li   // CXXDependentScopeMemberExpr. The former can instantiate to either
427*67e74705SXin Li   // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
428*67e74705SXin Li   // always a MemberExpr.
429*67e74705SXin Li   bool MightBeCxx11UnevalField =
430*67e74705SXin Li       getLangOpts().CPlusPlus11 && isUnevaluatedContext();
431*67e74705SXin Li 
432*67e74705SXin Li   if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
433*67e74705SXin Li       isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
434*67e74705SXin Li     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
435*67e74705SXin Li 
436*67e74705SXin Li     // Since the 'this' expression is synthesized, we don't need to
437*67e74705SXin Li     // perform the double-lookup check.
438*67e74705SXin Li     NamedDecl *FirstQualifierInScope = nullptr;
439*67e74705SXin Li 
440*67e74705SXin Li     return CXXDependentScopeMemberExpr::Create(
441*67e74705SXin Li         Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
442*67e74705SXin Li         /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
443*67e74705SXin Li         FirstQualifierInScope, NameInfo, TemplateArgs);
444*67e74705SXin Li   }
445*67e74705SXin Li 
446*67e74705SXin Li   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
447*67e74705SXin Li }
448*67e74705SXin Li 
449*67e74705SXin Li ExprResult
BuildDependentDeclRefExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)450*67e74705SXin Li Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
451*67e74705SXin Li                                 SourceLocation TemplateKWLoc,
452*67e74705SXin Li                                 const DeclarationNameInfo &NameInfo,
453*67e74705SXin Li                                 const TemplateArgumentListInfo *TemplateArgs) {
454*67e74705SXin Li   return DependentScopeDeclRefExpr::Create(
455*67e74705SXin Li       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
456*67e74705SXin Li       TemplateArgs);
457*67e74705SXin Li }
458*67e74705SXin Li 
459*67e74705SXin Li /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
460*67e74705SXin Li /// that the template parameter 'PrevDecl' is being shadowed by a new
461*67e74705SXin Li /// declaration at location Loc. Returns true to indicate that this is
462*67e74705SXin Li /// an error, and false otherwise.
DiagnoseTemplateParameterShadow(SourceLocation Loc,Decl * PrevDecl)463*67e74705SXin Li void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
464*67e74705SXin Li   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
465*67e74705SXin Li 
466*67e74705SXin Li   // Microsoft Visual C++ permits template parameters to be shadowed.
467*67e74705SXin Li   if (getLangOpts().MicrosoftExt)
468*67e74705SXin Li     return;
469*67e74705SXin Li 
470*67e74705SXin Li   // C++ [temp.local]p4:
471*67e74705SXin Li   //   A template-parameter shall not be redeclared within its
472*67e74705SXin Li   //   scope (including nested scopes).
473*67e74705SXin Li   Diag(Loc, diag::err_template_param_shadow)
474*67e74705SXin Li     << cast<NamedDecl>(PrevDecl)->getDeclName();
475*67e74705SXin Li   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
476*67e74705SXin Li }
477*67e74705SXin Li 
478*67e74705SXin Li /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
479*67e74705SXin Li /// the parameter D to reference the templated declaration and return a pointer
480*67e74705SXin Li /// to the template declaration. Otherwise, do nothing to D and return null.
AdjustDeclIfTemplate(Decl * & D)481*67e74705SXin Li TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
482*67e74705SXin Li   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
483*67e74705SXin Li     D = Temp->getTemplatedDecl();
484*67e74705SXin Li     return Temp;
485*67e74705SXin Li   }
486*67e74705SXin Li   return nullptr;
487*67e74705SXin Li }
488*67e74705SXin Li 
getTemplatePackExpansion(SourceLocation EllipsisLoc) const489*67e74705SXin Li ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
490*67e74705SXin Li                                              SourceLocation EllipsisLoc) const {
491*67e74705SXin Li   assert(Kind == Template &&
492*67e74705SXin Li          "Only template template arguments can be pack expansions here");
493*67e74705SXin Li   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
494*67e74705SXin Li          "Template template argument pack expansion without packs");
495*67e74705SXin Li   ParsedTemplateArgument Result(*this);
496*67e74705SXin Li   Result.EllipsisLoc = EllipsisLoc;
497*67e74705SXin Li   return Result;
498*67e74705SXin Li }
499*67e74705SXin Li 
translateTemplateArgument(Sema & SemaRef,const ParsedTemplateArgument & Arg)500*67e74705SXin Li static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
501*67e74705SXin Li                                             const ParsedTemplateArgument &Arg) {
502*67e74705SXin Li 
503*67e74705SXin Li   switch (Arg.getKind()) {
504*67e74705SXin Li   case ParsedTemplateArgument::Type: {
505*67e74705SXin Li     TypeSourceInfo *DI;
506*67e74705SXin Li     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
507*67e74705SXin Li     if (!DI)
508*67e74705SXin Li       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
509*67e74705SXin Li     return TemplateArgumentLoc(TemplateArgument(T), DI);
510*67e74705SXin Li   }
511*67e74705SXin Li 
512*67e74705SXin Li   case ParsedTemplateArgument::NonType: {
513*67e74705SXin Li     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
514*67e74705SXin Li     return TemplateArgumentLoc(TemplateArgument(E), E);
515*67e74705SXin Li   }
516*67e74705SXin Li 
517*67e74705SXin Li   case ParsedTemplateArgument::Template: {
518*67e74705SXin Li     TemplateName Template = Arg.getAsTemplate().get();
519*67e74705SXin Li     TemplateArgument TArg;
520*67e74705SXin Li     if (Arg.getEllipsisLoc().isValid())
521*67e74705SXin Li       TArg = TemplateArgument(Template, Optional<unsigned int>());
522*67e74705SXin Li     else
523*67e74705SXin Li       TArg = Template;
524*67e74705SXin Li     return TemplateArgumentLoc(TArg,
525*67e74705SXin Li                                Arg.getScopeSpec().getWithLocInContext(
526*67e74705SXin Li                                                               SemaRef.Context),
527*67e74705SXin Li                                Arg.getLocation(),
528*67e74705SXin Li                                Arg.getEllipsisLoc());
529*67e74705SXin Li   }
530*67e74705SXin Li   }
531*67e74705SXin Li 
532*67e74705SXin Li   llvm_unreachable("Unhandled parsed template argument");
533*67e74705SXin Li }
534*67e74705SXin Li 
535*67e74705SXin Li /// \brief Translates template arguments as provided by the parser
536*67e74705SXin Li /// into template arguments used by semantic analysis.
translateTemplateArguments(const ASTTemplateArgsPtr & TemplateArgsIn,TemplateArgumentListInfo & TemplateArgs)537*67e74705SXin Li void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
538*67e74705SXin Li                                       TemplateArgumentListInfo &TemplateArgs) {
539*67e74705SXin Li  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
540*67e74705SXin Li    TemplateArgs.addArgument(translateTemplateArgument(*this,
541*67e74705SXin Li                                                       TemplateArgsIn[I]));
542*67e74705SXin Li }
543*67e74705SXin Li 
maybeDiagnoseTemplateParameterShadow(Sema & SemaRef,Scope * S,SourceLocation Loc,IdentifierInfo * Name)544*67e74705SXin Li static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
545*67e74705SXin Li                                                  SourceLocation Loc,
546*67e74705SXin Li                                                  IdentifierInfo *Name) {
547*67e74705SXin Li   NamedDecl *PrevDecl = SemaRef.LookupSingleName(
548*67e74705SXin Li       S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
549*67e74705SXin Li   if (PrevDecl && PrevDecl->isTemplateParameter())
550*67e74705SXin Li     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
551*67e74705SXin Li }
552*67e74705SXin Li 
553*67e74705SXin Li /// ActOnTypeParameter - Called when a C++ template type parameter
554*67e74705SXin Li /// (e.g., "typename T") has been parsed. Typename specifies whether
555*67e74705SXin Li /// the keyword "typename" was used to declare the type parameter
556*67e74705SXin Li /// (otherwise, "class" was used), and KeyLoc is the location of the
557*67e74705SXin Li /// "class" or "typename" keyword. ParamName is the name of the
558*67e74705SXin Li /// parameter (NULL indicates an unnamed template parameter) and
559*67e74705SXin Li /// ParamNameLoc is the location of the parameter name (if any).
560*67e74705SXin Li /// If the type parameter has a default argument, it will be added
561*67e74705SXin Li /// later via ActOnTypeParameterDefault.
ActOnTypeParameter(Scope * S,bool Typename,SourceLocation EllipsisLoc,SourceLocation KeyLoc,IdentifierInfo * ParamName,SourceLocation ParamNameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedType DefaultArg)562*67e74705SXin Li Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
563*67e74705SXin Li                                SourceLocation EllipsisLoc,
564*67e74705SXin Li                                SourceLocation KeyLoc,
565*67e74705SXin Li                                IdentifierInfo *ParamName,
566*67e74705SXin Li                                SourceLocation ParamNameLoc,
567*67e74705SXin Li                                unsigned Depth, unsigned Position,
568*67e74705SXin Li                                SourceLocation EqualLoc,
569*67e74705SXin Li                                ParsedType DefaultArg) {
570*67e74705SXin Li   assert(S->isTemplateParamScope() &&
571*67e74705SXin Li          "Template type parameter not in template parameter scope!");
572*67e74705SXin Li 
573*67e74705SXin Li   SourceLocation Loc = ParamNameLoc;
574*67e74705SXin Li   if (!ParamName)
575*67e74705SXin Li     Loc = KeyLoc;
576*67e74705SXin Li 
577*67e74705SXin Li   bool IsParameterPack = EllipsisLoc.isValid();
578*67e74705SXin Li   TemplateTypeParmDecl *Param
579*67e74705SXin Li     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
580*67e74705SXin Li                                    KeyLoc, Loc, Depth, Position, ParamName,
581*67e74705SXin Li                                    Typename, IsParameterPack);
582*67e74705SXin Li   Param->setAccess(AS_public);
583*67e74705SXin Li 
584*67e74705SXin Li   if (ParamName) {
585*67e74705SXin Li     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
586*67e74705SXin Li 
587*67e74705SXin Li     // Add the template parameter into the current scope.
588*67e74705SXin Li     S->AddDecl(Param);
589*67e74705SXin Li     IdResolver.AddDecl(Param);
590*67e74705SXin Li   }
591*67e74705SXin Li 
592*67e74705SXin Li   // C++0x [temp.param]p9:
593*67e74705SXin Li   //   A default template-argument may be specified for any kind of
594*67e74705SXin Li   //   template-parameter that is not a template parameter pack.
595*67e74705SXin Li   if (DefaultArg && IsParameterPack) {
596*67e74705SXin Li     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
597*67e74705SXin Li     DefaultArg = nullptr;
598*67e74705SXin Li   }
599*67e74705SXin Li 
600*67e74705SXin Li   // Handle the default argument, if provided.
601*67e74705SXin Li   if (DefaultArg) {
602*67e74705SXin Li     TypeSourceInfo *DefaultTInfo;
603*67e74705SXin Li     GetTypeFromParser(DefaultArg, &DefaultTInfo);
604*67e74705SXin Li 
605*67e74705SXin Li     assert(DefaultTInfo && "expected source information for type");
606*67e74705SXin Li 
607*67e74705SXin Li     // Check for unexpanded parameter packs.
608*67e74705SXin Li     if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
609*67e74705SXin Li                                         UPPC_DefaultArgument))
610*67e74705SXin Li       return Param;
611*67e74705SXin Li 
612*67e74705SXin Li     // Check the template argument itself.
613*67e74705SXin Li     if (CheckTemplateArgument(Param, DefaultTInfo)) {
614*67e74705SXin Li       Param->setInvalidDecl();
615*67e74705SXin Li       return Param;
616*67e74705SXin Li     }
617*67e74705SXin Li 
618*67e74705SXin Li     Param->setDefaultArgument(DefaultTInfo);
619*67e74705SXin Li   }
620*67e74705SXin Li 
621*67e74705SXin Li   return Param;
622*67e74705SXin Li }
623*67e74705SXin Li 
624*67e74705SXin Li /// \brief Check that the type of a non-type template parameter is
625*67e74705SXin Li /// well-formed.
626*67e74705SXin Li ///
627*67e74705SXin Li /// \returns the (possibly-promoted) parameter type if valid;
628*67e74705SXin Li /// otherwise, produces a diagnostic and returns a NULL type.
629*67e74705SXin Li QualType
CheckNonTypeTemplateParameterType(QualType T,SourceLocation Loc)630*67e74705SXin Li Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
631*67e74705SXin Li   // We don't allow variably-modified types as the type of non-type template
632*67e74705SXin Li   // parameters.
633*67e74705SXin Li   if (T->isVariablyModifiedType()) {
634*67e74705SXin Li     Diag(Loc, diag::err_variably_modified_nontype_template_param)
635*67e74705SXin Li       << T;
636*67e74705SXin Li     return QualType();
637*67e74705SXin Li   }
638*67e74705SXin Li 
639*67e74705SXin Li   // C++ [temp.param]p4:
640*67e74705SXin Li   //
641*67e74705SXin Li   // A non-type template-parameter shall have one of the following
642*67e74705SXin Li   // (optionally cv-qualified) types:
643*67e74705SXin Li   //
644*67e74705SXin Li   //       -- integral or enumeration type,
645*67e74705SXin Li   if (T->isIntegralOrEnumerationType() ||
646*67e74705SXin Li       //   -- pointer to object or pointer to function,
647*67e74705SXin Li       T->isPointerType() ||
648*67e74705SXin Li       //   -- reference to object or reference to function,
649*67e74705SXin Li       T->isReferenceType() ||
650*67e74705SXin Li       //   -- pointer to member,
651*67e74705SXin Li       T->isMemberPointerType() ||
652*67e74705SXin Li       //   -- std::nullptr_t.
653*67e74705SXin Li       T->isNullPtrType() ||
654*67e74705SXin Li       // If T is a dependent type, we can't do the check now, so we
655*67e74705SXin Li       // assume that it is well-formed.
656*67e74705SXin Li       T->isDependentType()) {
657*67e74705SXin Li     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
658*67e74705SXin Li     // are ignored when determining its type.
659*67e74705SXin Li     return T.getUnqualifiedType();
660*67e74705SXin Li   }
661*67e74705SXin Li 
662*67e74705SXin Li   // C++ [temp.param]p8:
663*67e74705SXin Li   //
664*67e74705SXin Li   //   A non-type template-parameter of type "array of T" or
665*67e74705SXin Li   //   "function returning T" is adjusted to be of type "pointer to
666*67e74705SXin Li   //   T" or "pointer to function returning T", respectively.
667*67e74705SXin Li   else if (T->isArrayType() || T->isFunctionType())
668*67e74705SXin Li     return Context.getDecayedType(T);
669*67e74705SXin Li 
670*67e74705SXin Li   Diag(Loc, diag::err_template_nontype_parm_bad_type)
671*67e74705SXin Li     << T;
672*67e74705SXin Li 
673*67e74705SXin Li   return QualType();
674*67e74705SXin Li }
675*67e74705SXin Li 
ActOnNonTypeTemplateParameter(Scope * S,Declarator & D,unsigned Depth,unsigned Position,SourceLocation EqualLoc,Expr * Default)676*67e74705SXin Li Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
677*67e74705SXin Li                                           unsigned Depth,
678*67e74705SXin Li                                           unsigned Position,
679*67e74705SXin Li                                           SourceLocation EqualLoc,
680*67e74705SXin Li                                           Expr *Default) {
681*67e74705SXin Li   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
682*67e74705SXin Li   QualType T = TInfo->getType();
683*67e74705SXin Li 
684*67e74705SXin Li   assert(S->isTemplateParamScope() &&
685*67e74705SXin Li          "Non-type template parameter not in template parameter scope!");
686*67e74705SXin Li   bool Invalid = false;
687*67e74705SXin Li 
688*67e74705SXin Li   T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
689*67e74705SXin Li   if (T.isNull()) {
690*67e74705SXin Li     T = Context.IntTy; // Recover with an 'int' type.
691*67e74705SXin Li     Invalid = true;
692*67e74705SXin Li   }
693*67e74705SXin Li 
694*67e74705SXin Li   IdentifierInfo *ParamName = D.getIdentifier();
695*67e74705SXin Li   bool IsParameterPack = D.hasEllipsis();
696*67e74705SXin Li   NonTypeTemplateParmDecl *Param
697*67e74705SXin Li     = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
698*67e74705SXin Li                                       D.getLocStart(),
699*67e74705SXin Li                                       D.getIdentifierLoc(),
700*67e74705SXin Li                                       Depth, Position, ParamName, T,
701*67e74705SXin Li                                       IsParameterPack, TInfo);
702*67e74705SXin Li   Param->setAccess(AS_public);
703*67e74705SXin Li 
704*67e74705SXin Li   if (Invalid)
705*67e74705SXin Li     Param->setInvalidDecl();
706*67e74705SXin Li 
707*67e74705SXin Li   if (ParamName) {
708*67e74705SXin Li     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
709*67e74705SXin Li                                          ParamName);
710*67e74705SXin Li 
711*67e74705SXin Li     // Add the template parameter into the current scope.
712*67e74705SXin Li     S->AddDecl(Param);
713*67e74705SXin Li     IdResolver.AddDecl(Param);
714*67e74705SXin Li   }
715*67e74705SXin Li 
716*67e74705SXin Li   // C++0x [temp.param]p9:
717*67e74705SXin Li   //   A default template-argument may be specified for any kind of
718*67e74705SXin Li   //   template-parameter that is not a template parameter pack.
719*67e74705SXin Li   if (Default && IsParameterPack) {
720*67e74705SXin Li     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
721*67e74705SXin Li     Default = nullptr;
722*67e74705SXin Li   }
723*67e74705SXin Li 
724*67e74705SXin Li   // Check the well-formedness of the default template argument, if provided.
725*67e74705SXin Li   if (Default) {
726*67e74705SXin Li     // Check for unexpanded parameter packs.
727*67e74705SXin Li     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
728*67e74705SXin Li       return Param;
729*67e74705SXin Li 
730*67e74705SXin Li     TemplateArgument Converted;
731*67e74705SXin Li     ExprResult DefaultRes =
732*67e74705SXin Li         CheckTemplateArgument(Param, Param->getType(), Default, Converted);
733*67e74705SXin Li     if (DefaultRes.isInvalid()) {
734*67e74705SXin Li       Param->setInvalidDecl();
735*67e74705SXin Li       return Param;
736*67e74705SXin Li     }
737*67e74705SXin Li     Default = DefaultRes.get();
738*67e74705SXin Li 
739*67e74705SXin Li     Param->setDefaultArgument(Default);
740*67e74705SXin Li   }
741*67e74705SXin Li 
742*67e74705SXin Li   return Param;
743*67e74705SXin Li }
744*67e74705SXin Li 
745*67e74705SXin Li /// ActOnTemplateTemplateParameter - Called when a C++ template template
746*67e74705SXin Li /// parameter (e.g. T in template <template \<typename> class T> class array)
747*67e74705SXin Li /// has been parsed. S is the current scope.
ActOnTemplateTemplateParameter(Scope * S,SourceLocation TmpLoc,TemplateParameterList * Params,SourceLocation EllipsisLoc,IdentifierInfo * Name,SourceLocation NameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedTemplateArgument Default)748*67e74705SXin Li Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
749*67e74705SXin Li                                            SourceLocation TmpLoc,
750*67e74705SXin Li                                            TemplateParameterList *Params,
751*67e74705SXin Li                                            SourceLocation EllipsisLoc,
752*67e74705SXin Li                                            IdentifierInfo *Name,
753*67e74705SXin Li                                            SourceLocation NameLoc,
754*67e74705SXin Li                                            unsigned Depth,
755*67e74705SXin Li                                            unsigned Position,
756*67e74705SXin Li                                            SourceLocation EqualLoc,
757*67e74705SXin Li                                            ParsedTemplateArgument Default) {
758*67e74705SXin Li   assert(S->isTemplateParamScope() &&
759*67e74705SXin Li          "Template template parameter not in template parameter scope!");
760*67e74705SXin Li 
761*67e74705SXin Li   // Construct the parameter object.
762*67e74705SXin Li   bool IsParameterPack = EllipsisLoc.isValid();
763*67e74705SXin Li   TemplateTemplateParmDecl *Param =
764*67e74705SXin Li     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
765*67e74705SXin Li                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
766*67e74705SXin Li                                      Depth, Position, IsParameterPack,
767*67e74705SXin Li                                      Name, Params);
768*67e74705SXin Li   Param->setAccess(AS_public);
769*67e74705SXin Li 
770*67e74705SXin Li   // If the template template parameter has a name, then link the identifier
771*67e74705SXin Li   // into the scope and lookup mechanisms.
772*67e74705SXin Li   if (Name) {
773*67e74705SXin Li     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
774*67e74705SXin Li 
775*67e74705SXin Li     S->AddDecl(Param);
776*67e74705SXin Li     IdResolver.AddDecl(Param);
777*67e74705SXin Li   }
778*67e74705SXin Li 
779*67e74705SXin Li   if (Params->size() == 0) {
780*67e74705SXin Li     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
781*67e74705SXin Li     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
782*67e74705SXin Li     Param->setInvalidDecl();
783*67e74705SXin Li   }
784*67e74705SXin Li 
785*67e74705SXin Li   // C++0x [temp.param]p9:
786*67e74705SXin Li   //   A default template-argument may be specified for any kind of
787*67e74705SXin Li   //   template-parameter that is not a template parameter pack.
788*67e74705SXin Li   if (IsParameterPack && !Default.isInvalid()) {
789*67e74705SXin Li     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
790*67e74705SXin Li     Default = ParsedTemplateArgument();
791*67e74705SXin Li   }
792*67e74705SXin Li 
793*67e74705SXin Li   if (!Default.isInvalid()) {
794*67e74705SXin Li     // Check only that we have a template template argument. We don't want to
795*67e74705SXin Li     // try to check well-formedness now, because our template template parameter
796*67e74705SXin Li     // might have dependent types in its template parameters, which we wouldn't
797*67e74705SXin Li     // be able to match now.
798*67e74705SXin Li     //
799*67e74705SXin Li     // If none of the template template parameter's template arguments mention
800*67e74705SXin Li     // other template parameters, we could actually perform more checking here.
801*67e74705SXin Li     // However, it isn't worth doing.
802*67e74705SXin Li     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
803*67e74705SXin Li     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
804*67e74705SXin Li       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
805*67e74705SXin Li         << DefaultArg.getSourceRange();
806*67e74705SXin Li       return Param;
807*67e74705SXin Li     }
808*67e74705SXin Li 
809*67e74705SXin Li     // Check for unexpanded parameter packs.
810*67e74705SXin Li     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
811*67e74705SXin Li                                         DefaultArg.getArgument().getAsTemplate(),
812*67e74705SXin Li                                         UPPC_DefaultArgument))
813*67e74705SXin Li       return Param;
814*67e74705SXin Li 
815*67e74705SXin Li     Param->setDefaultArgument(Context, DefaultArg);
816*67e74705SXin Li   }
817*67e74705SXin Li 
818*67e74705SXin Li   return Param;
819*67e74705SXin Li }
820*67e74705SXin Li 
821*67e74705SXin Li /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
822*67e74705SXin Li /// constrained by RequiresClause, that contains the template parameters in
823*67e74705SXin Li /// Params.
824*67e74705SXin Li TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,SourceLocation ExportLoc,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ArrayRef<Decl * > Params,SourceLocation RAngleLoc,Expr * RequiresClause)825*67e74705SXin Li Sema::ActOnTemplateParameterList(unsigned Depth,
826*67e74705SXin Li                                  SourceLocation ExportLoc,
827*67e74705SXin Li                                  SourceLocation TemplateLoc,
828*67e74705SXin Li                                  SourceLocation LAngleLoc,
829*67e74705SXin Li                                  ArrayRef<Decl *> Params,
830*67e74705SXin Li                                  SourceLocation RAngleLoc,
831*67e74705SXin Li                                  Expr *RequiresClause) {
832*67e74705SXin Li   if (ExportLoc.isValid())
833*67e74705SXin Li     Diag(ExportLoc, diag::warn_template_export_unsupported);
834*67e74705SXin Li 
835*67e74705SXin Li   // FIXME: store RequiresClause
836*67e74705SXin Li   return TemplateParameterList::Create(
837*67e74705SXin Li       Context, TemplateLoc, LAngleLoc,
838*67e74705SXin Li       llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
839*67e74705SXin Li       RAngleLoc);
840*67e74705SXin Li }
841*67e74705SXin Li 
SetNestedNameSpecifier(TagDecl * T,const CXXScopeSpec & SS)842*67e74705SXin Li static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
843*67e74705SXin Li   if (SS.isSet())
844*67e74705SXin Li     T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
845*67e74705SXin Li }
846*67e74705SXin Li 
847*67e74705SXin Li DeclResult
CheckClassTemplate(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,TemplateParameterList * TemplateParams,AccessSpecifier AS,SourceLocation ModulePrivateLoc,SourceLocation FriendLoc,unsigned NumOuterTemplateParamLists,TemplateParameterList ** OuterTemplateParamLists,SkipBodyInfo * SkipBody)848*67e74705SXin Li Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
849*67e74705SXin Li                          SourceLocation KWLoc, CXXScopeSpec &SS,
850*67e74705SXin Li                          IdentifierInfo *Name, SourceLocation NameLoc,
851*67e74705SXin Li                          AttributeList *Attr,
852*67e74705SXin Li                          TemplateParameterList *TemplateParams,
853*67e74705SXin Li                          AccessSpecifier AS, SourceLocation ModulePrivateLoc,
854*67e74705SXin Li                          SourceLocation FriendLoc,
855*67e74705SXin Li                          unsigned NumOuterTemplateParamLists,
856*67e74705SXin Li                          TemplateParameterList** OuterTemplateParamLists,
857*67e74705SXin Li                          SkipBodyInfo *SkipBody) {
858*67e74705SXin Li   assert(TemplateParams && TemplateParams->size() > 0 &&
859*67e74705SXin Li          "No template parameters");
860*67e74705SXin Li   assert(TUK != TUK_Reference && "Can only declare or define class templates");
861*67e74705SXin Li   bool Invalid = false;
862*67e74705SXin Li 
863*67e74705SXin Li   // Check that we can declare a template here.
864*67e74705SXin Li   if (CheckTemplateDeclScope(S, TemplateParams))
865*67e74705SXin Li     return true;
866*67e74705SXin Li 
867*67e74705SXin Li   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
868*67e74705SXin Li   assert(Kind != TTK_Enum && "can't build template of enumerated type");
869*67e74705SXin Li 
870*67e74705SXin Li   // There is no such thing as an unnamed class template.
871*67e74705SXin Li   if (!Name) {
872*67e74705SXin Li     Diag(KWLoc, diag::err_template_unnamed_class);
873*67e74705SXin Li     return true;
874*67e74705SXin Li   }
875*67e74705SXin Li 
876*67e74705SXin Li   // Find any previous declaration with this name. For a friend with no
877*67e74705SXin Li   // scope explicitly specified, we only look for tag declarations (per
878*67e74705SXin Li   // C++11 [basic.lookup.elab]p2).
879*67e74705SXin Li   DeclContext *SemanticContext;
880*67e74705SXin Li   LookupResult Previous(*this, Name, NameLoc,
881*67e74705SXin Li                         (SS.isEmpty() && TUK == TUK_Friend)
882*67e74705SXin Li                           ? LookupTagName : LookupOrdinaryName,
883*67e74705SXin Li                         ForRedeclaration);
884*67e74705SXin Li   if (SS.isNotEmpty() && !SS.isInvalid()) {
885*67e74705SXin Li     SemanticContext = computeDeclContext(SS, true);
886*67e74705SXin Li     if (!SemanticContext) {
887*67e74705SXin Li       // FIXME: Horrible, horrible hack! We can't currently represent this
888*67e74705SXin Li       // in the AST, and historically we have just ignored such friend
889*67e74705SXin Li       // class templates, so don't complain here.
890*67e74705SXin Li       Diag(NameLoc, TUK == TUK_Friend
891*67e74705SXin Li                         ? diag::warn_template_qualified_friend_ignored
892*67e74705SXin Li                         : diag::err_template_qualified_declarator_no_match)
893*67e74705SXin Li           << SS.getScopeRep() << SS.getRange();
894*67e74705SXin Li       return TUK != TUK_Friend;
895*67e74705SXin Li     }
896*67e74705SXin Li 
897*67e74705SXin Li     if (RequireCompleteDeclContext(SS, SemanticContext))
898*67e74705SXin Li       return true;
899*67e74705SXin Li 
900*67e74705SXin Li     // If we're adding a template to a dependent context, we may need to
901*67e74705SXin Li     // rebuilding some of the types used within the template parameter list,
902*67e74705SXin Li     // now that we know what the current instantiation is.
903*67e74705SXin Li     if (SemanticContext->isDependentContext()) {
904*67e74705SXin Li       ContextRAII SavedContext(*this, SemanticContext);
905*67e74705SXin Li       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
906*67e74705SXin Li         Invalid = true;
907*67e74705SXin Li     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
908*67e74705SXin Li       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
909*67e74705SXin Li 
910*67e74705SXin Li     LookupQualifiedName(Previous, SemanticContext);
911*67e74705SXin Li   } else {
912*67e74705SXin Li     SemanticContext = CurContext;
913*67e74705SXin Li 
914*67e74705SXin Li     // C++14 [class.mem]p14:
915*67e74705SXin Li     //   If T is the name of a class, then each of the following shall have a
916*67e74705SXin Li     //   name different from T:
917*67e74705SXin Li     //    -- every member template of class T
918*67e74705SXin Li     if (TUK != TUK_Friend &&
919*67e74705SXin Li         DiagnoseClassNameShadow(SemanticContext,
920*67e74705SXin Li                                 DeclarationNameInfo(Name, NameLoc)))
921*67e74705SXin Li       return true;
922*67e74705SXin Li 
923*67e74705SXin Li     LookupName(Previous, S);
924*67e74705SXin Li   }
925*67e74705SXin Li 
926*67e74705SXin Li   if (Previous.isAmbiguous())
927*67e74705SXin Li     return true;
928*67e74705SXin Li 
929*67e74705SXin Li   NamedDecl *PrevDecl = nullptr;
930*67e74705SXin Li   if (Previous.begin() != Previous.end())
931*67e74705SXin Li     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
932*67e74705SXin Li 
933*67e74705SXin Li   if (PrevDecl && PrevDecl->isTemplateParameter()) {
934*67e74705SXin Li     // Maybe we will complain about the shadowed template parameter.
935*67e74705SXin Li     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
936*67e74705SXin Li     // Just pretend that we didn't see the previous declaration.
937*67e74705SXin Li     PrevDecl = nullptr;
938*67e74705SXin Li   }
939*67e74705SXin Li 
940*67e74705SXin Li   // If there is a previous declaration with the same name, check
941*67e74705SXin Li   // whether this is a valid redeclaration.
942*67e74705SXin Li   ClassTemplateDecl *PrevClassTemplate
943*67e74705SXin Li     = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
944*67e74705SXin Li 
945*67e74705SXin Li   // We may have found the injected-class-name of a class template,
946*67e74705SXin Li   // class template partial specialization, or class template specialization.
947*67e74705SXin Li   // In these cases, grab the template that is being defined or specialized.
948*67e74705SXin Li   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
949*67e74705SXin Li       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
950*67e74705SXin Li     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
951*67e74705SXin Li     PrevClassTemplate
952*67e74705SXin Li       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
953*67e74705SXin Li     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
954*67e74705SXin Li       PrevClassTemplate
955*67e74705SXin Li         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
956*67e74705SXin Li             ->getSpecializedTemplate();
957*67e74705SXin Li     }
958*67e74705SXin Li   }
959*67e74705SXin Li 
960*67e74705SXin Li   if (TUK == TUK_Friend) {
961*67e74705SXin Li     // C++ [namespace.memdef]p3:
962*67e74705SXin Li     //   [...] When looking for a prior declaration of a class or a function
963*67e74705SXin Li     //   declared as a friend, and when the name of the friend class or
964*67e74705SXin Li     //   function is neither a qualified name nor a template-id, scopes outside
965*67e74705SXin Li     //   the innermost enclosing namespace scope are not considered.
966*67e74705SXin Li     if (!SS.isSet()) {
967*67e74705SXin Li       DeclContext *OutermostContext = CurContext;
968*67e74705SXin Li       while (!OutermostContext->isFileContext())
969*67e74705SXin Li         OutermostContext = OutermostContext->getLookupParent();
970*67e74705SXin Li 
971*67e74705SXin Li       if (PrevDecl &&
972*67e74705SXin Li           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
973*67e74705SXin Li            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
974*67e74705SXin Li         SemanticContext = PrevDecl->getDeclContext();
975*67e74705SXin Li       } else {
976*67e74705SXin Li         // Declarations in outer scopes don't matter. However, the outermost
977*67e74705SXin Li         // context we computed is the semantic context for our new
978*67e74705SXin Li         // declaration.
979*67e74705SXin Li         PrevDecl = PrevClassTemplate = nullptr;
980*67e74705SXin Li         SemanticContext = OutermostContext;
981*67e74705SXin Li 
982*67e74705SXin Li         // Check that the chosen semantic context doesn't already contain a
983*67e74705SXin Li         // declaration of this name as a non-tag type.
984*67e74705SXin Li         Previous.clear(LookupOrdinaryName);
985*67e74705SXin Li         DeclContext *LookupContext = SemanticContext;
986*67e74705SXin Li         while (LookupContext->isTransparentContext())
987*67e74705SXin Li           LookupContext = LookupContext->getLookupParent();
988*67e74705SXin Li         LookupQualifiedName(Previous, LookupContext);
989*67e74705SXin Li 
990*67e74705SXin Li         if (Previous.isAmbiguous())
991*67e74705SXin Li           return true;
992*67e74705SXin Li 
993*67e74705SXin Li         if (Previous.begin() != Previous.end())
994*67e74705SXin Li           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
995*67e74705SXin Li       }
996*67e74705SXin Li     }
997*67e74705SXin Li   } else if (PrevDecl &&
998*67e74705SXin Li              !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
999*67e74705SXin Li                             S, SS.isValid()))
1000*67e74705SXin Li     PrevDecl = PrevClassTemplate = nullptr;
1001*67e74705SXin Li 
1002*67e74705SXin Li   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1003*67e74705SXin Li           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1004*67e74705SXin Li     if (SS.isEmpty() &&
1005*67e74705SXin Li         !(PrevClassTemplate &&
1006*67e74705SXin Li           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1007*67e74705SXin Li               SemanticContext->getRedeclContext()))) {
1008*67e74705SXin Li       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1009*67e74705SXin Li       Diag(Shadow->getTargetDecl()->getLocation(),
1010*67e74705SXin Li            diag::note_using_decl_target);
1011*67e74705SXin Li       Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1012*67e74705SXin Li       // Recover by ignoring the old declaration.
1013*67e74705SXin Li       PrevDecl = PrevClassTemplate = nullptr;
1014*67e74705SXin Li     }
1015*67e74705SXin Li   }
1016*67e74705SXin Li 
1017*67e74705SXin Li   if (PrevClassTemplate) {
1018*67e74705SXin Li     // Ensure that the template parameter lists are compatible. Skip this check
1019*67e74705SXin Li     // for a friend in a dependent context: the template parameter list itself
1020*67e74705SXin Li     // could be dependent.
1021*67e74705SXin Li     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1022*67e74705SXin Li         !TemplateParameterListsAreEqual(TemplateParams,
1023*67e74705SXin Li                                    PrevClassTemplate->getTemplateParameters(),
1024*67e74705SXin Li                                         /*Complain=*/true,
1025*67e74705SXin Li                                         TPL_TemplateMatch))
1026*67e74705SXin Li       return true;
1027*67e74705SXin Li 
1028*67e74705SXin Li     // C++ [temp.class]p4:
1029*67e74705SXin Li     //   In a redeclaration, partial specialization, explicit
1030*67e74705SXin Li     //   specialization or explicit instantiation of a class template,
1031*67e74705SXin Li     //   the class-key shall agree in kind with the original class
1032*67e74705SXin Li     //   template declaration (7.1.5.3).
1033*67e74705SXin Li     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1034*67e74705SXin Li     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1035*67e74705SXin Li                                       TUK == TUK_Definition,  KWLoc, Name)) {
1036*67e74705SXin Li       Diag(KWLoc, diag::err_use_with_wrong_tag)
1037*67e74705SXin Li         << Name
1038*67e74705SXin Li         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1039*67e74705SXin Li       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1040*67e74705SXin Li       Kind = PrevRecordDecl->getTagKind();
1041*67e74705SXin Li     }
1042*67e74705SXin Li 
1043*67e74705SXin Li     // Check for redefinition of this class template.
1044*67e74705SXin Li     if (TUK == TUK_Definition) {
1045*67e74705SXin Li       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1046*67e74705SXin Li         // If we have a prior definition that is not visible, treat this as
1047*67e74705SXin Li         // simply making that previous definition visible.
1048*67e74705SXin Li         NamedDecl *Hidden = nullptr;
1049*67e74705SXin Li         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1050*67e74705SXin Li           SkipBody->ShouldSkip = true;
1051*67e74705SXin Li           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1052*67e74705SXin Li           assert(Tmpl && "original definition of a class template is not a "
1053*67e74705SXin Li                          "class template?");
1054*67e74705SXin Li           makeMergedDefinitionVisible(Hidden, KWLoc);
1055*67e74705SXin Li           makeMergedDefinitionVisible(Tmpl, KWLoc);
1056*67e74705SXin Li           return Def;
1057*67e74705SXin Li         }
1058*67e74705SXin Li 
1059*67e74705SXin Li         Diag(NameLoc, diag::err_redefinition) << Name;
1060*67e74705SXin Li         Diag(Def->getLocation(), diag::note_previous_definition);
1061*67e74705SXin Li         // FIXME: Would it make sense to try to "forget" the previous
1062*67e74705SXin Li         // definition, as part of error recovery?
1063*67e74705SXin Li         return true;
1064*67e74705SXin Li       }
1065*67e74705SXin Li     }
1066*67e74705SXin Li   } else if (PrevDecl) {
1067*67e74705SXin Li     // C++ [temp]p5:
1068*67e74705SXin Li     //   A class template shall not have the same name as any other
1069*67e74705SXin Li     //   template, class, function, object, enumeration, enumerator,
1070*67e74705SXin Li     //   namespace, or type in the same scope (3.3), except as specified
1071*67e74705SXin Li     //   in (14.5.4).
1072*67e74705SXin Li     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1073*67e74705SXin Li     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1074*67e74705SXin Li     return true;
1075*67e74705SXin Li   }
1076*67e74705SXin Li 
1077*67e74705SXin Li   // Check the template parameter list of this declaration, possibly
1078*67e74705SXin Li   // merging in the template parameter list from the previous class
1079*67e74705SXin Li   // template declaration. Skip this check for a friend in a dependent
1080*67e74705SXin Li   // context, because the template parameter list might be dependent.
1081*67e74705SXin Li   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1082*67e74705SXin Li       CheckTemplateParameterList(
1083*67e74705SXin Li           TemplateParams,
1084*67e74705SXin Li           PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1085*67e74705SXin Li                             : nullptr,
1086*67e74705SXin Li           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1087*67e74705SXin Li            SemanticContext->isDependentContext())
1088*67e74705SXin Li               ? TPC_ClassTemplateMember
1089*67e74705SXin Li               : TUK == TUK_Friend ? TPC_FriendClassTemplate
1090*67e74705SXin Li                                   : TPC_ClassTemplate))
1091*67e74705SXin Li     Invalid = true;
1092*67e74705SXin Li 
1093*67e74705SXin Li   if (SS.isSet()) {
1094*67e74705SXin Li     // If the name of the template was qualified, we must be defining the
1095*67e74705SXin Li     // template out-of-line.
1096*67e74705SXin Li     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1097*67e74705SXin Li       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1098*67e74705SXin Li                                       : diag::err_member_decl_does_not_match)
1099*67e74705SXin Li         << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1100*67e74705SXin Li       Invalid = true;
1101*67e74705SXin Li     }
1102*67e74705SXin Li   }
1103*67e74705SXin Li 
1104*67e74705SXin Li   CXXRecordDecl *NewClass =
1105*67e74705SXin Li     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1106*67e74705SXin Li                           PrevClassTemplate?
1107*67e74705SXin Li                             PrevClassTemplate->getTemplatedDecl() : nullptr,
1108*67e74705SXin Li                           /*DelayTypeCreation=*/true);
1109*67e74705SXin Li   SetNestedNameSpecifier(NewClass, SS);
1110*67e74705SXin Li   if (NumOuterTemplateParamLists > 0)
1111*67e74705SXin Li     NewClass->setTemplateParameterListsInfo(
1112*67e74705SXin Li         Context, llvm::makeArrayRef(OuterTemplateParamLists,
1113*67e74705SXin Li                                     NumOuterTemplateParamLists));
1114*67e74705SXin Li 
1115*67e74705SXin Li   // Add alignment attributes if necessary; these attributes are checked when
1116*67e74705SXin Li   // the ASTContext lays out the structure.
1117*67e74705SXin Li   if (TUK == TUK_Definition) {
1118*67e74705SXin Li     AddAlignmentAttributesForRecord(NewClass);
1119*67e74705SXin Li     AddMsStructLayoutForRecord(NewClass);
1120*67e74705SXin Li   }
1121*67e74705SXin Li 
1122*67e74705SXin Li   ClassTemplateDecl *NewTemplate
1123*67e74705SXin Li     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1124*67e74705SXin Li                                 DeclarationName(Name), TemplateParams,
1125*67e74705SXin Li                                 NewClass, PrevClassTemplate);
1126*67e74705SXin Li   NewClass->setDescribedClassTemplate(NewTemplate);
1127*67e74705SXin Li 
1128*67e74705SXin Li   if (ModulePrivateLoc.isValid())
1129*67e74705SXin Li     NewTemplate->setModulePrivate();
1130*67e74705SXin Li 
1131*67e74705SXin Li   // Build the type for the class template declaration now.
1132*67e74705SXin Li   QualType T = NewTemplate->getInjectedClassNameSpecialization();
1133*67e74705SXin Li   T = Context.getInjectedClassNameType(NewClass, T);
1134*67e74705SXin Li   assert(T->isDependentType() && "Class template type is not dependent?");
1135*67e74705SXin Li   (void)T;
1136*67e74705SXin Li 
1137*67e74705SXin Li   // If we are providing an explicit specialization of a member that is a
1138*67e74705SXin Li   // class template, make a note of that.
1139*67e74705SXin Li   if (PrevClassTemplate &&
1140*67e74705SXin Li       PrevClassTemplate->getInstantiatedFromMemberTemplate())
1141*67e74705SXin Li     PrevClassTemplate->setMemberSpecialization();
1142*67e74705SXin Li 
1143*67e74705SXin Li   // Set the access specifier.
1144*67e74705SXin Li   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1145*67e74705SXin Li     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1146*67e74705SXin Li 
1147*67e74705SXin Li   // Set the lexical context of these templates
1148*67e74705SXin Li   NewClass->setLexicalDeclContext(CurContext);
1149*67e74705SXin Li   NewTemplate->setLexicalDeclContext(CurContext);
1150*67e74705SXin Li 
1151*67e74705SXin Li   if (TUK == TUK_Definition)
1152*67e74705SXin Li     NewClass->startDefinition();
1153*67e74705SXin Li 
1154*67e74705SXin Li   if (Attr)
1155*67e74705SXin Li     ProcessDeclAttributeList(S, NewClass, Attr);
1156*67e74705SXin Li 
1157*67e74705SXin Li   if (PrevClassTemplate)
1158*67e74705SXin Li     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1159*67e74705SXin Li 
1160*67e74705SXin Li   AddPushedVisibilityAttribute(NewClass);
1161*67e74705SXin Li 
1162*67e74705SXin Li   if (TUK != TUK_Friend) {
1163*67e74705SXin Li     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1164*67e74705SXin Li     Scope *Outer = S;
1165*67e74705SXin Li     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1166*67e74705SXin Li       Outer = Outer->getParent();
1167*67e74705SXin Li     PushOnScopeChains(NewTemplate, Outer);
1168*67e74705SXin Li   } else {
1169*67e74705SXin Li     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1170*67e74705SXin Li       NewTemplate->setAccess(PrevClassTemplate->getAccess());
1171*67e74705SXin Li       NewClass->setAccess(PrevClassTemplate->getAccess());
1172*67e74705SXin Li     }
1173*67e74705SXin Li 
1174*67e74705SXin Li     NewTemplate->setObjectOfFriendDecl();
1175*67e74705SXin Li 
1176*67e74705SXin Li     // Friend templates are visible in fairly strange ways.
1177*67e74705SXin Li     if (!CurContext->isDependentContext()) {
1178*67e74705SXin Li       DeclContext *DC = SemanticContext->getRedeclContext();
1179*67e74705SXin Li       DC->makeDeclVisibleInContext(NewTemplate);
1180*67e74705SXin Li       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1181*67e74705SXin Li         PushOnScopeChains(NewTemplate, EnclosingScope,
1182*67e74705SXin Li                           /* AddToContext = */ false);
1183*67e74705SXin Li     }
1184*67e74705SXin Li 
1185*67e74705SXin Li     FriendDecl *Friend = FriendDecl::Create(
1186*67e74705SXin Li         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1187*67e74705SXin Li     Friend->setAccess(AS_public);
1188*67e74705SXin Li     CurContext->addDecl(Friend);
1189*67e74705SXin Li   }
1190*67e74705SXin Li 
1191*67e74705SXin Li   if (Invalid) {
1192*67e74705SXin Li     NewTemplate->setInvalidDecl();
1193*67e74705SXin Li     NewClass->setInvalidDecl();
1194*67e74705SXin Li   }
1195*67e74705SXin Li 
1196*67e74705SXin Li   ActOnDocumentableDecl(NewTemplate);
1197*67e74705SXin Li 
1198*67e74705SXin Li   return NewTemplate;
1199*67e74705SXin Li }
1200*67e74705SXin Li 
1201*67e74705SXin Li /// \brief Diagnose the presence of a default template argument on a
1202*67e74705SXin Li /// template parameter, which is ill-formed in certain contexts.
1203*67e74705SXin Li ///
1204*67e74705SXin Li /// \returns true if the default template argument should be dropped.
DiagnoseDefaultTemplateArgument(Sema & S,Sema::TemplateParamListContext TPC,SourceLocation ParamLoc,SourceRange DefArgRange)1205*67e74705SXin Li static bool DiagnoseDefaultTemplateArgument(Sema &S,
1206*67e74705SXin Li                                             Sema::TemplateParamListContext TPC,
1207*67e74705SXin Li                                             SourceLocation ParamLoc,
1208*67e74705SXin Li                                             SourceRange DefArgRange) {
1209*67e74705SXin Li   switch (TPC) {
1210*67e74705SXin Li   case Sema::TPC_ClassTemplate:
1211*67e74705SXin Li   case Sema::TPC_VarTemplate:
1212*67e74705SXin Li   case Sema::TPC_TypeAliasTemplate:
1213*67e74705SXin Li     return false;
1214*67e74705SXin Li 
1215*67e74705SXin Li   case Sema::TPC_FunctionTemplate:
1216*67e74705SXin Li   case Sema::TPC_FriendFunctionTemplateDefinition:
1217*67e74705SXin Li     // C++ [temp.param]p9:
1218*67e74705SXin Li     //   A default template-argument shall not be specified in a
1219*67e74705SXin Li     //   function template declaration or a function template
1220*67e74705SXin Li     //   definition [...]
1221*67e74705SXin Li     //   If a friend function template declaration specifies a default
1222*67e74705SXin Li     //   template-argument, that declaration shall be a definition and shall be
1223*67e74705SXin Li     //   the only declaration of the function template in the translation unit.
1224*67e74705SXin Li     // (C++98/03 doesn't have this wording; see DR226).
1225*67e74705SXin Li     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1226*67e74705SXin Li          diag::warn_cxx98_compat_template_parameter_default_in_function_template
1227*67e74705SXin Li            : diag::ext_template_parameter_default_in_function_template)
1228*67e74705SXin Li       << DefArgRange;
1229*67e74705SXin Li     return false;
1230*67e74705SXin Li 
1231*67e74705SXin Li   case Sema::TPC_ClassTemplateMember:
1232*67e74705SXin Li     // C++0x [temp.param]p9:
1233*67e74705SXin Li     //   A default template-argument shall not be specified in the
1234*67e74705SXin Li     //   template-parameter-lists of the definition of a member of a
1235*67e74705SXin Li     //   class template that appears outside of the member's class.
1236*67e74705SXin Li     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1237*67e74705SXin Li       << DefArgRange;
1238*67e74705SXin Li     return true;
1239*67e74705SXin Li 
1240*67e74705SXin Li   case Sema::TPC_FriendClassTemplate:
1241*67e74705SXin Li   case Sema::TPC_FriendFunctionTemplate:
1242*67e74705SXin Li     // C++ [temp.param]p9:
1243*67e74705SXin Li     //   A default template-argument shall not be specified in a
1244*67e74705SXin Li     //   friend template declaration.
1245*67e74705SXin Li     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1246*67e74705SXin Li       << DefArgRange;
1247*67e74705SXin Li     return true;
1248*67e74705SXin Li 
1249*67e74705SXin Li     // FIXME: C++0x [temp.param]p9 allows default template-arguments
1250*67e74705SXin Li     // for friend function templates if there is only a single
1251*67e74705SXin Li     // declaration (and it is a definition). Strange!
1252*67e74705SXin Li   }
1253*67e74705SXin Li 
1254*67e74705SXin Li   llvm_unreachable("Invalid TemplateParamListContext!");
1255*67e74705SXin Li }
1256*67e74705SXin Li 
1257*67e74705SXin Li /// \brief Check for unexpanded parameter packs within the template parameters
1258*67e74705SXin Li /// of a template template parameter, recursively.
DiagnoseUnexpandedParameterPacks(Sema & S,TemplateTemplateParmDecl * TTP)1259*67e74705SXin Li static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1260*67e74705SXin Li                                              TemplateTemplateParmDecl *TTP) {
1261*67e74705SXin Li   // A template template parameter which is a parameter pack is also a pack
1262*67e74705SXin Li   // expansion.
1263*67e74705SXin Li   if (TTP->isParameterPack())
1264*67e74705SXin Li     return false;
1265*67e74705SXin Li 
1266*67e74705SXin Li   TemplateParameterList *Params = TTP->getTemplateParameters();
1267*67e74705SXin Li   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1268*67e74705SXin Li     NamedDecl *P = Params->getParam(I);
1269*67e74705SXin Li     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1270*67e74705SXin Li       if (!NTTP->isParameterPack() &&
1271*67e74705SXin Li           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1272*67e74705SXin Li                                             NTTP->getTypeSourceInfo(),
1273*67e74705SXin Li                                       Sema::UPPC_NonTypeTemplateParameterType))
1274*67e74705SXin Li         return true;
1275*67e74705SXin Li 
1276*67e74705SXin Li       continue;
1277*67e74705SXin Li     }
1278*67e74705SXin Li 
1279*67e74705SXin Li     if (TemplateTemplateParmDecl *InnerTTP
1280*67e74705SXin Li                                         = dyn_cast<TemplateTemplateParmDecl>(P))
1281*67e74705SXin Li       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1282*67e74705SXin Li         return true;
1283*67e74705SXin Li   }
1284*67e74705SXin Li 
1285*67e74705SXin Li   return false;
1286*67e74705SXin Li }
1287*67e74705SXin Li 
1288*67e74705SXin Li /// \brief Checks the validity of a template parameter list, possibly
1289*67e74705SXin Li /// considering the template parameter list from a previous
1290*67e74705SXin Li /// declaration.
1291*67e74705SXin Li ///
1292*67e74705SXin Li /// If an "old" template parameter list is provided, it must be
1293*67e74705SXin Li /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1294*67e74705SXin Li /// template parameter list.
1295*67e74705SXin Li ///
1296*67e74705SXin Li /// \param NewParams Template parameter list for a new template
1297*67e74705SXin Li /// declaration. This template parameter list will be updated with any
1298*67e74705SXin Li /// default arguments that are carried through from the previous
1299*67e74705SXin Li /// template parameter list.
1300*67e74705SXin Li ///
1301*67e74705SXin Li /// \param OldParams If provided, template parameter list from a
1302*67e74705SXin Li /// previous declaration of the same template. Default template
1303*67e74705SXin Li /// arguments will be merged from the old template parameter list to
1304*67e74705SXin Li /// the new template parameter list.
1305*67e74705SXin Li ///
1306*67e74705SXin Li /// \param TPC Describes the context in which we are checking the given
1307*67e74705SXin Li /// template parameter list.
1308*67e74705SXin Li ///
1309*67e74705SXin Li /// \returns true if an error occurred, false otherwise.
CheckTemplateParameterList(TemplateParameterList * NewParams,TemplateParameterList * OldParams,TemplateParamListContext TPC)1310*67e74705SXin Li bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1311*67e74705SXin Li                                       TemplateParameterList *OldParams,
1312*67e74705SXin Li                                       TemplateParamListContext TPC) {
1313*67e74705SXin Li   bool Invalid = false;
1314*67e74705SXin Li 
1315*67e74705SXin Li   // C++ [temp.param]p10:
1316*67e74705SXin Li   //   The set of default template-arguments available for use with a
1317*67e74705SXin Li   //   template declaration or definition is obtained by merging the
1318*67e74705SXin Li   //   default arguments from the definition (if in scope) and all
1319*67e74705SXin Li   //   declarations in scope in the same way default function
1320*67e74705SXin Li   //   arguments are (8.3.6).
1321*67e74705SXin Li   bool SawDefaultArgument = false;
1322*67e74705SXin Li   SourceLocation PreviousDefaultArgLoc;
1323*67e74705SXin Li 
1324*67e74705SXin Li   // Dummy initialization to avoid warnings.
1325*67e74705SXin Li   TemplateParameterList::iterator OldParam = NewParams->end();
1326*67e74705SXin Li   if (OldParams)
1327*67e74705SXin Li     OldParam = OldParams->begin();
1328*67e74705SXin Li 
1329*67e74705SXin Li   bool RemoveDefaultArguments = false;
1330*67e74705SXin Li   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1331*67e74705SXin Li                                     NewParamEnd = NewParams->end();
1332*67e74705SXin Li        NewParam != NewParamEnd; ++NewParam) {
1333*67e74705SXin Li     // Variables used to diagnose redundant default arguments
1334*67e74705SXin Li     bool RedundantDefaultArg = false;
1335*67e74705SXin Li     SourceLocation OldDefaultLoc;
1336*67e74705SXin Li     SourceLocation NewDefaultLoc;
1337*67e74705SXin Li 
1338*67e74705SXin Li     // Variable used to diagnose missing default arguments
1339*67e74705SXin Li     bool MissingDefaultArg = false;
1340*67e74705SXin Li 
1341*67e74705SXin Li     // Variable used to diagnose non-final parameter packs
1342*67e74705SXin Li     bool SawParameterPack = false;
1343*67e74705SXin Li 
1344*67e74705SXin Li     if (TemplateTypeParmDecl *NewTypeParm
1345*67e74705SXin Li           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1346*67e74705SXin Li       // Check the presence of a default argument here.
1347*67e74705SXin Li       if (NewTypeParm->hasDefaultArgument() &&
1348*67e74705SXin Li           DiagnoseDefaultTemplateArgument(*this, TPC,
1349*67e74705SXin Li                                           NewTypeParm->getLocation(),
1350*67e74705SXin Li                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1351*67e74705SXin Li                                                        .getSourceRange()))
1352*67e74705SXin Li         NewTypeParm->removeDefaultArgument();
1353*67e74705SXin Li 
1354*67e74705SXin Li       // Merge default arguments for template type parameters.
1355*67e74705SXin Li       TemplateTypeParmDecl *OldTypeParm
1356*67e74705SXin Li           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1357*67e74705SXin Li       if (NewTypeParm->isParameterPack()) {
1358*67e74705SXin Li         assert(!NewTypeParm->hasDefaultArgument() &&
1359*67e74705SXin Li                "Parameter packs can't have a default argument!");
1360*67e74705SXin Li         SawParameterPack = true;
1361*67e74705SXin Li       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1362*67e74705SXin Li                  NewTypeParm->hasDefaultArgument()) {
1363*67e74705SXin Li         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1364*67e74705SXin Li         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1365*67e74705SXin Li         SawDefaultArgument = true;
1366*67e74705SXin Li         RedundantDefaultArg = true;
1367*67e74705SXin Li         PreviousDefaultArgLoc = NewDefaultLoc;
1368*67e74705SXin Li       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1369*67e74705SXin Li         // Merge the default argument from the old declaration to the
1370*67e74705SXin Li         // new declaration.
1371*67e74705SXin Li         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1372*67e74705SXin Li         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1373*67e74705SXin Li       } else if (NewTypeParm->hasDefaultArgument()) {
1374*67e74705SXin Li         SawDefaultArgument = true;
1375*67e74705SXin Li         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1376*67e74705SXin Li       } else if (SawDefaultArgument)
1377*67e74705SXin Li         MissingDefaultArg = true;
1378*67e74705SXin Li     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1379*67e74705SXin Li                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1380*67e74705SXin Li       // Check for unexpanded parameter packs.
1381*67e74705SXin Li       if (!NewNonTypeParm->isParameterPack() &&
1382*67e74705SXin Li           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1383*67e74705SXin Li                                           NewNonTypeParm->getTypeSourceInfo(),
1384*67e74705SXin Li                                           UPPC_NonTypeTemplateParameterType)) {
1385*67e74705SXin Li         Invalid = true;
1386*67e74705SXin Li         continue;
1387*67e74705SXin Li       }
1388*67e74705SXin Li 
1389*67e74705SXin Li       // Check the presence of a default argument here.
1390*67e74705SXin Li       if (NewNonTypeParm->hasDefaultArgument() &&
1391*67e74705SXin Li           DiagnoseDefaultTemplateArgument(*this, TPC,
1392*67e74705SXin Li                                           NewNonTypeParm->getLocation(),
1393*67e74705SXin Li                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1394*67e74705SXin Li         NewNonTypeParm->removeDefaultArgument();
1395*67e74705SXin Li       }
1396*67e74705SXin Li 
1397*67e74705SXin Li       // Merge default arguments for non-type template parameters
1398*67e74705SXin Li       NonTypeTemplateParmDecl *OldNonTypeParm
1399*67e74705SXin Li         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1400*67e74705SXin Li       if (NewNonTypeParm->isParameterPack()) {
1401*67e74705SXin Li         assert(!NewNonTypeParm->hasDefaultArgument() &&
1402*67e74705SXin Li                "Parameter packs can't have a default argument!");
1403*67e74705SXin Li         if (!NewNonTypeParm->isPackExpansion())
1404*67e74705SXin Li           SawParameterPack = true;
1405*67e74705SXin Li       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1406*67e74705SXin Li                  NewNonTypeParm->hasDefaultArgument()) {
1407*67e74705SXin Li         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1408*67e74705SXin Li         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1409*67e74705SXin Li         SawDefaultArgument = true;
1410*67e74705SXin Li         RedundantDefaultArg = true;
1411*67e74705SXin Li         PreviousDefaultArgLoc = NewDefaultLoc;
1412*67e74705SXin Li       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1413*67e74705SXin Li         // Merge the default argument from the old declaration to the
1414*67e74705SXin Li         // new declaration.
1415*67e74705SXin Li         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1416*67e74705SXin Li         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1417*67e74705SXin Li       } else if (NewNonTypeParm->hasDefaultArgument()) {
1418*67e74705SXin Li         SawDefaultArgument = true;
1419*67e74705SXin Li         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1420*67e74705SXin Li       } else if (SawDefaultArgument)
1421*67e74705SXin Li         MissingDefaultArg = true;
1422*67e74705SXin Li     } else {
1423*67e74705SXin Li       TemplateTemplateParmDecl *NewTemplateParm
1424*67e74705SXin Li         = cast<TemplateTemplateParmDecl>(*NewParam);
1425*67e74705SXin Li 
1426*67e74705SXin Li       // Check for unexpanded parameter packs, recursively.
1427*67e74705SXin Li       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1428*67e74705SXin Li         Invalid = true;
1429*67e74705SXin Li         continue;
1430*67e74705SXin Li       }
1431*67e74705SXin Li 
1432*67e74705SXin Li       // Check the presence of a default argument here.
1433*67e74705SXin Li       if (NewTemplateParm->hasDefaultArgument() &&
1434*67e74705SXin Li           DiagnoseDefaultTemplateArgument(*this, TPC,
1435*67e74705SXin Li                                           NewTemplateParm->getLocation(),
1436*67e74705SXin Li                      NewTemplateParm->getDefaultArgument().getSourceRange()))
1437*67e74705SXin Li         NewTemplateParm->removeDefaultArgument();
1438*67e74705SXin Li 
1439*67e74705SXin Li       // Merge default arguments for template template parameters
1440*67e74705SXin Li       TemplateTemplateParmDecl *OldTemplateParm
1441*67e74705SXin Li         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1442*67e74705SXin Li       if (NewTemplateParm->isParameterPack()) {
1443*67e74705SXin Li         assert(!NewTemplateParm->hasDefaultArgument() &&
1444*67e74705SXin Li                "Parameter packs can't have a default argument!");
1445*67e74705SXin Li         if (!NewTemplateParm->isPackExpansion())
1446*67e74705SXin Li           SawParameterPack = true;
1447*67e74705SXin Li       } else if (OldTemplateParm &&
1448*67e74705SXin Li                  hasVisibleDefaultArgument(OldTemplateParm) &&
1449*67e74705SXin Li                  NewTemplateParm->hasDefaultArgument()) {
1450*67e74705SXin Li         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1451*67e74705SXin Li         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1452*67e74705SXin Li         SawDefaultArgument = true;
1453*67e74705SXin Li         RedundantDefaultArg = true;
1454*67e74705SXin Li         PreviousDefaultArgLoc = NewDefaultLoc;
1455*67e74705SXin Li       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1456*67e74705SXin Li         // Merge the default argument from the old declaration to the
1457*67e74705SXin Li         // new declaration.
1458*67e74705SXin Li         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
1459*67e74705SXin Li         PreviousDefaultArgLoc
1460*67e74705SXin Li           = OldTemplateParm->getDefaultArgument().getLocation();
1461*67e74705SXin Li       } else if (NewTemplateParm->hasDefaultArgument()) {
1462*67e74705SXin Li         SawDefaultArgument = true;
1463*67e74705SXin Li         PreviousDefaultArgLoc
1464*67e74705SXin Li           = NewTemplateParm->getDefaultArgument().getLocation();
1465*67e74705SXin Li       } else if (SawDefaultArgument)
1466*67e74705SXin Li         MissingDefaultArg = true;
1467*67e74705SXin Li     }
1468*67e74705SXin Li 
1469*67e74705SXin Li     // C++11 [temp.param]p11:
1470*67e74705SXin Li     //   If a template parameter of a primary class template or alias template
1471*67e74705SXin Li     //   is a template parameter pack, it shall be the last template parameter.
1472*67e74705SXin Li     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1473*67e74705SXin Li         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1474*67e74705SXin Li          TPC == TPC_TypeAliasTemplate)) {
1475*67e74705SXin Li       Diag((*NewParam)->getLocation(),
1476*67e74705SXin Li            diag::err_template_param_pack_must_be_last_template_parameter);
1477*67e74705SXin Li       Invalid = true;
1478*67e74705SXin Li     }
1479*67e74705SXin Li 
1480*67e74705SXin Li     if (RedundantDefaultArg) {
1481*67e74705SXin Li       // C++ [temp.param]p12:
1482*67e74705SXin Li       //   A template-parameter shall not be given default arguments
1483*67e74705SXin Li       //   by two different declarations in the same scope.
1484*67e74705SXin Li       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1485*67e74705SXin Li       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1486*67e74705SXin Li       Invalid = true;
1487*67e74705SXin Li     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1488*67e74705SXin Li       // C++ [temp.param]p11:
1489*67e74705SXin Li       //   If a template-parameter of a class template has a default
1490*67e74705SXin Li       //   template-argument, each subsequent template-parameter shall either
1491*67e74705SXin Li       //   have a default template-argument supplied or be a template parameter
1492*67e74705SXin Li       //   pack.
1493*67e74705SXin Li       Diag((*NewParam)->getLocation(),
1494*67e74705SXin Li            diag::err_template_param_default_arg_missing);
1495*67e74705SXin Li       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1496*67e74705SXin Li       Invalid = true;
1497*67e74705SXin Li       RemoveDefaultArguments = true;
1498*67e74705SXin Li     }
1499*67e74705SXin Li 
1500*67e74705SXin Li     // If we have an old template parameter list that we're merging
1501*67e74705SXin Li     // in, move on to the next parameter.
1502*67e74705SXin Li     if (OldParams)
1503*67e74705SXin Li       ++OldParam;
1504*67e74705SXin Li   }
1505*67e74705SXin Li 
1506*67e74705SXin Li   // We were missing some default arguments at the end of the list, so remove
1507*67e74705SXin Li   // all of the default arguments.
1508*67e74705SXin Li   if (RemoveDefaultArguments) {
1509*67e74705SXin Li     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1510*67e74705SXin Li                                       NewParamEnd = NewParams->end();
1511*67e74705SXin Li          NewParam != NewParamEnd; ++NewParam) {
1512*67e74705SXin Li       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1513*67e74705SXin Li         TTP->removeDefaultArgument();
1514*67e74705SXin Li       else if (NonTypeTemplateParmDecl *NTTP
1515*67e74705SXin Li                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1516*67e74705SXin Li         NTTP->removeDefaultArgument();
1517*67e74705SXin Li       else
1518*67e74705SXin Li         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1519*67e74705SXin Li     }
1520*67e74705SXin Li   }
1521*67e74705SXin Li 
1522*67e74705SXin Li   return Invalid;
1523*67e74705SXin Li }
1524*67e74705SXin Li 
1525*67e74705SXin Li namespace {
1526*67e74705SXin Li 
1527*67e74705SXin Li /// A class which looks for a use of a certain level of template
1528*67e74705SXin Li /// parameter.
1529*67e74705SXin Li struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1530*67e74705SXin Li   typedef RecursiveASTVisitor<DependencyChecker> super;
1531*67e74705SXin Li 
1532*67e74705SXin Li   unsigned Depth;
1533*67e74705SXin Li   bool Match;
1534*67e74705SXin Li   SourceLocation MatchLoc;
1535*67e74705SXin Li 
DependencyChecker__anonf3c9dfa90111::DependencyChecker1536*67e74705SXin Li   DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1537*67e74705SXin Li 
DependencyChecker__anonf3c9dfa90111::DependencyChecker1538*67e74705SXin Li   DependencyChecker(TemplateParameterList *Params) : Match(false) {
1539*67e74705SXin Li     NamedDecl *ND = Params->getParam(0);
1540*67e74705SXin Li     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1541*67e74705SXin Li       Depth = PD->getDepth();
1542*67e74705SXin Li     } else if (NonTypeTemplateParmDecl *PD =
1543*67e74705SXin Li                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1544*67e74705SXin Li       Depth = PD->getDepth();
1545*67e74705SXin Li     } else {
1546*67e74705SXin Li       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1547*67e74705SXin Li     }
1548*67e74705SXin Li   }
1549*67e74705SXin Li 
Matches__anonf3c9dfa90111::DependencyChecker1550*67e74705SXin Li   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1551*67e74705SXin Li     if (ParmDepth >= Depth) {
1552*67e74705SXin Li       Match = true;
1553*67e74705SXin Li       MatchLoc = Loc;
1554*67e74705SXin Li       return true;
1555*67e74705SXin Li     }
1556*67e74705SXin Li     return false;
1557*67e74705SXin Li   }
1558*67e74705SXin Li 
VisitTemplateTypeParmTypeLoc__anonf3c9dfa90111::DependencyChecker1559*67e74705SXin Li   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1560*67e74705SXin Li     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1561*67e74705SXin Li   }
1562*67e74705SXin Li 
VisitTemplateTypeParmType__anonf3c9dfa90111::DependencyChecker1563*67e74705SXin Li   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1564*67e74705SXin Li     return !Matches(T->getDepth());
1565*67e74705SXin Li   }
1566*67e74705SXin Li 
TraverseTemplateName__anonf3c9dfa90111::DependencyChecker1567*67e74705SXin Li   bool TraverseTemplateName(TemplateName N) {
1568*67e74705SXin Li     if (TemplateTemplateParmDecl *PD =
1569*67e74705SXin Li           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1570*67e74705SXin Li       if (Matches(PD->getDepth()))
1571*67e74705SXin Li         return false;
1572*67e74705SXin Li     return super::TraverseTemplateName(N);
1573*67e74705SXin Li   }
1574*67e74705SXin Li 
VisitDeclRefExpr__anonf3c9dfa90111::DependencyChecker1575*67e74705SXin Li   bool VisitDeclRefExpr(DeclRefExpr *E) {
1576*67e74705SXin Li     if (NonTypeTemplateParmDecl *PD =
1577*67e74705SXin Li           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1578*67e74705SXin Li       if (Matches(PD->getDepth(), E->getExprLoc()))
1579*67e74705SXin Li         return false;
1580*67e74705SXin Li     return super::VisitDeclRefExpr(E);
1581*67e74705SXin Li   }
1582*67e74705SXin Li 
VisitSubstTemplateTypeParmType__anonf3c9dfa90111::DependencyChecker1583*67e74705SXin Li   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1584*67e74705SXin Li     return TraverseType(T->getReplacementType());
1585*67e74705SXin Li   }
1586*67e74705SXin Li 
1587*67e74705SXin Li   bool
VisitSubstTemplateTypeParmPackType__anonf3c9dfa90111::DependencyChecker1588*67e74705SXin Li   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1589*67e74705SXin Li     return TraverseTemplateArgument(T->getArgumentPack());
1590*67e74705SXin Li   }
1591*67e74705SXin Li 
TraverseInjectedClassNameType__anonf3c9dfa90111::DependencyChecker1592*67e74705SXin Li   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1593*67e74705SXin Li     return TraverseType(T->getInjectedSpecializationType());
1594*67e74705SXin Li   }
1595*67e74705SXin Li };
1596*67e74705SXin Li } // end anonymous namespace
1597*67e74705SXin Li 
1598*67e74705SXin Li /// Determines whether a given type depends on the given parameter
1599*67e74705SXin Li /// list.
1600*67e74705SXin Li static bool
DependsOnTemplateParameters(QualType T,TemplateParameterList * Params)1601*67e74705SXin Li DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1602*67e74705SXin Li   DependencyChecker Checker(Params);
1603*67e74705SXin Li   Checker.TraverseType(T);
1604*67e74705SXin Li   return Checker.Match;
1605*67e74705SXin Li }
1606*67e74705SXin Li 
1607*67e74705SXin Li // Find the source range corresponding to the named type in the given
1608*67e74705SXin Li // nested-name-specifier, if any.
getRangeOfTypeInNestedNameSpecifier(ASTContext & Context,QualType T,const CXXScopeSpec & SS)1609*67e74705SXin Li static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1610*67e74705SXin Li                                                        QualType T,
1611*67e74705SXin Li                                                        const CXXScopeSpec &SS) {
1612*67e74705SXin Li   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1613*67e74705SXin Li   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1614*67e74705SXin Li     if (const Type *CurType = NNS->getAsType()) {
1615*67e74705SXin Li       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1616*67e74705SXin Li         return NNSLoc.getTypeLoc().getSourceRange();
1617*67e74705SXin Li     } else
1618*67e74705SXin Li       break;
1619*67e74705SXin Li 
1620*67e74705SXin Li     NNSLoc = NNSLoc.getPrefix();
1621*67e74705SXin Li   }
1622*67e74705SXin Li 
1623*67e74705SXin Li   return SourceRange();
1624*67e74705SXin Li }
1625*67e74705SXin Li 
1626*67e74705SXin Li /// \brief Match the given template parameter lists to the given scope
1627*67e74705SXin Li /// specifier, returning the template parameter list that applies to the
1628*67e74705SXin Li /// name.
1629*67e74705SXin Li ///
1630*67e74705SXin Li /// \param DeclStartLoc the start of the declaration that has a scope
1631*67e74705SXin Li /// specifier or a template parameter list.
1632*67e74705SXin Li ///
1633*67e74705SXin Li /// \param DeclLoc The location of the declaration itself.
1634*67e74705SXin Li ///
1635*67e74705SXin Li /// \param SS the scope specifier that will be matched to the given template
1636*67e74705SXin Li /// parameter lists. This scope specifier precedes a qualified name that is
1637*67e74705SXin Li /// being declared.
1638*67e74705SXin Li ///
1639*67e74705SXin Li /// \param TemplateId The template-id following the scope specifier, if there
1640*67e74705SXin Li /// is one. Used to check for a missing 'template<>'.
1641*67e74705SXin Li ///
1642*67e74705SXin Li /// \param ParamLists the template parameter lists, from the outermost to the
1643*67e74705SXin Li /// innermost template parameter lists.
1644*67e74705SXin Li ///
1645*67e74705SXin Li /// \param IsFriend Whether to apply the slightly different rules for
1646*67e74705SXin Li /// matching template parameters to scope specifiers in friend
1647*67e74705SXin Li /// declarations.
1648*67e74705SXin Li ///
1649*67e74705SXin Li /// \param IsExplicitSpecialization will be set true if the entity being
1650*67e74705SXin Li /// declared is an explicit specialization, false otherwise.
1651*67e74705SXin Li ///
1652*67e74705SXin Li /// \returns the template parameter list, if any, that corresponds to the
1653*67e74705SXin Li /// name that is preceded by the scope specifier @p SS. This template
1654*67e74705SXin Li /// parameter list may have template parameters (if we're declaring a
1655*67e74705SXin Li /// template) or may have no template parameters (if we're declaring a
1656*67e74705SXin Li /// template specialization), or may be NULL (if what we're declaring isn't
1657*67e74705SXin Li /// itself a template).
MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,SourceLocation DeclLoc,const CXXScopeSpec & SS,TemplateIdAnnotation * TemplateId,ArrayRef<TemplateParameterList * > ParamLists,bool IsFriend,bool & IsExplicitSpecialization,bool & Invalid)1658*67e74705SXin Li TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1659*67e74705SXin Li     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1660*67e74705SXin Li     TemplateIdAnnotation *TemplateId,
1661*67e74705SXin Li     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1662*67e74705SXin Li     bool &IsExplicitSpecialization, bool &Invalid) {
1663*67e74705SXin Li   IsExplicitSpecialization = false;
1664*67e74705SXin Li   Invalid = false;
1665*67e74705SXin Li 
1666*67e74705SXin Li   // The sequence of nested types to which we will match up the template
1667*67e74705SXin Li   // parameter lists. We first build this list by starting with the type named
1668*67e74705SXin Li   // by the nested-name-specifier and walking out until we run out of types.
1669*67e74705SXin Li   SmallVector<QualType, 4> NestedTypes;
1670*67e74705SXin Li   QualType T;
1671*67e74705SXin Li   if (SS.getScopeRep()) {
1672*67e74705SXin Li     if (CXXRecordDecl *Record
1673*67e74705SXin Li               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1674*67e74705SXin Li       T = Context.getTypeDeclType(Record);
1675*67e74705SXin Li     else
1676*67e74705SXin Li       T = QualType(SS.getScopeRep()->getAsType(), 0);
1677*67e74705SXin Li   }
1678*67e74705SXin Li 
1679*67e74705SXin Li   // If we found an explicit specialization that prevents us from needing
1680*67e74705SXin Li   // 'template<>' headers, this will be set to the location of that
1681*67e74705SXin Li   // explicit specialization.
1682*67e74705SXin Li   SourceLocation ExplicitSpecLoc;
1683*67e74705SXin Li 
1684*67e74705SXin Li   while (!T.isNull()) {
1685*67e74705SXin Li     NestedTypes.push_back(T);
1686*67e74705SXin Li 
1687*67e74705SXin Li     // Retrieve the parent of a record type.
1688*67e74705SXin Li     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1689*67e74705SXin Li       // If this type is an explicit specialization, we're done.
1690*67e74705SXin Li       if (ClassTemplateSpecializationDecl *Spec
1691*67e74705SXin Li           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1692*67e74705SXin Li         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1693*67e74705SXin Li             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1694*67e74705SXin Li           ExplicitSpecLoc = Spec->getLocation();
1695*67e74705SXin Li           break;
1696*67e74705SXin Li         }
1697*67e74705SXin Li       } else if (Record->getTemplateSpecializationKind()
1698*67e74705SXin Li                                                 == TSK_ExplicitSpecialization) {
1699*67e74705SXin Li         ExplicitSpecLoc = Record->getLocation();
1700*67e74705SXin Li         break;
1701*67e74705SXin Li       }
1702*67e74705SXin Li 
1703*67e74705SXin Li       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1704*67e74705SXin Li         T = Context.getTypeDeclType(Parent);
1705*67e74705SXin Li       else
1706*67e74705SXin Li         T = QualType();
1707*67e74705SXin Li       continue;
1708*67e74705SXin Li     }
1709*67e74705SXin Li 
1710*67e74705SXin Li     if (const TemplateSpecializationType *TST
1711*67e74705SXin Li                                      = T->getAs<TemplateSpecializationType>()) {
1712*67e74705SXin Li       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1713*67e74705SXin Li         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1714*67e74705SXin Li           T = Context.getTypeDeclType(Parent);
1715*67e74705SXin Li         else
1716*67e74705SXin Li           T = QualType();
1717*67e74705SXin Li         continue;
1718*67e74705SXin Li       }
1719*67e74705SXin Li     }
1720*67e74705SXin Li 
1721*67e74705SXin Li     // Look one step prior in a dependent template specialization type.
1722*67e74705SXin Li     if (const DependentTemplateSpecializationType *DependentTST
1723*67e74705SXin Li                           = T->getAs<DependentTemplateSpecializationType>()) {
1724*67e74705SXin Li       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1725*67e74705SXin Li         T = QualType(NNS->getAsType(), 0);
1726*67e74705SXin Li       else
1727*67e74705SXin Li         T = QualType();
1728*67e74705SXin Li       continue;
1729*67e74705SXin Li     }
1730*67e74705SXin Li 
1731*67e74705SXin Li     // Look one step prior in a dependent name type.
1732*67e74705SXin Li     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1733*67e74705SXin Li       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1734*67e74705SXin Li         T = QualType(NNS->getAsType(), 0);
1735*67e74705SXin Li       else
1736*67e74705SXin Li         T = QualType();
1737*67e74705SXin Li       continue;
1738*67e74705SXin Li     }
1739*67e74705SXin Li 
1740*67e74705SXin Li     // Retrieve the parent of an enumeration type.
1741*67e74705SXin Li     if (const EnumType *EnumT = T->getAs<EnumType>()) {
1742*67e74705SXin Li       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1743*67e74705SXin Li       // check here.
1744*67e74705SXin Li       EnumDecl *Enum = EnumT->getDecl();
1745*67e74705SXin Li 
1746*67e74705SXin Li       // Get to the parent type.
1747*67e74705SXin Li       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1748*67e74705SXin Li         T = Context.getTypeDeclType(Parent);
1749*67e74705SXin Li       else
1750*67e74705SXin Li         T = QualType();
1751*67e74705SXin Li       continue;
1752*67e74705SXin Li     }
1753*67e74705SXin Li 
1754*67e74705SXin Li     T = QualType();
1755*67e74705SXin Li   }
1756*67e74705SXin Li   // Reverse the nested types list, since we want to traverse from the outermost
1757*67e74705SXin Li   // to the innermost while checking template-parameter-lists.
1758*67e74705SXin Li   std::reverse(NestedTypes.begin(), NestedTypes.end());
1759*67e74705SXin Li 
1760*67e74705SXin Li   // C++0x [temp.expl.spec]p17:
1761*67e74705SXin Li   //   A member or a member template may be nested within many
1762*67e74705SXin Li   //   enclosing class templates. In an explicit specialization for
1763*67e74705SXin Li   //   such a member, the member declaration shall be preceded by a
1764*67e74705SXin Li   //   template<> for each enclosing class template that is
1765*67e74705SXin Li   //   explicitly specialized.
1766*67e74705SXin Li   bool SawNonEmptyTemplateParameterList = false;
1767*67e74705SXin Li 
1768*67e74705SXin Li   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1769*67e74705SXin Li     if (SawNonEmptyTemplateParameterList) {
1770*67e74705SXin Li       Diag(DeclLoc, diag::err_specialize_member_of_template)
1771*67e74705SXin Li         << !Recovery << Range;
1772*67e74705SXin Li       Invalid = true;
1773*67e74705SXin Li       IsExplicitSpecialization = false;
1774*67e74705SXin Li       return true;
1775*67e74705SXin Li     }
1776*67e74705SXin Li 
1777*67e74705SXin Li     return false;
1778*67e74705SXin Li   };
1779*67e74705SXin Li 
1780*67e74705SXin Li   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1781*67e74705SXin Li     // Check that we can have an explicit specialization here.
1782*67e74705SXin Li     if (CheckExplicitSpecialization(Range, true))
1783*67e74705SXin Li       return true;
1784*67e74705SXin Li 
1785*67e74705SXin Li     // We don't have a template header, but we should.
1786*67e74705SXin Li     SourceLocation ExpectedTemplateLoc;
1787*67e74705SXin Li     if (!ParamLists.empty())
1788*67e74705SXin Li       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1789*67e74705SXin Li     else
1790*67e74705SXin Li       ExpectedTemplateLoc = DeclStartLoc;
1791*67e74705SXin Li 
1792*67e74705SXin Li     Diag(DeclLoc, diag::err_template_spec_needs_header)
1793*67e74705SXin Li       << Range
1794*67e74705SXin Li       << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1795*67e74705SXin Li     return false;
1796*67e74705SXin Li   };
1797*67e74705SXin Li 
1798*67e74705SXin Li   unsigned ParamIdx = 0;
1799*67e74705SXin Li   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1800*67e74705SXin Li        ++TypeIdx) {
1801*67e74705SXin Li     T = NestedTypes[TypeIdx];
1802*67e74705SXin Li 
1803*67e74705SXin Li     // Whether we expect a 'template<>' header.
1804*67e74705SXin Li     bool NeedEmptyTemplateHeader = false;
1805*67e74705SXin Li 
1806*67e74705SXin Li     // Whether we expect a template header with parameters.
1807*67e74705SXin Li     bool NeedNonemptyTemplateHeader = false;
1808*67e74705SXin Li 
1809*67e74705SXin Li     // For a dependent type, the set of template parameters that we
1810*67e74705SXin Li     // expect to see.
1811*67e74705SXin Li     TemplateParameterList *ExpectedTemplateParams = nullptr;
1812*67e74705SXin Li 
1813*67e74705SXin Li     // C++0x [temp.expl.spec]p15:
1814*67e74705SXin Li     //   A member or a member template may be nested within many enclosing
1815*67e74705SXin Li     //   class templates. In an explicit specialization for such a member, the
1816*67e74705SXin Li     //   member declaration shall be preceded by a template<> for each
1817*67e74705SXin Li     //   enclosing class template that is explicitly specialized.
1818*67e74705SXin Li     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1819*67e74705SXin Li       if (ClassTemplatePartialSpecializationDecl *Partial
1820*67e74705SXin Li             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1821*67e74705SXin Li         ExpectedTemplateParams = Partial->getTemplateParameters();
1822*67e74705SXin Li         NeedNonemptyTemplateHeader = true;
1823*67e74705SXin Li       } else if (Record->isDependentType()) {
1824*67e74705SXin Li         if (Record->getDescribedClassTemplate()) {
1825*67e74705SXin Li           ExpectedTemplateParams = Record->getDescribedClassTemplate()
1826*67e74705SXin Li                                                       ->getTemplateParameters();
1827*67e74705SXin Li           NeedNonemptyTemplateHeader = true;
1828*67e74705SXin Li         }
1829*67e74705SXin Li       } else if (ClassTemplateSpecializationDecl *Spec
1830*67e74705SXin Li                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1831*67e74705SXin Li         // C++0x [temp.expl.spec]p4:
1832*67e74705SXin Li         //   Members of an explicitly specialized class template are defined
1833*67e74705SXin Li         //   in the same manner as members of normal classes, and not using
1834*67e74705SXin Li         //   the template<> syntax.
1835*67e74705SXin Li         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1836*67e74705SXin Li           NeedEmptyTemplateHeader = true;
1837*67e74705SXin Li         else
1838*67e74705SXin Li           continue;
1839*67e74705SXin Li       } else if (Record->getTemplateSpecializationKind()) {
1840*67e74705SXin Li         if (Record->getTemplateSpecializationKind()
1841*67e74705SXin Li                                                 != TSK_ExplicitSpecialization &&
1842*67e74705SXin Li             TypeIdx == NumTypes - 1)
1843*67e74705SXin Li           IsExplicitSpecialization = true;
1844*67e74705SXin Li 
1845*67e74705SXin Li         continue;
1846*67e74705SXin Li       }
1847*67e74705SXin Li     } else if (const TemplateSpecializationType *TST
1848*67e74705SXin Li                                      = T->getAs<TemplateSpecializationType>()) {
1849*67e74705SXin Li       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1850*67e74705SXin Li         ExpectedTemplateParams = Template->getTemplateParameters();
1851*67e74705SXin Li         NeedNonemptyTemplateHeader = true;
1852*67e74705SXin Li       }
1853*67e74705SXin Li     } else if (T->getAs<DependentTemplateSpecializationType>()) {
1854*67e74705SXin Li       // FIXME:  We actually could/should check the template arguments here
1855*67e74705SXin Li       // against the corresponding template parameter list.
1856*67e74705SXin Li       NeedNonemptyTemplateHeader = false;
1857*67e74705SXin Li     }
1858*67e74705SXin Li 
1859*67e74705SXin Li     // C++ [temp.expl.spec]p16:
1860*67e74705SXin Li     //   In an explicit specialization declaration for a member of a class
1861*67e74705SXin Li     //   template or a member template that ap- pears in namespace scope, the
1862*67e74705SXin Li     //   member template and some of its enclosing class templates may remain
1863*67e74705SXin Li     //   unspecialized, except that the declaration shall not explicitly
1864*67e74705SXin Li     //   specialize a class member template if its en- closing class templates
1865*67e74705SXin Li     //   are not explicitly specialized as well.
1866*67e74705SXin Li     if (ParamIdx < ParamLists.size()) {
1867*67e74705SXin Li       if (ParamLists[ParamIdx]->size() == 0) {
1868*67e74705SXin Li         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1869*67e74705SXin Li                                         false))
1870*67e74705SXin Li           return nullptr;
1871*67e74705SXin Li       } else
1872*67e74705SXin Li         SawNonEmptyTemplateParameterList = true;
1873*67e74705SXin Li     }
1874*67e74705SXin Li 
1875*67e74705SXin Li     if (NeedEmptyTemplateHeader) {
1876*67e74705SXin Li       // If we're on the last of the types, and we need a 'template<>' header
1877*67e74705SXin Li       // here, then it's an explicit specialization.
1878*67e74705SXin Li       if (TypeIdx == NumTypes - 1)
1879*67e74705SXin Li         IsExplicitSpecialization = true;
1880*67e74705SXin Li 
1881*67e74705SXin Li       if (ParamIdx < ParamLists.size()) {
1882*67e74705SXin Li         if (ParamLists[ParamIdx]->size() > 0) {
1883*67e74705SXin Li           // The header has template parameters when it shouldn't. Complain.
1884*67e74705SXin Li           Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1885*67e74705SXin Li                diag::err_template_param_list_matches_nontemplate)
1886*67e74705SXin Li             << T
1887*67e74705SXin Li             << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1888*67e74705SXin Li                            ParamLists[ParamIdx]->getRAngleLoc())
1889*67e74705SXin Li             << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1890*67e74705SXin Li           Invalid = true;
1891*67e74705SXin Li           return nullptr;
1892*67e74705SXin Li         }
1893*67e74705SXin Li 
1894*67e74705SXin Li         // Consume this template header.
1895*67e74705SXin Li         ++ParamIdx;
1896*67e74705SXin Li         continue;
1897*67e74705SXin Li       }
1898*67e74705SXin Li 
1899*67e74705SXin Li       if (!IsFriend)
1900*67e74705SXin Li         if (DiagnoseMissingExplicitSpecialization(
1901*67e74705SXin Li                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1902*67e74705SXin Li           return nullptr;
1903*67e74705SXin Li 
1904*67e74705SXin Li       continue;
1905*67e74705SXin Li     }
1906*67e74705SXin Li 
1907*67e74705SXin Li     if (NeedNonemptyTemplateHeader) {
1908*67e74705SXin Li       // In friend declarations we can have template-ids which don't
1909*67e74705SXin Li       // depend on the corresponding template parameter lists.  But
1910*67e74705SXin Li       // assume that empty parameter lists are supposed to match this
1911*67e74705SXin Li       // template-id.
1912*67e74705SXin Li       if (IsFriend && T->isDependentType()) {
1913*67e74705SXin Li         if (ParamIdx < ParamLists.size() &&
1914*67e74705SXin Li             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1915*67e74705SXin Li           ExpectedTemplateParams = nullptr;
1916*67e74705SXin Li         else
1917*67e74705SXin Li           continue;
1918*67e74705SXin Li       }
1919*67e74705SXin Li 
1920*67e74705SXin Li       if (ParamIdx < ParamLists.size()) {
1921*67e74705SXin Li         // Check the template parameter list, if we can.
1922*67e74705SXin Li         if (ExpectedTemplateParams &&
1923*67e74705SXin Li             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1924*67e74705SXin Li                                             ExpectedTemplateParams,
1925*67e74705SXin Li                                             true, TPL_TemplateMatch))
1926*67e74705SXin Li           Invalid = true;
1927*67e74705SXin Li 
1928*67e74705SXin Li         if (!Invalid &&
1929*67e74705SXin Li             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1930*67e74705SXin Li                                        TPC_ClassTemplateMember))
1931*67e74705SXin Li           Invalid = true;
1932*67e74705SXin Li 
1933*67e74705SXin Li         ++ParamIdx;
1934*67e74705SXin Li         continue;
1935*67e74705SXin Li       }
1936*67e74705SXin Li 
1937*67e74705SXin Li       Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1938*67e74705SXin Li         << T
1939*67e74705SXin Li         << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1940*67e74705SXin Li       Invalid = true;
1941*67e74705SXin Li       continue;
1942*67e74705SXin Li     }
1943*67e74705SXin Li   }
1944*67e74705SXin Li 
1945*67e74705SXin Li   // If there were at least as many template-ids as there were template
1946*67e74705SXin Li   // parameter lists, then there are no template parameter lists remaining for
1947*67e74705SXin Li   // the declaration itself.
1948*67e74705SXin Li   if (ParamIdx >= ParamLists.size()) {
1949*67e74705SXin Li     if (TemplateId && !IsFriend) {
1950*67e74705SXin Li       // We don't have a template header for the declaration itself, but we
1951*67e74705SXin Li       // should.
1952*67e74705SXin Li       IsExplicitSpecialization = true;
1953*67e74705SXin Li       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1954*67e74705SXin Li                                                         TemplateId->RAngleLoc));
1955*67e74705SXin Li 
1956*67e74705SXin Li       // Fabricate an empty template parameter list for the invented header.
1957*67e74705SXin Li       return TemplateParameterList::Create(Context, SourceLocation(),
1958*67e74705SXin Li                                            SourceLocation(), None,
1959*67e74705SXin Li                                            SourceLocation());
1960*67e74705SXin Li     }
1961*67e74705SXin Li 
1962*67e74705SXin Li     return nullptr;
1963*67e74705SXin Li   }
1964*67e74705SXin Li 
1965*67e74705SXin Li   // If there were too many template parameter lists, complain about that now.
1966*67e74705SXin Li   if (ParamIdx < ParamLists.size() - 1) {
1967*67e74705SXin Li     bool HasAnyExplicitSpecHeader = false;
1968*67e74705SXin Li     bool AllExplicitSpecHeaders = true;
1969*67e74705SXin Li     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1970*67e74705SXin Li       if (ParamLists[I]->size() == 0)
1971*67e74705SXin Li         HasAnyExplicitSpecHeader = true;
1972*67e74705SXin Li       else
1973*67e74705SXin Li         AllExplicitSpecHeaders = false;
1974*67e74705SXin Li     }
1975*67e74705SXin Li 
1976*67e74705SXin Li     Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1977*67e74705SXin Li          AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1978*67e74705SXin Li                                 : diag::err_template_spec_extra_headers)
1979*67e74705SXin Li         << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1980*67e74705SXin Li                        ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1981*67e74705SXin Li 
1982*67e74705SXin Li     // If there was a specialization somewhere, such that 'template<>' is
1983*67e74705SXin Li     // not required, and there were any 'template<>' headers, note where the
1984*67e74705SXin Li     // specialization occurred.
1985*67e74705SXin Li     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1986*67e74705SXin Li       Diag(ExplicitSpecLoc,
1987*67e74705SXin Li            diag::note_explicit_template_spec_does_not_need_header)
1988*67e74705SXin Li         << NestedTypes.back();
1989*67e74705SXin Li 
1990*67e74705SXin Li     // We have a template parameter list with no corresponding scope, which
1991*67e74705SXin Li     // means that the resulting template declaration can't be instantiated
1992*67e74705SXin Li     // properly (we'll end up with dependent nodes when we shouldn't).
1993*67e74705SXin Li     if (!AllExplicitSpecHeaders)
1994*67e74705SXin Li       Invalid = true;
1995*67e74705SXin Li   }
1996*67e74705SXin Li 
1997*67e74705SXin Li   // C++ [temp.expl.spec]p16:
1998*67e74705SXin Li   //   In an explicit specialization declaration for a member of a class
1999*67e74705SXin Li   //   template or a member template that ap- pears in namespace scope, the
2000*67e74705SXin Li   //   member template and some of its enclosing class templates may remain
2001*67e74705SXin Li   //   unspecialized, except that the declaration shall not explicitly
2002*67e74705SXin Li   //   specialize a class member template if its en- closing class templates
2003*67e74705SXin Li   //   are not explicitly specialized as well.
2004*67e74705SXin Li   if (ParamLists.back()->size() == 0 &&
2005*67e74705SXin Li       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2006*67e74705SXin Li                                   false))
2007*67e74705SXin Li     return nullptr;
2008*67e74705SXin Li 
2009*67e74705SXin Li   // Return the last template parameter list, which corresponds to the
2010*67e74705SXin Li   // entity being declared.
2011*67e74705SXin Li   return ParamLists.back();
2012*67e74705SXin Li }
2013*67e74705SXin Li 
NoteAllFoundTemplates(TemplateName Name)2014*67e74705SXin Li void Sema::NoteAllFoundTemplates(TemplateName Name) {
2015*67e74705SXin Li   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2016*67e74705SXin Li     Diag(Template->getLocation(), diag::note_template_declared_here)
2017*67e74705SXin Li         << (isa<FunctionTemplateDecl>(Template)
2018*67e74705SXin Li                 ? 0
2019*67e74705SXin Li                 : isa<ClassTemplateDecl>(Template)
2020*67e74705SXin Li                       ? 1
2021*67e74705SXin Li                       : isa<VarTemplateDecl>(Template)
2022*67e74705SXin Li                             ? 2
2023*67e74705SXin Li                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2024*67e74705SXin Li         << Template->getDeclName();
2025*67e74705SXin Li     return;
2026*67e74705SXin Li   }
2027*67e74705SXin Li 
2028*67e74705SXin Li   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2029*67e74705SXin Li     for (OverloadedTemplateStorage::iterator I = OST->begin(),
2030*67e74705SXin Li                                           IEnd = OST->end();
2031*67e74705SXin Li          I != IEnd; ++I)
2032*67e74705SXin Li       Diag((*I)->getLocation(), diag::note_template_declared_here)
2033*67e74705SXin Li         << 0 << (*I)->getDeclName();
2034*67e74705SXin Li 
2035*67e74705SXin Li     return;
2036*67e74705SXin Li   }
2037*67e74705SXin Li }
2038*67e74705SXin Li 
2039*67e74705SXin Li static QualType
checkBuiltinTemplateIdType(Sema & SemaRef,BuiltinTemplateDecl * BTD,const SmallVectorImpl<TemplateArgument> & Converted,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)2040*67e74705SXin Li checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2041*67e74705SXin Li                            const SmallVectorImpl<TemplateArgument> &Converted,
2042*67e74705SXin Li                            SourceLocation TemplateLoc,
2043*67e74705SXin Li                            TemplateArgumentListInfo &TemplateArgs) {
2044*67e74705SXin Li   ASTContext &Context = SemaRef.getASTContext();
2045*67e74705SXin Li   switch (BTD->getBuiltinTemplateKind()) {
2046*67e74705SXin Li   case BTK__make_integer_seq: {
2047*67e74705SXin Li     // Specializations of __make_integer_seq<S, T, N> are treated like
2048*67e74705SXin Li     // S<T, 0, ..., N-1>.
2049*67e74705SXin Li 
2050*67e74705SXin Li     // C++14 [inteseq.intseq]p1:
2051*67e74705SXin Li     //   T shall be an integer type.
2052*67e74705SXin Li     if (!Converted[1].getAsType()->isIntegralType(Context)) {
2053*67e74705SXin Li       SemaRef.Diag(TemplateArgs[1].getLocation(),
2054*67e74705SXin Li                    diag::err_integer_sequence_integral_element_type);
2055*67e74705SXin Li       return QualType();
2056*67e74705SXin Li     }
2057*67e74705SXin Li 
2058*67e74705SXin Li     // C++14 [inteseq.make]p1:
2059*67e74705SXin Li     //   If N is negative the program is ill-formed.
2060*67e74705SXin Li     TemplateArgument NumArgsArg = Converted[2];
2061*67e74705SXin Li     llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2062*67e74705SXin Li     if (NumArgs < 0) {
2063*67e74705SXin Li       SemaRef.Diag(TemplateArgs[2].getLocation(),
2064*67e74705SXin Li                    diag::err_integer_sequence_negative_length);
2065*67e74705SXin Li       return QualType();
2066*67e74705SXin Li     }
2067*67e74705SXin Li 
2068*67e74705SXin Li     QualType ArgTy = NumArgsArg.getIntegralType();
2069*67e74705SXin Li     TemplateArgumentListInfo SyntheticTemplateArgs;
2070*67e74705SXin Li     // The type argument gets reused as the first template argument in the
2071*67e74705SXin Li     // synthetic template argument list.
2072*67e74705SXin Li     SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2073*67e74705SXin Li     // Expand N into 0 ... N-1.
2074*67e74705SXin Li     for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2075*67e74705SXin Li          I < NumArgs; ++I) {
2076*67e74705SXin Li       TemplateArgument TA(Context, I, ArgTy);
2077*67e74705SXin Li       Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2078*67e74705SXin Li                            TA, TemplateArgs[2].getLocation())
2079*67e74705SXin Li                     .getAs<Expr>();
2080*67e74705SXin Li       SyntheticTemplateArgs.addArgument(
2081*67e74705SXin Li           TemplateArgumentLoc(TemplateArgument(E), E));
2082*67e74705SXin Li     }
2083*67e74705SXin Li     // The first template argument will be reused as the template decl that
2084*67e74705SXin Li     // our synthetic template arguments will be applied to.
2085*67e74705SXin Li     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2086*67e74705SXin Li                                        TemplateLoc, SyntheticTemplateArgs);
2087*67e74705SXin Li   }
2088*67e74705SXin Li 
2089*67e74705SXin Li   case BTK__type_pack_element:
2090*67e74705SXin Li     // Specializations of
2091*67e74705SXin Li     //    __type_pack_element<Index, T_1, ..., T_N>
2092*67e74705SXin Li     // are treated like T_Index.
2093*67e74705SXin Li     assert(Converted.size() == 2 &&
2094*67e74705SXin Li       "__type_pack_element should be given an index and a parameter pack");
2095*67e74705SXin Li 
2096*67e74705SXin Li     // If the Index is out of bounds, the program is ill-formed.
2097*67e74705SXin Li     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2098*67e74705SXin Li     llvm::APSInt Index = IndexArg.getAsIntegral();
2099*67e74705SXin Li     assert(Index >= 0 && "the index used with __type_pack_element should be of "
2100*67e74705SXin Li                          "type std::size_t, and hence be non-negative");
2101*67e74705SXin Li     if (Index >= Ts.pack_size()) {
2102*67e74705SXin Li       SemaRef.Diag(TemplateArgs[0].getLocation(),
2103*67e74705SXin Li                    diag::err_type_pack_element_out_of_bounds);
2104*67e74705SXin Li       return QualType();
2105*67e74705SXin Li     }
2106*67e74705SXin Li 
2107*67e74705SXin Li     // We simply return the type at index `Index`.
2108*67e74705SXin Li     auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2109*67e74705SXin Li     return Nth->getAsType();
2110*67e74705SXin Li   }
2111*67e74705SXin Li   llvm_unreachable("unexpected BuiltinTemplateDecl!");
2112*67e74705SXin Li }
2113*67e74705SXin Li 
CheckTemplateIdType(TemplateName Name,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)2114*67e74705SXin Li QualType Sema::CheckTemplateIdType(TemplateName Name,
2115*67e74705SXin Li                                    SourceLocation TemplateLoc,
2116*67e74705SXin Li                                    TemplateArgumentListInfo &TemplateArgs) {
2117*67e74705SXin Li   DependentTemplateName *DTN
2118*67e74705SXin Li     = Name.getUnderlying().getAsDependentTemplateName();
2119*67e74705SXin Li   if (DTN && DTN->isIdentifier())
2120*67e74705SXin Li     // When building a template-id where the template-name is dependent,
2121*67e74705SXin Li     // assume the template is a type template. Either our assumption is
2122*67e74705SXin Li     // correct, or the code is ill-formed and will be diagnosed when the
2123*67e74705SXin Li     // dependent name is substituted.
2124*67e74705SXin Li     return Context.getDependentTemplateSpecializationType(ETK_None,
2125*67e74705SXin Li                                                           DTN->getQualifier(),
2126*67e74705SXin Li                                                           DTN->getIdentifier(),
2127*67e74705SXin Li                                                           TemplateArgs);
2128*67e74705SXin Li 
2129*67e74705SXin Li   TemplateDecl *Template = Name.getAsTemplateDecl();
2130*67e74705SXin Li   if (!Template || isa<FunctionTemplateDecl>(Template) ||
2131*67e74705SXin Li       isa<VarTemplateDecl>(Template)) {
2132*67e74705SXin Li     // We might have a substituted template template parameter pack. If so,
2133*67e74705SXin Li     // build a template specialization type for it.
2134*67e74705SXin Li     if (Name.getAsSubstTemplateTemplateParmPack())
2135*67e74705SXin Li       return Context.getTemplateSpecializationType(Name, TemplateArgs);
2136*67e74705SXin Li 
2137*67e74705SXin Li     Diag(TemplateLoc, diag::err_template_id_not_a_type)
2138*67e74705SXin Li       << Name;
2139*67e74705SXin Li     NoteAllFoundTemplates(Name);
2140*67e74705SXin Li     return QualType();
2141*67e74705SXin Li   }
2142*67e74705SXin Li 
2143*67e74705SXin Li   // Check that the template argument list is well-formed for this
2144*67e74705SXin Li   // template.
2145*67e74705SXin Li   SmallVector<TemplateArgument, 4> Converted;
2146*67e74705SXin Li   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2147*67e74705SXin Li                                 false, Converted))
2148*67e74705SXin Li     return QualType();
2149*67e74705SXin Li 
2150*67e74705SXin Li   QualType CanonType;
2151*67e74705SXin Li 
2152*67e74705SXin Li   bool InstantiationDependent = false;
2153*67e74705SXin Li   if (TypeAliasTemplateDecl *AliasTemplate =
2154*67e74705SXin Li           dyn_cast<TypeAliasTemplateDecl>(Template)) {
2155*67e74705SXin Li     // Find the canonical type for this type alias template specialization.
2156*67e74705SXin Li     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2157*67e74705SXin Li     if (Pattern->isInvalidDecl())
2158*67e74705SXin Li       return QualType();
2159*67e74705SXin Li 
2160*67e74705SXin Li     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2161*67e74705SXin Li                                       Converted);
2162*67e74705SXin Li 
2163*67e74705SXin Li     // Only substitute for the innermost template argument list.
2164*67e74705SXin Li     MultiLevelTemplateArgumentList TemplateArgLists;
2165*67e74705SXin Li     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2166*67e74705SXin Li     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2167*67e74705SXin Li     for (unsigned I = 0; I < Depth; ++I)
2168*67e74705SXin Li       TemplateArgLists.addOuterTemplateArguments(None);
2169*67e74705SXin Li 
2170*67e74705SXin Li     LocalInstantiationScope Scope(*this);
2171*67e74705SXin Li     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2172*67e74705SXin Li     if (Inst.isInvalid())
2173*67e74705SXin Li       return QualType();
2174*67e74705SXin Li 
2175*67e74705SXin Li     CanonType = SubstType(Pattern->getUnderlyingType(),
2176*67e74705SXin Li                           TemplateArgLists, AliasTemplate->getLocation(),
2177*67e74705SXin Li                           AliasTemplate->getDeclName());
2178*67e74705SXin Li     if (CanonType.isNull())
2179*67e74705SXin Li       return QualType();
2180*67e74705SXin Li   } else if (Name.isDependent() ||
2181*67e74705SXin Li              TemplateSpecializationType::anyDependentTemplateArguments(
2182*67e74705SXin Li                TemplateArgs, InstantiationDependent)) {
2183*67e74705SXin Li     // This class template specialization is a dependent
2184*67e74705SXin Li     // type. Therefore, its canonical type is another class template
2185*67e74705SXin Li     // specialization type that contains all of the converted
2186*67e74705SXin Li     // arguments in canonical form. This ensures that, e.g., A<T> and
2187*67e74705SXin Li     // A<T, T> have identical types when A is declared as:
2188*67e74705SXin Li     //
2189*67e74705SXin Li     //   template<typename T, typename U = T> struct A;
2190*67e74705SXin Li     TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2191*67e74705SXin Li     CanonType = Context.getTemplateSpecializationType(CanonName,
2192*67e74705SXin Li                                                       Converted);
2193*67e74705SXin Li 
2194*67e74705SXin Li     // FIXME: CanonType is not actually the canonical type, and unfortunately
2195*67e74705SXin Li     // it is a TemplateSpecializationType that we will never use again.
2196*67e74705SXin Li     // In the future, we need to teach getTemplateSpecializationType to only
2197*67e74705SXin Li     // build the canonical type and return that to us.
2198*67e74705SXin Li     CanonType = Context.getCanonicalType(CanonType);
2199*67e74705SXin Li 
2200*67e74705SXin Li     // This might work out to be a current instantiation, in which
2201*67e74705SXin Li     // case the canonical type needs to be the InjectedClassNameType.
2202*67e74705SXin Li     //
2203*67e74705SXin Li     // TODO: in theory this could be a simple hashtable lookup; most
2204*67e74705SXin Li     // changes to CurContext don't change the set of current
2205*67e74705SXin Li     // instantiations.
2206*67e74705SXin Li     if (isa<ClassTemplateDecl>(Template)) {
2207*67e74705SXin Li       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2208*67e74705SXin Li         // If we get out to a namespace, we're done.
2209*67e74705SXin Li         if (Ctx->isFileContext()) break;
2210*67e74705SXin Li 
2211*67e74705SXin Li         // If this isn't a record, keep looking.
2212*67e74705SXin Li         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2213*67e74705SXin Li         if (!Record) continue;
2214*67e74705SXin Li 
2215*67e74705SXin Li         // Look for one of the two cases with InjectedClassNameTypes
2216*67e74705SXin Li         // and check whether it's the same template.
2217*67e74705SXin Li         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2218*67e74705SXin Li             !Record->getDescribedClassTemplate())
2219*67e74705SXin Li           continue;
2220*67e74705SXin Li 
2221*67e74705SXin Li         // Fetch the injected class name type and check whether its
2222*67e74705SXin Li         // injected type is equal to the type we just built.
2223*67e74705SXin Li         QualType ICNT = Context.getTypeDeclType(Record);
2224*67e74705SXin Li         QualType Injected = cast<InjectedClassNameType>(ICNT)
2225*67e74705SXin Li           ->getInjectedSpecializationType();
2226*67e74705SXin Li 
2227*67e74705SXin Li         if (CanonType != Injected->getCanonicalTypeInternal())
2228*67e74705SXin Li           continue;
2229*67e74705SXin Li 
2230*67e74705SXin Li         // If so, the canonical type of this TST is the injected
2231*67e74705SXin Li         // class name type of the record we just found.
2232*67e74705SXin Li         assert(ICNT.isCanonical());
2233*67e74705SXin Li         CanonType = ICNT;
2234*67e74705SXin Li         break;
2235*67e74705SXin Li       }
2236*67e74705SXin Li     }
2237*67e74705SXin Li   } else if (ClassTemplateDecl *ClassTemplate
2238*67e74705SXin Li                = dyn_cast<ClassTemplateDecl>(Template)) {
2239*67e74705SXin Li     // Find the class template specialization declaration that
2240*67e74705SXin Li     // corresponds to these arguments.
2241*67e74705SXin Li     void *InsertPos = nullptr;
2242*67e74705SXin Li     ClassTemplateSpecializationDecl *Decl
2243*67e74705SXin Li       = ClassTemplate->findSpecialization(Converted, InsertPos);
2244*67e74705SXin Li     if (!Decl) {
2245*67e74705SXin Li       // This is the first time we have referenced this class template
2246*67e74705SXin Li       // specialization. Create the canonical declaration and add it to
2247*67e74705SXin Li       // the set of specializations.
2248*67e74705SXin Li       Decl = ClassTemplateSpecializationDecl::Create(Context,
2249*67e74705SXin Li                             ClassTemplate->getTemplatedDecl()->getTagKind(),
2250*67e74705SXin Li                                                 ClassTemplate->getDeclContext(),
2251*67e74705SXin Li                             ClassTemplate->getTemplatedDecl()->getLocStart(),
2252*67e74705SXin Li                                                 ClassTemplate->getLocation(),
2253*67e74705SXin Li                                                      ClassTemplate,
2254*67e74705SXin Li                                                      Converted, nullptr);
2255*67e74705SXin Li       ClassTemplate->AddSpecialization(Decl, InsertPos);
2256*67e74705SXin Li       if (ClassTemplate->isOutOfLine())
2257*67e74705SXin Li         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2258*67e74705SXin Li     }
2259*67e74705SXin Li 
2260*67e74705SXin Li     // Diagnose uses of this specialization.
2261*67e74705SXin Li     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2262*67e74705SXin Li 
2263*67e74705SXin Li     CanonType = Context.getTypeDeclType(Decl);
2264*67e74705SXin Li     assert(isa<RecordType>(CanonType) &&
2265*67e74705SXin Li            "type of non-dependent specialization is not a RecordType");
2266*67e74705SXin Li   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2267*67e74705SXin Li     CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2268*67e74705SXin Li                                            TemplateArgs);
2269*67e74705SXin Li   }
2270*67e74705SXin Li 
2271*67e74705SXin Li   // Build the fully-sugared type for this class template
2272*67e74705SXin Li   // specialization, which refers back to the class template
2273*67e74705SXin Li   // specialization we created or found.
2274*67e74705SXin Li   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2275*67e74705SXin Li }
2276*67e74705SXin Li 
2277*67e74705SXin Li TypeResult
ActOnTemplateIdType(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,bool IsCtorOrDtorName)2278*67e74705SXin Li Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2279*67e74705SXin Li                           TemplateTy TemplateD, SourceLocation TemplateLoc,
2280*67e74705SXin Li                           SourceLocation LAngleLoc,
2281*67e74705SXin Li                           ASTTemplateArgsPtr TemplateArgsIn,
2282*67e74705SXin Li                           SourceLocation RAngleLoc,
2283*67e74705SXin Li                           bool IsCtorOrDtorName) {
2284*67e74705SXin Li   if (SS.isInvalid())
2285*67e74705SXin Li     return true;
2286*67e74705SXin Li 
2287*67e74705SXin Li   TemplateName Template = TemplateD.get();
2288*67e74705SXin Li 
2289*67e74705SXin Li   // Translate the parser's template argument list in our AST format.
2290*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2291*67e74705SXin Li   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2292*67e74705SXin Li 
2293*67e74705SXin Li   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2294*67e74705SXin Li     QualType T
2295*67e74705SXin Li       = Context.getDependentTemplateSpecializationType(ETK_None,
2296*67e74705SXin Li                                                        DTN->getQualifier(),
2297*67e74705SXin Li                                                        DTN->getIdentifier(),
2298*67e74705SXin Li                                                        TemplateArgs);
2299*67e74705SXin Li     // Build type-source information.
2300*67e74705SXin Li     TypeLocBuilder TLB;
2301*67e74705SXin Li     DependentTemplateSpecializationTypeLoc SpecTL
2302*67e74705SXin Li       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2303*67e74705SXin Li     SpecTL.setElaboratedKeywordLoc(SourceLocation());
2304*67e74705SXin Li     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2305*67e74705SXin Li     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2306*67e74705SXin Li     SpecTL.setTemplateNameLoc(TemplateLoc);
2307*67e74705SXin Li     SpecTL.setLAngleLoc(LAngleLoc);
2308*67e74705SXin Li     SpecTL.setRAngleLoc(RAngleLoc);
2309*67e74705SXin Li     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2310*67e74705SXin Li       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2311*67e74705SXin Li     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2312*67e74705SXin Li   }
2313*67e74705SXin Li 
2314*67e74705SXin Li   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2315*67e74705SXin Li 
2316*67e74705SXin Li   if (Result.isNull())
2317*67e74705SXin Li     return true;
2318*67e74705SXin Li 
2319*67e74705SXin Li   // Build type-source information.
2320*67e74705SXin Li   TypeLocBuilder TLB;
2321*67e74705SXin Li   TemplateSpecializationTypeLoc SpecTL
2322*67e74705SXin Li     = TLB.push<TemplateSpecializationTypeLoc>(Result);
2323*67e74705SXin Li   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2324*67e74705SXin Li   SpecTL.setTemplateNameLoc(TemplateLoc);
2325*67e74705SXin Li   SpecTL.setLAngleLoc(LAngleLoc);
2326*67e74705SXin Li   SpecTL.setRAngleLoc(RAngleLoc);
2327*67e74705SXin Li   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2328*67e74705SXin Li     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2329*67e74705SXin Li 
2330*67e74705SXin Li   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2331*67e74705SXin Li   // constructor or destructor name (in such a case, the scope specifier
2332*67e74705SXin Li   // will be attached to the enclosing Decl or Expr node).
2333*67e74705SXin Li   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2334*67e74705SXin Li     // Create an elaborated-type-specifier containing the nested-name-specifier.
2335*67e74705SXin Li     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2336*67e74705SXin Li     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2337*67e74705SXin Li     ElabTL.setElaboratedKeywordLoc(SourceLocation());
2338*67e74705SXin Li     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2339*67e74705SXin Li   }
2340*67e74705SXin Li 
2341*67e74705SXin Li   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2342*67e74705SXin Li }
2343*67e74705SXin Li 
ActOnTagTemplateIdType(TagUseKind TUK,TypeSpecifierType TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)2344*67e74705SXin Li TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2345*67e74705SXin Li                                         TypeSpecifierType TagSpec,
2346*67e74705SXin Li                                         SourceLocation TagLoc,
2347*67e74705SXin Li                                         CXXScopeSpec &SS,
2348*67e74705SXin Li                                         SourceLocation TemplateKWLoc,
2349*67e74705SXin Li                                         TemplateTy TemplateD,
2350*67e74705SXin Li                                         SourceLocation TemplateLoc,
2351*67e74705SXin Li                                         SourceLocation LAngleLoc,
2352*67e74705SXin Li                                         ASTTemplateArgsPtr TemplateArgsIn,
2353*67e74705SXin Li                                         SourceLocation RAngleLoc) {
2354*67e74705SXin Li   TemplateName Template = TemplateD.get();
2355*67e74705SXin Li 
2356*67e74705SXin Li   // Translate the parser's template argument list in our AST format.
2357*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2358*67e74705SXin Li   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2359*67e74705SXin Li 
2360*67e74705SXin Li   // Determine the tag kind
2361*67e74705SXin Li   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2362*67e74705SXin Li   ElaboratedTypeKeyword Keyword
2363*67e74705SXin Li     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2364*67e74705SXin Li 
2365*67e74705SXin Li   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2366*67e74705SXin Li     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2367*67e74705SXin Li                                                           DTN->getQualifier(),
2368*67e74705SXin Li                                                           DTN->getIdentifier(),
2369*67e74705SXin Li                                                                 TemplateArgs);
2370*67e74705SXin Li 
2371*67e74705SXin Li     // Build type-source information.
2372*67e74705SXin Li     TypeLocBuilder TLB;
2373*67e74705SXin Li     DependentTemplateSpecializationTypeLoc SpecTL
2374*67e74705SXin Li       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2375*67e74705SXin Li     SpecTL.setElaboratedKeywordLoc(TagLoc);
2376*67e74705SXin Li     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2377*67e74705SXin Li     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2378*67e74705SXin Li     SpecTL.setTemplateNameLoc(TemplateLoc);
2379*67e74705SXin Li     SpecTL.setLAngleLoc(LAngleLoc);
2380*67e74705SXin Li     SpecTL.setRAngleLoc(RAngleLoc);
2381*67e74705SXin Li     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2382*67e74705SXin Li       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2383*67e74705SXin Li     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2384*67e74705SXin Li   }
2385*67e74705SXin Li 
2386*67e74705SXin Li   if (TypeAliasTemplateDecl *TAT =
2387*67e74705SXin Li         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2388*67e74705SXin Li     // C++0x [dcl.type.elab]p2:
2389*67e74705SXin Li     //   If the identifier resolves to a typedef-name or the simple-template-id
2390*67e74705SXin Li     //   resolves to an alias template specialization, the
2391*67e74705SXin Li     //   elaborated-type-specifier is ill-formed.
2392*67e74705SXin Li     Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2393*67e74705SXin Li     Diag(TAT->getLocation(), diag::note_declared_at);
2394*67e74705SXin Li   }
2395*67e74705SXin Li 
2396*67e74705SXin Li   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2397*67e74705SXin Li   if (Result.isNull())
2398*67e74705SXin Li     return TypeResult(true);
2399*67e74705SXin Li 
2400*67e74705SXin Li   // Check the tag kind
2401*67e74705SXin Li   if (const RecordType *RT = Result->getAs<RecordType>()) {
2402*67e74705SXin Li     RecordDecl *D = RT->getDecl();
2403*67e74705SXin Li 
2404*67e74705SXin Li     IdentifierInfo *Id = D->getIdentifier();
2405*67e74705SXin Li     assert(Id && "templated class must have an identifier");
2406*67e74705SXin Li 
2407*67e74705SXin Li     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2408*67e74705SXin Li                                       TagLoc, Id)) {
2409*67e74705SXin Li       Diag(TagLoc, diag::err_use_with_wrong_tag)
2410*67e74705SXin Li         << Result
2411*67e74705SXin Li         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2412*67e74705SXin Li       Diag(D->getLocation(), diag::note_previous_use);
2413*67e74705SXin Li     }
2414*67e74705SXin Li   }
2415*67e74705SXin Li 
2416*67e74705SXin Li   // Provide source-location information for the template specialization.
2417*67e74705SXin Li   TypeLocBuilder TLB;
2418*67e74705SXin Li   TemplateSpecializationTypeLoc SpecTL
2419*67e74705SXin Li     = TLB.push<TemplateSpecializationTypeLoc>(Result);
2420*67e74705SXin Li   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2421*67e74705SXin Li   SpecTL.setTemplateNameLoc(TemplateLoc);
2422*67e74705SXin Li   SpecTL.setLAngleLoc(LAngleLoc);
2423*67e74705SXin Li   SpecTL.setRAngleLoc(RAngleLoc);
2424*67e74705SXin Li   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2425*67e74705SXin Li     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2426*67e74705SXin Li 
2427*67e74705SXin Li   // Construct an elaborated type containing the nested-name-specifier (if any)
2428*67e74705SXin Li   // and tag keyword.
2429*67e74705SXin Li   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2430*67e74705SXin Li   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2431*67e74705SXin Li   ElabTL.setElaboratedKeywordLoc(TagLoc);
2432*67e74705SXin Li   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2433*67e74705SXin Li   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2434*67e74705SXin Li }
2435*67e74705SXin Li 
2436*67e74705SXin Li static bool CheckTemplatePartialSpecializationArgs(
2437*67e74705SXin Li     Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2438*67e74705SXin Li     unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2439*67e74705SXin Li 
2440*67e74705SXin Li static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2441*67e74705SXin Li                                              NamedDecl *PrevDecl,
2442*67e74705SXin Li                                              SourceLocation Loc,
2443*67e74705SXin Li                                              bool IsPartialSpecialization);
2444*67e74705SXin Li 
2445*67e74705SXin Li static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2446*67e74705SXin Li 
isTemplateArgumentTemplateParameter(const TemplateArgument & Arg,unsigned Depth,unsigned Index)2447*67e74705SXin Li static bool isTemplateArgumentTemplateParameter(
2448*67e74705SXin Li     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2449*67e74705SXin Li   switch (Arg.getKind()) {
2450*67e74705SXin Li   case TemplateArgument::Null:
2451*67e74705SXin Li   case TemplateArgument::NullPtr:
2452*67e74705SXin Li   case TemplateArgument::Integral:
2453*67e74705SXin Li   case TemplateArgument::Declaration:
2454*67e74705SXin Li   case TemplateArgument::Pack:
2455*67e74705SXin Li   case TemplateArgument::TemplateExpansion:
2456*67e74705SXin Li     return false;
2457*67e74705SXin Li 
2458*67e74705SXin Li   case TemplateArgument::Type: {
2459*67e74705SXin Li     QualType Type = Arg.getAsType();
2460*67e74705SXin Li     const TemplateTypeParmType *TPT =
2461*67e74705SXin Li         Arg.getAsType()->getAs<TemplateTypeParmType>();
2462*67e74705SXin Li     return TPT && !Type.hasQualifiers() &&
2463*67e74705SXin Li            TPT->getDepth() == Depth && TPT->getIndex() == Index;
2464*67e74705SXin Li   }
2465*67e74705SXin Li 
2466*67e74705SXin Li   case TemplateArgument::Expression: {
2467*67e74705SXin Li     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2468*67e74705SXin Li     if (!DRE || !DRE->getDecl())
2469*67e74705SXin Li       return false;
2470*67e74705SXin Li     const NonTypeTemplateParmDecl *NTTP =
2471*67e74705SXin Li         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2472*67e74705SXin Li     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2473*67e74705SXin Li   }
2474*67e74705SXin Li 
2475*67e74705SXin Li   case TemplateArgument::Template:
2476*67e74705SXin Li     const TemplateTemplateParmDecl *TTP =
2477*67e74705SXin Li         dyn_cast_or_null<TemplateTemplateParmDecl>(
2478*67e74705SXin Li             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2479*67e74705SXin Li     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2480*67e74705SXin Li   }
2481*67e74705SXin Li   llvm_unreachable("unexpected kind of template argument");
2482*67e74705SXin Li }
2483*67e74705SXin Li 
isSameAsPrimaryTemplate(TemplateParameterList * Params,ArrayRef<TemplateArgument> Args)2484*67e74705SXin Li static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2485*67e74705SXin Li                                     ArrayRef<TemplateArgument> Args) {
2486*67e74705SXin Li   if (Params->size() != Args.size())
2487*67e74705SXin Li     return false;
2488*67e74705SXin Li 
2489*67e74705SXin Li   unsigned Depth = Params->getDepth();
2490*67e74705SXin Li 
2491*67e74705SXin Li   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2492*67e74705SXin Li     TemplateArgument Arg = Args[I];
2493*67e74705SXin Li 
2494*67e74705SXin Li     // If the parameter is a pack expansion, the argument must be a pack
2495*67e74705SXin Li     // whose only element is a pack expansion.
2496*67e74705SXin Li     if (Params->getParam(I)->isParameterPack()) {
2497*67e74705SXin Li       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2498*67e74705SXin Li           !Arg.pack_begin()->isPackExpansion())
2499*67e74705SXin Li         return false;
2500*67e74705SXin Li       Arg = Arg.pack_begin()->getPackExpansionPattern();
2501*67e74705SXin Li     }
2502*67e74705SXin Li 
2503*67e74705SXin Li     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2504*67e74705SXin Li       return false;
2505*67e74705SXin Li   }
2506*67e74705SXin Li 
2507*67e74705SXin Li   return true;
2508*67e74705SXin Li }
2509*67e74705SXin Li 
2510*67e74705SXin Li /// Convert the parser's template argument list representation into our form.
2511*67e74705SXin Li static TemplateArgumentListInfo
makeTemplateArgumentListInfo(Sema & S,TemplateIdAnnotation & TemplateId)2512*67e74705SXin Li makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2513*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2514*67e74705SXin Li                                         TemplateId.RAngleLoc);
2515*67e74705SXin Li   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2516*67e74705SXin Li                                      TemplateId.NumArgs);
2517*67e74705SXin Li   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2518*67e74705SXin Li   return TemplateArgs;
2519*67e74705SXin Li }
2520*67e74705SXin Li 
ActOnVarTemplateSpecialization(Scope * S,Declarator & D,TypeSourceInfo * DI,SourceLocation TemplateKWLoc,TemplateParameterList * TemplateParams,StorageClass SC,bool IsPartialSpecialization)2521*67e74705SXin Li DeclResult Sema::ActOnVarTemplateSpecialization(
2522*67e74705SXin Li     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2523*67e74705SXin Li     TemplateParameterList *TemplateParams, StorageClass SC,
2524*67e74705SXin Li     bool IsPartialSpecialization) {
2525*67e74705SXin Li   // D must be variable template id.
2526*67e74705SXin Li   assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2527*67e74705SXin Li          "Variable template specialization is declared with a template it.");
2528*67e74705SXin Li 
2529*67e74705SXin Li   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2530*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs =
2531*67e74705SXin Li       makeTemplateArgumentListInfo(*this, *TemplateId);
2532*67e74705SXin Li   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2533*67e74705SXin Li   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2534*67e74705SXin Li   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2535*67e74705SXin Li 
2536*67e74705SXin Li   TemplateName Name = TemplateId->Template.get();
2537*67e74705SXin Li 
2538*67e74705SXin Li   // The template-id must name a variable template.
2539*67e74705SXin Li   VarTemplateDecl *VarTemplate =
2540*67e74705SXin Li       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2541*67e74705SXin Li   if (!VarTemplate) {
2542*67e74705SXin Li     NamedDecl *FnTemplate;
2543*67e74705SXin Li     if (auto *OTS = Name.getAsOverloadedTemplate())
2544*67e74705SXin Li       FnTemplate = *OTS->begin();
2545*67e74705SXin Li     else
2546*67e74705SXin Li       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2547*67e74705SXin Li     if (FnTemplate)
2548*67e74705SXin Li       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2549*67e74705SXin Li                << FnTemplate->getDeclName();
2550*67e74705SXin Li     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2551*67e74705SXin Li              << IsPartialSpecialization;
2552*67e74705SXin Li   }
2553*67e74705SXin Li 
2554*67e74705SXin Li   // Check for unexpanded parameter packs in any of the template arguments.
2555*67e74705SXin Li   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2556*67e74705SXin Li     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2557*67e74705SXin Li                                         UPPC_PartialSpecialization))
2558*67e74705SXin Li       return true;
2559*67e74705SXin Li 
2560*67e74705SXin Li   // Check that the template argument list is well-formed for this
2561*67e74705SXin Li   // template.
2562*67e74705SXin Li   SmallVector<TemplateArgument, 4> Converted;
2563*67e74705SXin Li   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2564*67e74705SXin Li                                 false, Converted))
2565*67e74705SXin Li     return true;
2566*67e74705SXin Li 
2567*67e74705SXin Li   // Find the variable template (partial) specialization declaration that
2568*67e74705SXin Li   // corresponds to these arguments.
2569*67e74705SXin Li   if (IsPartialSpecialization) {
2570*67e74705SXin Li     if (CheckTemplatePartialSpecializationArgs(
2571*67e74705SXin Li             *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2572*67e74705SXin Li             TemplateArgs.size(), Converted))
2573*67e74705SXin Li       return true;
2574*67e74705SXin Li 
2575*67e74705SXin Li     bool InstantiationDependent;
2576*67e74705SXin Li     if (!Name.isDependent() &&
2577*67e74705SXin Li         !TemplateSpecializationType::anyDependentTemplateArguments(
2578*67e74705SXin Li             TemplateArgs.arguments(),
2579*67e74705SXin Li             InstantiationDependent)) {
2580*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2581*67e74705SXin Li           << VarTemplate->getDeclName();
2582*67e74705SXin Li       IsPartialSpecialization = false;
2583*67e74705SXin Li     }
2584*67e74705SXin Li 
2585*67e74705SXin Li     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2586*67e74705SXin Li                                 Converted)) {
2587*67e74705SXin Li       // C++ [temp.class.spec]p9b3:
2588*67e74705SXin Li       //
2589*67e74705SXin Li       //   -- The argument list of the specialization shall not be identical
2590*67e74705SXin Li       //      to the implicit argument list of the primary template.
2591*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2592*67e74705SXin Li         << /*variable template*/ 1
2593*67e74705SXin Li         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2594*67e74705SXin Li         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2595*67e74705SXin Li       // FIXME: Recover from this by treating the declaration as a redeclaration
2596*67e74705SXin Li       // of the primary template.
2597*67e74705SXin Li       return true;
2598*67e74705SXin Li     }
2599*67e74705SXin Li   }
2600*67e74705SXin Li 
2601*67e74705SXin Li   void *InsertPos = nullptr;
2602*67e74705SXin Li   VarTemplateSpecializationDecl *PrevDecl = nullptr;
2603*67e74705SXin Li 
2604*67e74705SXin Li   if (IsPartialSpecialization)
2605*67e74705SXin Li     // FIXME: Template parameter list matters too
2606*67e74705SXin Li     PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2607*67e74705SXin Li   else
2608*67e74705SXin Li     PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2609*67e74705SXin Li 
2610*67e74705SXin Li   VarTemplateSpecializationDecl *Specialization = nullptr;
2611*67e74705SXin Li 
2612*67e74705SXin Li   // Check whether we can declare a variable template specialization in
2613*67e74705SXin Li   // the current scope.
2614*67e74705SXin Li   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2615*67e74705SXin Li                                        TemplateNameLoc,
2616*67e74705SXin Li                                        IsPartialSpecialization))
2617*67e74705SXin Li     return true;
2618*67e74705SXin Li 
2619*67e74705SXin Li   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2620*67e74705SXin Li     // Since the only prior variable template specialization with these
2621*67e74705SXin Li     // arguments was referenced but not declared,  reuse that
2622*67e74705SXin Li     // declaration node as our own, updating its source location and
2623*67e74705SXin Li     // the list of outer template parameters to reflect our new declaration.
2624*67e74705SXin Li     Specialization = PrevDecl;
2625*67e74705SXin Li     Specialization->setLocation(TemplateNameLoc);
2626*67e74705SXin Li     PrevDecl = nullptr;
2627*67e74705SXin Li   } else if (IsPartialSpecialization) {
2628*67e74705SXin Li     // Create a new class template partial specialization declaration node.
2629*67e74705SXin Li     VarTemplatePartialSpecializationDecl *PrevPartial =
2630*67e74705SXin Li         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2631*67e74705SXin Li     VarTemplatePartialSpecializationDecl *Partial =
2632*67e74705SXin Li         VarTemplatePartialSpecializationDecl::Create(
2633*67e74705SXin Li             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2634*67e74705SXin Li             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2635*67e74705SXin Li             Converted, TemplateArgs);
2636*67e74705SXin Li 
2637*67e74705SXin Li     if (!PrevPartial)
2638*67e74705SXin Li       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2639*67e74705SXin Li     Specialization = Partial;
2640*67e74705SXin Li 
2641*67e74705SXin Li     // If we are providing an explicit specialization of a member variable
2642*67e74705SXin Li     // template specialization, make a note of that.
2643*67e74705SXin Li     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2644*67e74705SXin Li       PrevPartial->setMemberSpecialization();
2645*67e74705SXin Li 
2646*67e74705SXin Li     // Check that all of the template parameters of the variable template
2647*67e74705SXin Li     // partial specialization are deducible from the template
2648*67e74705SXin Li     // arguments. If not, this variable template partial specialization
2649*67e74705SXin Li     // will never be used.
2650*67e74705SXin Li     llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2651*67e74705SXin Li     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2652*67e74705SXin Li                                TemplateParams->getDepth(), DeducibleParams);
2653*67e74705SXin Li 
2654*67e74705SXin Li     if (!DeducibleParams.all()) {
2655*67e74705SXin Li       unsigned NumNonDeducible =
2656*67e74705SXin Li           DeducibleParams.size() - DeducibleParams.count();
2657*67e74705SXin Li       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2658*67e74705SXin Li         << /*variable template*/ 1 << (NumNonDeducible > 1)
2659*67e74705SXin Li         << SourceRange(TemplateNameLoc, RAngleLoc);
2660*67e74705SXin Li       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2661*67e74705SXin Li         if (!DeducibleParams[I]) {
2662*67e74705SXin Li           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2663*67e74705SXin Li           if (Param->getDeclName())
2664*67e74705SXin Li             Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2665*67e74705SXin Li                 << Param->getDeclName();
2666*67e74705SXin Li           else
2667*67e74705SXin Li             Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2668*67e74705SXin Li                 << "(anonymous)";
2669*67e74705SXin Li         }
2670*67e74705SXin Li       }
2671*67e74705SXin Li     }
2672*67e74705SXin Li   } else {
2673*67e74705SXin Li     // Create a new class template specialization declaration node for
2674*67e74705SXin Li     // this explicit specialization or friend declaration.
2675*67e74705SXin Li     Specialization = VarTemplateSpecializationDecl::Create(
2676*67e74705SXin Li         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2677*67e74705SXin Li         VarTemplate, DI->getType(), DI, SC, Converted);
2678*67e74705SXin Li     Specialization->setTemplateArgsInfo(TemplateArgs);
2679*67e74705SXin Li 
2680*67e74705SXin Li     if (!PrevDecl)
2681*67e74705SXin Li       VarTemplate->AddSpecialization(Specialization, InsertPos);
2682*67e74705SXin Li   }
2683*67e74705SXin Li 
2684*67e74705SXin Li   // C++ [temp.expl.spec]p6:
2685*67e74705SXin Li   //   If a template, a member template or the member of a class template is
2686*67e74705SXin Li   //   explicitly specialized then that specialization shall be declared
2687*67e74705SXin Li   //   before the first use of that specialization that would cause an implicit
2688*67e74705SXin Li   //   instantiation to take place, in every translation unit in which such a
2689*67e74705SXin Li   //   use occurs; no diagnostic is required.
2690*67e74705SXin Li   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2691*67e74705SXin Li     bool Okay = false;
2692*67e74705SXin Li     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2693*67e74705SXin Li       // Is there any previous explicit specialization declaration?
2694*67e74705SXin Li       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2695*67e74705SXin Li         Okay = true;
2696*67e74705SXin Li         break;
2697*67e74705SXin Li       }
2698*67e74705SXin Li     }
2699*67e74705SXin Li 
2700*67e74705SXin Li     if (!Okay) {
2701*67e74705SXin Li       SourceRange Range(TemplateNameLoc, RAngleLoc);
2702*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2703*67e74705SXin Li           << Name << Range;
2704*67e74705SXin Li 
2705*67e74705SXin Li       Diag(PrevDecl->getPointOfInstantiation(),
2706*67e74705SXin Li            diag::note_instantiation_required_here)
2707*67e74705SXin Li           << (PrevDecl->getTemplateSpecializationKind() !=
2708*67e74705SXin Li               TSK_ImplicitInstantiation);
2709*67e74705SXin Li       return true;
2710*67e74705SXin Li     }
2711*67e74705SXin Li   }
2712*67e74705SXin Li 
2713*67e74705SXin Li   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2714*67e74705SXin Li   Specialization->setLexicalDeclContext(CurContext);
2715*67e74705SXin Li 
2716*67e74705SXin Li   // Add the specialization into its lexical context, so that it can
2717*67e74705SXin Li   // be seen when iterating through the list of declarations in that
2718*67e74705SXin Li   // context. However, specializations are not found by name lookup.
2719*67e74705SXin Li   CurContext->addDecl(Specialization);
2720*67e74705SXin Li 
2721*67e74705SXin Li   // Note that this is an explicit specialization.
2722*67e74705SXin Li   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2723*67e74705SXin Li 
2724*67e74705SXin Li   if (PrevDecl) {
2725*67e74705SXin Li     // Check that this isn't a redefinition of this specialization,
2726*67e74705SXin Li     // merging with previous declarations.
2727*67e74705SXin Li     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2728*67e74705SXin Li                           ForRedeclaration);
2729*67e74705SXin Li     PrevSpec.addDecl(PrevDecl);
2730*67e74705SXin Li     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2731*67e74705SXin Li   } else if (Specialization->isStaticDataMember() &&
2732*67e74705SXin Li              Specialization->isOutOfLine()) {
2733*67e74705SXin Li     Specialization->setAccess(VarTemplate->getAccess());
2734*67e74705SXin Li   }
2735*67e74705SXin Li 
2736*67e74705SXin Li   // Link instantiations of static data members back to the template from
2737*67e74705SXin Li   // which they were instantiated.
2738*67e74705SXin Li   if (Specialization->isStaticDataMember())
2739*67e74705SXin Li     Specialization->setInstantiationOfStaticDataMember(
2740*67e74705SXin Li         VarTemplate->getTemplatedDecl(),
2741*67e74705SXin Li         Specialization->getSpecializationKind());
2742*67e74705SXin Li 
2743*67e74705SXin Li   return Specialization;
2744*67e74705SXin Li }
2745*67e74705SXin Li 
2746*67e74705SXin Li namespace {
2747*67e74705SXin Li /// \brief A partial specialization whose template arguments have matched
2748*67e74705SXin Li /// a given template-id.
2749*67e74705SXin Li struct PartialSpecMatchResult {
2750*67e74705SXin Li   VarTemplatePartialSpecializationDecl *Partial;
2751*67e74705SXin Li   TemplateArgumentList *Args;
2752*67e74705SXin Li };
2753*67e74705SXin Li } // end anonymous namespace
2754*67e74705SXin Li 
2755*67e74705SXin Li DeclResult
CheckVarTemplateId(VarTemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation TemplateNameLoc,const TemplateArgumentListInfo & TemplateArgs)2756*67e74705SXin Li Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2757*67e74705SXin Li                          SourceLocation TemplateNameLoc,
2758*67e74705SXin Li                          const TemplateArgumentListInfo &TemplateArgs) {
2759*67e74705SXin Li   assert(Template && "A variable template id without template?");
2760*67e74705SXin Li 
2761*67e74705SXin Li   // Check that the template argument list is well-formed for this template.
2762*67e74705SXin Li   SmallVector<TemplateArgument, 4> Converted;
2763*67e74705SXin Li   if (CheckTemplateArgumentList(
2764*67e74705SXin Li           Template, TemplateNameLoc,
2765*67e74705SXin Li           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2766*67e74705SXin Li           Converted))
2767*67e74705SXin Li     return true;
2768*67e74705SXin Li 
2769*67e74705SXin Li   // Find the variable template specialization declaration that
2770*67e74705SXin Li   // corresponds to these arguments.
2771*67e74705SXin Li   void *InsertPos = nullptr;
2772*67e74705SXin Li   if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2773*67e74705SXin Li           Converted, InsertPos)) {
2774*67e74705SXin Li     checkSpecializationVisibility(TemplateNameLoc, Spec);
2775*67e74705SXin Li     // If we already have a variable template specialization, return it.
2776*67e74705SXin Li     return Spec;
2777*67e74705SXin Li   }
2778*67e74705SXin Li 
2779*67e74705SXin Li   // This is the first time we have referenced this variable template
2780*67e74705SXin Li   // specialization. Create the canonical declaration and add it to
2781*67e74705SXin Li   // the set of specializations, based on the closest partial specialization
2782*67e74705SXin Li   // that it represents. That is,
2783*67e74705SXin Li   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2784*67e74705SXin Li   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2785*67e74705SXin Li                                        Converted);
2786*67e74705SXin Li   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2787*67e74705SXin Li   bool AmbiguousPartialSpec = false;
2788*67e74705SXin Li   typedef PartialSpecMatchResult MatchResult;
2789*67e74705SXin Li   SmallVector<MatchResult, 4> Matched;
2790*67e74705SXin Li   SourceLocation PointOfInstantiation = TemplateNameLoc;
2791*67e74705SXin Li   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2792*67e74705SXin Li                                             /*ForTakingAddress=*/false);
2793*67e74705SXin Li 
2794*67e74705SXin Li   // 1. Attempt to find the closest partial specialization that this
2795*67e74705SXin Li   // specializes, if any.
2796*67e74705SXin Li   // If any of the template arguments is dependent, then this is probably
2797*67e74705SXin Li   // a placeholder for an incomplete declarative context; which must be
2798*67e74705SXin Li   // complete by instantiation time. Thus, do not search through the partial
2799*67e74705SXin Li   // specializations yet.
2800*67e74705SXin Li   // TODO: Unify with InstantiateClassTemplateSpecialization()?
2801*67e74705SXin Li   //       Perhaps better after unification of DeduceTemplateArguments() and
2802*67e74705SXin Li   //       getMoreSpecializedPartialSpecialization().
2803*67e74705SXin Li   bool InstantiationDependent = false;
2804*67e74705SXin Li   if (!TemplateSpecializationType::anyDependentTemplateArguments(
2805*67e74705SXin Li           TemplateArgs, InstantiationDependent)) {
2806*67e74705SXin Li 
2807*67e74705SXin Li     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2808*67e74705SXin Li     Template->getPartialSpecializations(PartialSpecs);
2809*67e74705SXin Li 
2810*67e74705SXin Li     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2811*67e74705SXin Li       VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2812*67e74705SXin Li       TemplateDeductionInfo Info(FailedCandidates.getLocation());
2813*67e74705SXin Li 
2814*67e74705SXin Li       if (TemplateDeductionResult Result =
2815*67e74705SXin Li               DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2816*67e74705SXin Li         // Store the failed-deduction information for use in diagnostics, later.
2817*67e74705SXin Li         // TODO: Actually use the failed-deduction info?
2818*67e74705SXin Li         FailedCandidates.addCandidate().set(
2819*67e74705SXin Li             DeclAccessPair::make(Template, AS_public), Partial,
2820*67e74705SXin Li             MakeDeductionFailureInfo(Context, Result, Info));
2821*67e74705SXin Li         (void)Result;
2822*67e74705SXin Li       } else {
2823*67e74705SXin Li         Matched.push_back(PartialSpecMatchResult());
2824*67e74705SXin Li         Matched.back().Partial = Partial;
2825*67e74705SXin Li         Matched.back().Args = Info.take();
2826*67e74705SXin Li       }
2827*67e74705SXin Li     }
2828*67e74705SXin Li 
2829*67e74705SXin Li     if (Matched.size() >= 1) {
2830*67e74705SXin Li       SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2831*67e74705SXin Li       if (Matched.size() == 1) {
2832*67e74705SXin Li         //   -- If exactly one matching specialization is found, the
2833*67e74705SXin Li         //      instantiation is generated from that specialization.
2834*67e74705SXin Li         // We don't need to do anything for this.
2835*67e74705SXin Li       } else {
2836*67e74705SXin Li         //   -- If more than one matching specialization is found, the
2837*67e74705SXin Li         //      partial order rules (14.5.4.2) are used to determine
2838*67e74705SXin Li         //      whether one of the specializations is more specialized
2839*67e74705SXin Li         //      than the others. If none of the specializations is more
2840*67e74705SXin Li         //      specialized than all of the other matching
2841*67e74705SXin Li         //      specializations, then the use of the variable template is
2842*67e74705SXin Li         //      ambiguous and the program is ill-formed.
2843*67e74705SXin Li         for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2844*67e74705SXin Li                                                    PEnd = Matched.end();
2845*67e74705SXin Li              P != PEnd; ++P) {
2846*67e74705SXin Li           if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2847*67e74705SXin Li                                                       PointOfInstantiation) ==
2848*67e74705SXin Li               P->Partial)
2849*67e74705SXin Li             Best = P;
2850*67e74705SXin Li         }
2851*67e74705SXin Li 
2852*67e74705SXin Li         // Determine if the best partial specialization is more specialized than
2853*67e74705SXin Li         // the others.
2854*67e74705SXin Li         for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2855*67e74705SXin Li                                                    PEnd = Matched.end();
2856*67e74705SXin Li              P != PEnd; ++P) {
2857*67e74705SXin Li           if (P != Best && getMoreSpecializedPartialSpecialization(
2858*67e74705SXin Li                                P->Partial, Best->Partial,
2859*67e74705SXin Li                                PointOfInstantiation) != Best->Partial) {
2860*67e74705SXin Li             AmbiguousPartialSpec = true;
2861*67e74705SXin Li             break;
2862*67e74705SXin Li           }
2863*67e74705SXin Li         }
2864*67e74705SXin Li       }
2865*67e74705SXin Li 
2866*67e74705SXin Li       // Instantiate using the best variable template partial specialization.
2867*67e74705SXin Li       InstantiationPattern = Best->Partial;
2868*67e74705SXin Li       InstantiationArgs = Best->Args;
2869*67e74705SXin Li     } else {
2870*67e74705SXin Li       //   -- If no match is found, the instantiation is generated
2871*67e74705SXin Li       //      from the primary template.
2872*67e74705SXin Li       // InstantiationPattern = Template->getTemplatedDecl();
2873*67e74705SXin Li     }
2874*67e74705SXin Li   }
2875*67e74705SXin Li 
2876*67e74705SXin Li   // 2. Create the canonical declaration.
2877*67e74705SXin Li   // Note that we do not instantiate a definition until we see an odr-use
2878*67e74705SXin Li   // in DoMarkVarDeclReferenced().
2879*67e74705SXin Li   // FIXME: LateAttrs et al.?
2880*67e74705SXin Li   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2881*67e74705SXin Li       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2882*67e74705SXin Li       Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2883*67e74705SXin Li   if (!Decl)
2884*67e74705SXin Li     return true;
2885*67e74705SXin Li 
2886*67e74705SXin Li   if (AmbiguousPartialSpec) {
2887*67e74705SXin Li     // Partial ordering did not produce a clear winner. Complain.
2888*67e74705SXin Li     Decl->setInvalidDecl();
2889*67e74705SXin Li     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2890*67e74705SXin Li         << Decl;
2891*67e74705SXin Li 
2892*67e74705SXin Li     // Print the matching partial specializations.
2893*67e74705SXin Li     for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2894*67e74705SXin Li                                                PEnd = Matched.end();
2895*67e74705SXin Li          P != PEnd; ++P)
2896*67e74705SXin Li       Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2897*67e74705SXin Li           << getTemplateArgumentBindingsText(
2898*67e74705SXin Li                  P->Partial->getTemplateParameters(), *P->Args);
2899*67e74705SXin Li     return true;
2900*67e74705SXin Li   }
2901*67e74705SXin Li 
2902*67e74705SXin Li   if (VarTemplatePartialSpecializationDecl *D =
2903*67e74705SXin Li           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2904*67e74705SXin Li     Decl->setInstantiationOf(D, InstantiationArgs);
2905*67e74705SXin Li 
2906*67e74705SXin Li   checkSpecializationVisibility(TemplateNameLoc, Decl);
2907*67e74705SXin Li 
2908*67e74705SXin Li   assert(Decl && "No variable template specialization?");
2909*67e74705SXin Li   return Decl;
2910*67e74705SXin Li }
2911*67e74705SXin Li 
2912*67e74705SXin Li ExprResult
CheckVarTemplateId(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,VarTemplateDecl * Template,SourceLocation TemplateLoc,const TemplateArgumentListInfo * TemplateArgs)2913*67e74705SXin Li Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2914*67e74705SXin Li                          const DeclarationNameInfo &NameInfo,
2915*67e74705SXin Li                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
2916*67e74705SXin Li                          const TemplateArgumentListInfo *TemplateArgs) {
2917*67e74705SXin Li 
2918*67e74705SXin Li   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2919*67e74705SXin Li                                        *TemplateArgs);
2920*67e74705SXin Li   if (Decl.isInvalid())
2921*67e74705SXin Li     return ExprError();
2922*67e74705SXin Li 
2923*67e74705SXin Li   VarDecl *Var = cast<VarDecl>(Decl.get());
2924*67e74705SXin Li   if (!Var->getTemplateSpecializationKind())
2925*67e74705SXin Li     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2926*67e74705SXin Li                                        NameInfo.getLoc());
2927*67e74705SXin Li 
2928*67e74705SXin Li   // Build an ordinary singleton decl ref.
2929*67e74705SXin Li   return BuildDeclarationNameExpr(SS, NameInfo, Var,
2930*67e74705SXin Li                                   /*FoundD=*/nullptr, TemplateArgs);
2931*67e74705SXin Li }
2932*67e74705SXin Li 
BuildTemplateIdExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,bool RequiresADL,const TemplateArgumentListInfo * TemplateArgs)2933*67e74705SXin Li ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2934*67e74705SXin Li                                      SourceLocation TemplateKWLoc,
2935*67e74705SXin Li                                      LookupResult &R,
2936*67e74705SXin Li                                      bool RequiresADL,
2937*67e74705SXin Li                                  const TemplateArgumentListInfo *TemplateArgs) {
2938*67e74705SXin Li   // FIXME: Can we do any checking at this point? I guess we could check the
2939*67e74705SXin Li   // template arguments that we have against the template name, if the template
2940*67e74705SXin Li   // name refers to a single template. That's not a terribly common case,
2941*67e74705SXin Li   // though.
2942*67e74705SXin Li   // foo<int> could identify a single function unambiguously
2943*67e74705SXin Li   // This approach does NOT work, since f<int>(1);
2944*67e74705SXin Li   // gets resolved prior to resorting to overload resolution
2945*67e74705SXin Li   // i.e., template<class T> void f(double);
2946*67e74705SXin Li   //       vs template<class T, class U> void f(U);
2947*67e74705SXin Li 
2948*67e74705SXin Li   // These should be filtered out by our callers.
2949*67e74705SXin Li   assert(!R.empty() && "empty lookup results when building templateid");
2950*67e74705SXin Li   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2951*67e74705SXin Li 
2952*67e74705SXin Li   // In C++1y, check variable template ids.
2953*67e74705SXin Li   bool InstantiationDependent;
2954*67e74705SXin Li   if (R.getAsSingle<VarTemplateDecl>() &&
2955*67e74705SXin Li       !TemplateSpecializationType::anyDependentTemplateArguments(
2956*67e74705SXin Li            *TemplateArgs, InstantiationDependent)) {
2957*67e74705SXin Li     return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2958*67e74705SXin Li                               R.getAsSingle<VarTemplateDecl>(),
2959*67e74705SXin Li                               TemplateKWLoc, TemplateArgs);
2960*67e74705SXin Li   }
2961*67e74705SXin Li 
2962*67e74705SXin Li   // We don't want lookup warnings at this point.
2963*67e74705SXin Li   R.suppressDiagnostics();
2964*67e74705SXin Li 
2965*67e74705SXin Li   UnresolvedLookupExpr *ULE
2966*67e74705SXin Li     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2967*67e74705SXin Li                                    SS.getWithLocInContext(Context),
2968*67e74705SXin Li                                    TemplateKWLoc,
2969*67e74705SXin Li                                    R.getLookupNameInfo(),
2970*67e74705SXin Li                                    RequiresADL, TemplateArgs,
2971*67e74705SXin Li                                    R.begin(), R.end());
2972*67e74705SXin Li 
2973*67e74705SXin Li   return ULE;
2974*67e74705SXin Li }
2975*67e74705SXin Li 
2976*67e74705SXin Li // We actually only call this from template instantiation.
2977*67e74705SXin Li ExprResult
BuildQualifiedTemplateIdExpr(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)2978*67e74705SXin Li Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2979*67e74705SXin Li                                    SourceLocation TemplateKWLoc,
2980*67e74705SXin Li                                    const DeclarationNameInfo &NameInfo,
2981*67e74705SXin Li                              const TemplateArgumentListInfo *TemplateArgs) {
2982*67e74705SXin Li 
2983*67e74705SXin Li   assert(TemplateArgs || TemplateKWLoc.isValid());
2984*67e74705SXin Li   DeclContext *DC;
2985*67e74705SXin Li   if (!(DC = computeDeclContext(SS, false)) ||
2986*67e74705SXin Li       DC->isDependentContext() ||
2987*67e74705SXin Li       RequireCompleteDeclContext(SS, DC))
2988*67e74705SXin Li     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2989*67e74705SXin Li 
2990*67e74705SXin Li   bool MemberOfUnknownSpecialization;
2991*67e74705SXin Li   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2992*67e74705SXin Li   LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2993*67e74705SXin Li                      MemberOfUnknownSpecialization);
2994*67e74705SXin Li 
2995*67e74705SXin Li   if (R.isAmbiguous())
2996*67e74705SXin Li     return ExprError();
2997*67e74705SXin Li 
2998*67e74705SXin Li   if (R.empty()) {
2999*67e74705SXin Li     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3000*67e74705SXin Li       << NameInfo.getName() << SS.getRange();
3001*67e74705SXin Li     return ExprError();
3002*67e74705SXin Li   }
3003*67e74705SXin Li 
3004*67e74705SXin Li   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3005*67e74705SXin Li     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3006*67e74705SXin Li       << SS.getScopeRep()
3007*67e74705SXin Li       << NameInfo.getName().getAsString() << SS.getRange();
3008*67e74705SXin Li     Diag(Temp->getLocation(), diag::note_referenced_class_template);
3009*67e74705SXin Li     return ExprError();
3010*67e74705SXin Li   }
3011*67e74705SXin Li 
3012*67e74705SXin Li   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3013*67e74705SXin Li }
3014*67e74705SXin Li 
3015*67e74705SXin Li /// \brief Form a dependent template name.
3016*67e74705SXin Li ///
3017*67e74705SXin Li /// This action forms a dependent template name given the template
3018*67e74705SXin Li /// name and its (presumably dependent) scope specifier. For
3019*67e74705SXin Li /// example, given "MetaFun::template apply", the scope specifier \p
3020*67e74705SXin Li /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3021*67e74705SXin Li /// of the "template" keyword, and "apply" is the \p Name.
ActOnDependentTemplateName(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Name,ParsedType ObjectType,bool EnteringContext,TemplateTy & Result)3022*67e74705SXin Li TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3023*67e74705SXin Li                                                   CXXScopeSpec &SS,
3024*67e74705SXin Li                                                   SourceLocation TemplateKWLoc,
3025*67e74705SXin Li                                                   UnqualifiedId &Name,
3026*67e74705SXin Li                                                   ParsedType ObjectType,
3027*67e74705SXin Li                                                   bool EnteringContext,
3028*67e74705SXin Li                                                   TemplateTy &Result) {
3029*67e74705SXin Li   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3030*67e74705SXin Li     Diag(TemplateKWLoc,
3031*67e74705SXin Li          getLangOpts().CPlusPlus11 ?
3032*67e74705SXin Li            diag::warn_cxx98_compat_template_outside_of_template :
3033*67e74705SXin Li            diag::ext_template_outside_of_template)
3034*67e74705SXin Li       << FixItHint::CreateRemoval(TemplateKWLoc);
3035*67e74705SXin Li 
3036*67e74705SXin Li   DeclContext *LookupCtx = nullptr;
3037*67e74705SXin Li   if (SS.isSet())
3038*67e74705SXin Li     LookupCtx = computeDeclContext(SS, EnteringContext);
3039*67e74705SXin Li   if (!LookupCtx && ObjectType)
3040*67e74705SXin Li     LookupCtx = computeDeclContext(ObjectType.get());
3041*67e74705SXin Li   if (LookupCtx) {
3042*67e74705SXin Li     // C++0x [temp.names]p5:
3043*67e74705SXin Li     //   If a name prefixed by the keyword template is not the name of
3044*67e74705SXin Li     //   a template, the program is ill-formed. [Note: the keyword
3045*67e74705SXin Li     //   template may not be applied to non-template members of class
3046*67e74705SXin Li     //   templates. -end note ] [ Note: as is the case with the
3047*67e74705SXin Li     //   typename prefix, the template prefix is allowed in cases
3048*67e74705SXin Li     //   where it is not strictly necessary; i.e., when the
3049*67e74705SXin Li     //   nested-name-specifier or the expression on the left of the ->
3050*67e74705SXin Li     //   or . is not dependent on a template-parameter, or the use
3051*67e74705SXin Li     //   does not appear in the scope of a template. -end note]
3052*67e74705SXin Li     //
3053*67e74705SXin Li     // Note: C++03 was more strict here, because it banned the use of
3054*67e74705SXin Li     // the "template" keyword prior to a template-name that was not a
3055*67e74705SXin Li     // dependent name. C++ DR468 relaxed this requirement (the
3056*67e74705SXin Li     // "template" keyword is now permitted). We follow the C++0x
3057*67e74705SXin Li     // rules, even in C++03 mode with a warning, retroactively applying the DR.
3058*67e74705SXin Li     bool MemberOfUnknownSpecialization;
3059*67e74705SXin Li     TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3060*67e74705SXin Li                                           ObjectType, EnteringContext, Result,
3061*67e74705SXin Li                                           MemberOfUnknownSpecialization);
3062*67e74705SXin Li     if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3063*67e74705SXin Li         isa<CXXRecordDecl>(LookupCtx) &&
3064*67e74705SXin Li         (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3065*67e74705SXin Li          cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3066*67e74705SXin Li       // This is a dependent template. Handle it below.
3067*67e74705SXin Li     } else if (TNK == TNK_Non_template) {
3068*67e74705SXin Li       Diag(Name.getLocStart(),
3069*67e74705SXin Li            diag::err_template_kw_refers_to_non_template)
3070*67e74705SXin Li         << GetNameFromUnqualifiedId(Name).getName()
3071*67e74705SXin Li         << Name.getSourceRange()
3072*67e74705SXin Li         << TemplateKWLoc;
3073*67e74705SXin Li       return TNK_Non_template;
3074*67e74705SXin Li     } else {
3075*67e74705SXin Li       // We found something; return it.
3076*67e74705SXin Li       return TNK;
3077*67e74705SXin Li     }
3078*67e74705SXin Li   }
3079*67e74705SXin Li 
3080*67e74705SXin Li   NestedNameSpecifier *Qualifier = SS.getScopeRep();
3081*67e74705SXin Li 
3082*67e74705SXin Li   switch (Name.getKind()) {
3083*67e74705SXin Li   case UnqualifiedId::IK_Identifier:
3084*67e74705SXin Li     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3085*67e74705SXin Li                                                               Name.Identifier));
3086*67e74705SXin Li     return TNK_Dependent_template_name;
3087*67e74705SXin Li 
3088*67e74705SXin Li   case UnqualifiedId::IK_OperatorFunctionId:
3089*67e74705SXin Li     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3090*67e74705SXin Li                                              Name.OperatorFunctionId.Operator));
3091*67e74705SXin Li     return TNK_Function_template;
3092*67e74705SXin Li 
3093*67e74705SXin Li   case UnqualifiedId::IK_LiteralOperatorId:
3094*67e74705SXin Li     llvm_unreachable("literal operator id cannot have a dependent scope");
3095*67e74705SXin Li 
3096*67e74705SXin Li   default:
3097*67e74705SXin Li     break;
3098*67e74705SXin Li   }
3099*67e74705SXin Li 
3100*67e74705SXin Li   Diag(Name.getLocStart(),
3101*67e74705SXin Li        diag::err_template_kw_refers_to_non_template)
3102*67e74705SXin Li     << GetNameFromUnqualifiedId(Name).getName()
3103*67e74705SXin Li     << Name.getSourceRange()
3104*67e74705SXin Li     << TemplateKWLoc;
3105*67e74705SXin Li   return TNK_Non_template;
3106*67e74705SXin Li }
3107*67e74705SXin Li 
CheckTemplateTypeArgument(TemplateTypeParmDecl * Param,TemplateArgumentLoc & AL,SmallVectorImpl<TemplateArgument> & Converted)3108*67e74705SXin Li bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3109*67e74705SXin Li                                      TemplateArgumentLoc &AL,
3110*67e74705SXin Li                           SmallVectorImpl<TemplateArgument> &Converted) {
3111*67e74705SXin Li   const TemplateArgument &Arg = AL.getArgument();
3112*67e74705SXin Li   QualType ArgType;
3113*67e74705SXin Li   TypeSourceInfo *TSI = nullptr;
3114*67e74705SXin Li 
3115*67e74705SXin Li   // Check template type parameter.
3116*67e74705SXin Li   switch(Arg.getKind()) {
3117*67e74705SXin Li   case TemplateArgument::Type:
3118*67e74705SXin Li     // C++ [temp.arg.type]p1:
3119*67e74705SXin Li     //   A template-argument for a template-parameter which is a
3120*67e74705SXin Li     //   type shall be a type-id.
3121*67e74705SXin Li     ArgType = Arg.getAsType();
3122*67e74705SXin Li     TSI = AL.getTypeSourceInfo();
3123*67e74705SXin Li     break;
3124*67e74705SXin Li   case TemplateArgument::Template: {
3125*67e74705SXin Li     // We have a template type parameter but the template argument
3126*67e74705SXin Li     // is a template without any arguments.
3127*67e74705SXin Li     SourceRange SR = AL.getSourceRange();
3128*67e74705SXin Li     TemplateName Name = Arg.getAsTemplate();
3129*67e74705SXin Li     Diag(SR.getBegin(), diag::err_template_missing_args)
3130*67e74705SXin Li       << Name << SR;
3131*67e74705SXin Li     if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3132*67e74705SXin Li       Diag(Decl->getLocation(), diag::note_template_decl_here);
3133*67e74705SXin Li 
3134*67e74705SXin Li     return true;
3135*67e74705SXin Li   }
3136*67e74705SXin Li   case TemplateArgument::Expression: {
3137*67e74705SXin Li     // We have a template type parameter but the template argument is an
3138*67e74705SXin Li     // expression; see if maybe it is missing the "typename" keyword.
3139*67e74705SXin Li     CXXScopeSpec SS;
3140*67e74705SXin Li     DeclarationNameInfo NameInfo;
3141*67e74705SXin Li 
3142*67e74705SXin Li     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3143*67e74705SXin Li       SS.Adopt(ArgExpr->getQualifierLoc());
3144*67e74705SXin Li       NameInfo = ArgExpr->getNameInfo();
3145*67e74705SXin Li     } else if (DependentScopeDeclRefExpr *ArgExpr =
3146*67e74705SXin Li                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3147*67e74705SXin Li       SS.Adopt(ArgExpr->getQualifierLoc());
3148*67e74705SXin Li       NameInfo = ArgExpr->getNameInfo();
3149*67e74705SXin Li     } else if (CXXDependentScopeMemberExpr *ArgExpr =
3150*67e74705SXin Li                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3151*67e74705SXin Li       if (ArgExpr->isImplicitAccess()) {
3152*67e74705SXin Li         SS.Adopt(ArgExpr->getQualifierLoc());
3153*67e74705SXin Li         NameInfo = ArgExpr->getMemberNameInfo();
3154*67e74705SXin Li       }
3155*67e74705SXin Li     }
3156*67e74705SXin Li 
3157*67e74705SXin Li     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3158*67e74705SXin Li       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3159*67e74705SXin Li       LookupParsedName(Result, CurScope, &SS);
3160*67e74705SXin Li 
3161*67e74705SXin Li       if (Result.getAsSingle<TypeDecl>() ||
3162*67e74705SXin Li           Result.getResultKind() ==
3163*67e74705SXin Li               LookupResult::NotFoundInCurrentInstantiation) {
3164*67e74705SXin Li         // Suggest that the user add 'typename' before the NNS.
3165*67e74705SXin Li         SourceLocation Loc = AL.getSourceRange().getBegin();
3166*67e74705SXin Li         Diag(Loc, getLangOpts().MSVCCompat
3167*67e74705SXin Li                       ? diag::ext_ms_template_type_arg_missing_typename
3168*67e74705SXin Li                       : diag::err_template_arg_must_be_type_suggest)
3169*67e74705SXin Li             << FixItHint::CreateInsertion(Loc, "typename ");
3170*67e74705SXin Li         Diag(Param->getLocation(), diag::note_template_param_here);
3171*67e74705SXin Li 
3172*67e74705SXin Li         // Recover by synthesizing a type using the location information that we
3173*67e74705SXin Li         // already have.
3174*67e74705SXin Li         ArgType =
3175*67e74705SXin Li             Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3176*67e74705SXin Li         TypeLocBuilder TLB;
3177*67e74705SXin Li         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3178*67e74705SXin Li         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3179*67e74705SXin Li         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3180*67e74705SXin Li         TL.setNameLoc(NameInfo.getLoc());
3181*67e74705SXin Li         TSI = TLB.getTypeSourceInfo(Context, ArgType);
3182*67e74705SXin Li 
3183*67e74705SXin Li         // Overwrite our input TemplateArgumentLoc so that we can recover
3184*67e74705SXin Li         // properly.
3185*67e74705SXin Li         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3186*67e74705SXin Li                                  TemplateArgumentLocInfo(TSI));
3187*67e74705SXin Li 
3188*67e74705SXin Li         break;
3189*67e74705SXin Li       }
3190*67e74705SXin Li     }
3191*67e74705SXin Li     // fallthrough
3192*67e74705SXin Li   }
3193*67e74705SXin Li   default: {
3194*67e74705SXin Li     // We have a template type parameter but the template argument
3195*67e74705SXin Li     // is not a type.
3196*67e74705SXin Li     SourceRange SR = AL.getSourceRange();
3197*67e74705SXin Li     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3198*67e74705SXin Li     Diag(Param->getLocation(), diag::note_template_param_here);
3199*67e74705SXin Li 
3200*67e74705SXin Li     return true;
3201*67e74705SXin Li   }
3202*67e74705SXin Li   }
3203*67e74705SXin Li 
3204*67e74705SXin Li   if (CheckTemplateArgument(Param, TSI))
3205*67e74705SXin Li     return true;
3206*67e74705SXin Li 
3207*67e74705SXin Li   // Add the converted template type argument.
3208*67e74705SXin Li   ArgType = Context.getCanonicalType(ArgType);
3209*67e74705SXin Li 
3210*67e74705SXin Li   // Objective-C ARC:
3211*67e74705SXin Li   //   If an explicitly-specified template argument type is a lifetime type
3212*67e74705SXin Li   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3213*67e74705SXin Li   if (getLangOpts().ObjCAutoRefCount &&
3214*67e74705SXin Li       ArgType->isObjCLifetimeType() &&
3215*67e74705SXin Li       !ArgType.getObjCLifetime()) {
3216*67e74705SXin Li     Qualifiers Qs;
3217*67e74705SXin Li     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3218*67e74705SXin Li     ArgType = Context.getQualifiedType(ArgType, Qs);
3219*67e74705SXin Li   }
3220*67e74705SXin Li 
3221*67e74705SXin Li   Converted.push_back(TemplateArgument(ArgType));
3222*67e74705SXin Li   return false;
3223*67e74705SXin Li }
3224*67e74705SXin Li 
3225*67e74705SXin Li /// \brief Substitute template arguments into the default template argument for
3226*67e74705SXin Li /// the given template type parameter.
3227*67e74705SXin Li ///
3228*67e74705SXin Li /// \param SemaRef the semantic analysis object for which we are performing
3229*67e74705SXin Li /// the substitution.
3230*67e74705SXin Li ///
3231*67e74705SXin Li /// \param Template the template that we are synthesizing template arguments
3232*67e74705SXin Li /// for.
3233*67e74705SXin Li ///
3234*67e74705SXin Li /// \param TemplateLoc the location of the template name that started the
3235*67e74705SXin Li /// template-id we are checking.
3236*67e74705SXin Li ///
3237*67e74705SXin Li /// \param RAngleLoc the location of the right angle bracket ('>') that
3238*67e74705SXin Li /// terminates the template-id.
3239*67e74705SXin Li ///
3240*67e74705SXin Li /// \param Param the template template parameter whose default we are
3241*67e74705SXin Li /// substituting into.
3242*67e74705SXin Li ///
3243*67e74705SXin Li /// \param Converted the list of template arguments provided for template
3244*67e74705SXin Li /// parameters that precede \p Param in the template parameter list.
3245*67e74705SXin Li /// \returns the substituted template argument, or NULL if an error occurred.
3246*67e74705SXin Li static TypeSourceInfo *
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTypeParmDecl * Param,SmallVectorImpl<TemplateArgument> & Converted)3247*67e74705SXin Li SubstDefaultTemplateArgument(Sema &SemaRef,
3248*67e74705SXin Li                              TemplateDecl *Template,
3249*67e74705SXin Li                              SourceLocation TemplateLoc,
3250*67e74705SXin Li                              SourceLocation RAngleLoc,
3251*67e74705SXin Li                              TemplateTypeParmDecl *Param,
3252*67e74705SXin Li                          SmallVectorImpl<TemplateArgument> &Converted) {
3253*67e74705SXin Li   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3254*67e74705SXin Li 
3255*67e74705SXin Li   // If the argument type is dependent, instantiate it now based
3256*67e74705SXin Li   // on the previously-computed template arguments.
3257*67e74705SXin Li   if (ArgType->getType()->isDependentType()) {
3258*67e74705SXin Li     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3259*67e74705SXin Li                                      Template, Converted,
3260*67e74705SXin Li                                      SourceRange(TemplateLoc, RAngleLoc));
3261*67e74705SXin Li     if (Inst.isInvalid())
3262*67e74705SXin Li       return nullptr;
3263*67e74705SXin Li 
3264*67e74705SXin Li     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
3265*67e74705SXin Li 
3266*67e74705SXin Li     // Only substitute for the innermost template argument list.
3267*67e74705SXin Li     MultiLevelTemplateArgumentList TemplateArgLists;
3268*67e74705SXin Li     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3269*67e74705SXin Li     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3270*67e74705SXin Li       TemplateArgLists.addOuterTemplateArguments(None);
3271*67e74705SXin Li 
3272*67e74705SXin Li     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3273*67e74705SXin Li     ArgType =
3274*67e74705SXin Li         SemaRef.SubstType(ArgType, TemplateArgLists,
3275*67e74705SXin Li                           Param->getDefaultArgumentLoc(), Param->getDeclName());
3276*67e74705SXin Li   }
3277*67e74705SXin Li 
3278*67e74705SXin Li   return ArgType;
3279*67e74705SXin Li }
3280*67e74705SXin Li 
3281*67e74705SXin Li /// \brief Substitute template arguments into the default template argument for
3282*67e74705SXin Li /// the given non-type template parameter.
3283*67e74705SXin Li ///
3284*67e74705SXin Li /// \param SemaRef the semantic analysis object for which we are performing
3285*67e74705SXin Li /// the substitution.
3286*67e74705SXin Li ///
3287*67e74705SXin Li /// \param Template the template that we are synthesizing template arguments
3288*67e74705SXin Li /// for.
3289*67e74705SXin Li ///
3290*67e74705SXin Li /// \param TemplateLoc the location of the template name that started the
3291*67e74705SXin Li /// template-id we are checking.
3292*67e74705SXin Li ///
3293*67e74705SXin Li /// \param RAngleLoc the location of the right angle bracket ('>') that
3294*67e74705SXin Li /// terminates the template-id.
3295*67e74705SXin Li ///
3296*67e74705SXin Li /// \param Param the non-type template parameter whose default we are
3297*67e74705SXin Li /// substituting into.
3298*67e74705SXin Li ///
3299*67e74705SXin Li /// \param Converted the list of template arguments provided for template
3300*67e74705SXin Li /// parameters that precede \p Param in the template parameter list.
3301*67e74705SXin Li ///
3302*67e74705SXin Li /// \returns the substituted template argument, or NULL if an error occurred.
3303*67e74705SXin Li static ExprResult
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,NonTypeTemplateParmDecl * Param,SmallVectorImpl<TemplateArgument> & Converted)3304*67e74705SXin Li SubstDefaultTemplateArgument(Sema &SemaRef,
3305*67e74705SXin Li                              TemplateDecl *Template,
3306*67e74705SXin Li                              SourceLocation TemplateLoc,
3307*67e74705SXin Li                              SourceLocation RAngleLoc,
3308*67e74705SXin Li                              NonTypeTemplateParmDecl *Param,
3309*67e74705SXin Li                         SmallVectorImpl<TemplateArgument> &Converted) {
3310*67e74705SXin Li   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3311*67e74705SXin Li                                    Template, Converted,
3312*67e74705SXin Li                                    SourceRange(TemplateLoc, RAngleLoc));
3313*67e74705SXin Li   if (Inst.isInvalid())
3314*67e74705SXin Li     return ExprError();
3315*67e74705SXin Li 
3316*67e74705SXin Li   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
3317*67e74705SXin Li 
3318*67e74705SXin Li   // Only substitute for the innermost template argument list.
3319*67e74705SXin Li   MultiLevelTemplateArgumentList TemplateArgLists;
3320*67e74705SXin Li   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3321*67e74705SXin Li   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3322*67e74705SXin Li     TemplateArgLists.addOuterTemplateArguments(None);
3323*67e74705SXin Li 
3324*67e74705SXin Li   EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3325*67e74705SXin Li                                                      Sema::ConstantEvaluated);
3326*67e74705SXin Li   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3327*67e74705SXin Li }
3328*67e74705SXin Li 
3329*67e74705SXin Li /// \brief Substitute template arguments into the default template argument for
3330*67e74705SXin Li /// the given template template parameter.
3331*67e74705SXin Li ///
3332*67e74705SXin Li /// \param SemaRef the semantic analysis object for which we are performing
3333*67e74705SXin Li /// the substitution.
3334*67e74705SXin Li ///
3335*67e74705SXin Li /// \param Template the template that we are synthesizing template arguments
3336*67e74705SXin Li /// for.
3337*67e74705SXin Li ///
3338*67e74705SXin Li /// \param TemplateLoc the location of the template name that started the
3339*67e74705SXin Li /// template-id we are checking.
3340*67e74705SXin Li ///
3341*67e74705SXin Li /// \param RAngleLoc the location of the right angle bracket ('>') that
3342*67e74705SXin Li /// terminates the template-id.
3343*67e74705SXin Li ///
3344*67e74705SXin Li /// \param Param the template template parameter whose default we are
3345*67e74705SXin Li /// substituting into.
3346*67e74705SXin Li ///
3347*67e74705SXin Li /// \param Converted the list of template arguments provided for template
3348*67e74705SXin Li /// parameters that precede \p Param in the template parameter list.
3349*67e74705SXin Li ///
3350*67e74705SXin Li /// \param QualifierLoc Will be set to the nested-name-specifier (with
3351*67e74705SXin Li /// source-location information) that precedes the template name.
3352*67e74705SXin Li ///
3353*67e74705SXin Li /// \returns the substituted template argument, or NULL if an error occurred.
3354*67e74705SXin Li static TemplateName
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTemplateParmDecl * Param,SmallVectorImpl<TemplateArgument> & Converted,NestedNameSpecifierLoc & QualifierLoc)3355*67e74705SXin Li SubstDefaultTemplateArgument(Sema &SemaRef,
3356*67e74705SXin Li                              TemplateDecl *Template,
3357*67e74705SXin Li                              SourceLocation TemplateLoc,
3358*67e74705SXin Li                              SourceLocation RAngleLoc,
3359*67e74705SXin Li                              TemplateTemplateParmDecl *Param,
3360*67e74705SXin Li                        SmallVectorImpl<TemplateArgument> &Converted,
3361*67e74705SXin Li                              NestedNameSpecifierLoc &QualifierLoc) {
3362*67e74705SXin Li   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3363*67e74705SXin Li                                    SourceRange(TemplateLoc, RAngleLoc));
3364*67e74705SXin Li   if (Inst.isInvalid())
3365*67e74705SXin Li     return TemplateName();
3366*67e74705SXin Li 
3367*67e74705SXin Li   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
3368*67e74705SXin Li 
3369*67e74705SXin Li   // Only substitute for the innermost template argument list.
3370*67e74705SXin Li   MultiLevelTemplateArgumentList TemplateArgLists;
3371*67e74705SXin Li   TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3372*67e74705SXin Li   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3373*67e74705SXin Li     TemplateArgLists.addOuterTemplateArguments(None);
3374*67e74705SXin Li 
3375*67e74705SXin Li   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3376*67e74705SXin Li   // Substitute into the nested-name-specifier first,
3377*67e74705SXin Li   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3378*67e74705SXin Li   if (QualifierLoc) {
3379*67e74705SXin Li     QualifierLoc =
3380*67e74705SXin Li         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3381*67e74705SXin Li     if (!QualifierLoc)
3382*67e74705SXin Li       return TemplateName();
3383*67e74705SXin Li   }
3384*67e74705SXin Li 
3385*67e74705SXin Li   return SemaRef.SubstTemplateName(
3386*67e74705SXin Li              QualifierLoc,
3387*67e74705SXin Li              Param->getDefaultArgument().getArgument().getAsTemplate(),
3388*67e74705SXin Li              Param->getDefaultArgument().getTemplateNameLoc(),
3389*67e74705SXin Li              TemplateArgLists);
3390*67e74705SXin Li }
3391*67e74705SXin Li 
3392*67e74705SXin Li /// \brief If the given template parameter has a default template
3393*67e74705SXin Li /// argument, substitute into that default template argument and
3394*67e74705SXin Li /// return the corresponding template argument.
3395*67e74705SXin Li TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,Decl * Param,SmallVectorImpl<TemplateArgument> & Converted,bool & HasDefaultArg)3396*67e74705SXin Li Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3397*67e74705SXin Li                                               SourceLocation TemplateLoc,
3398*67e74705SXin Li                                               SourceLocation RAngleLoc,
3399*67e74705SXin Li                                               Decl *Param,
3400*67e74705SXin Li                                               SmallVectorImpl<TemplateArgument>
3401*67e74705SXin Li                                                 &Converted,
3402*67e74705SXin Li                                               bool &HasDefaultArg) {
3403*67e74705SXin Li   HasDefaultArg = false;
3404*67e74705SXin Li 
3405*67e74705SXin Li   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3406*67e74705SXin Li     if (!hasVisibleDefaultArgument(TypeParm))
3407*67e74705SXin Li       return TemplateArgumentLoc();
3408*67e74705SXin Li 
3409*67e74705SXin Li     HasDefaultArg = true;
3410*67e74705SXin Li     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3411*67e74705SXin Li                                                       TemplateLoc,
3412*67e74705SXin Li                                                       RAngleLoc,
3413*67e74705SXin Li                                                       TypeParm,
3414*67e74705SXin Li                                                       Converted);
3415*67e74705SXin Li     if (DI)
3416*67e74705SXin Li       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3417*67e74705SXin Li 
3418*67e74705SXin Li     return TemplateArgumentLoc();
3419*67e74705SXin Li   }
3420*67e74705SXin Li 
3421*67e74705SXin Li   if (NonTypeTemplateParmDecl *NonTypeParm
3422*67e74705SXin Li         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3423*67e74705SXin Li     if (!hasVisibleDefaultArgument(NonTypeParm))
3424*67e74705SXin Li       return TemplateArgumentLoc();
3425*67e74705SXin Li 
3426*67e74705SXin Li     HasDefaultArg = true;
3427*67e74705SXin Li     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3428*67e74705SXin Li                                                   TemplateLoc,
3429*67e74705SXin Li                                                   RAngleLoc,
3430*67e74705SXin Li                                                   NonTypeParm,
3431*67e74705SXin Li                                                   Converted);
3432*67e74705SXin Li     if (Arg.isInvalid())
3433*67e74705SXin Li       return TemplateArgumentLoc();
3434*67e74705SXin Li 
3435*67e74705SXin Li     Expr *ArgE = Arg.getAs<Expr>();
3436*67e74705SXin Li     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3437*67e74705SXin Li   }
3438*67e74705SXin Li 
3439*67e74705SXin Li   TemplateTemplateParmDecl *TempTempParm
3440*67e74705SXin Li     = cast<TemplateTemplateParmDecl>(Param);
3441*67e74705SXin Li   if (!hasVisibleDefaultArgument(TempTempParm))
3442*67e74705SXin Li     return TemplateArgumentLoc();
3443*67e74705SXin Li 
3444*67e74705SXin Li   HasDefaultArg = true;
3445*67e74705SXin Li   NestedNameSpecifierLoc QualifierLoc;
3446*67e74705SXin Li   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3447*67e74705SXin Li                                                     TemplateLoc,
3448*67e74705SXin Li                                                     RAngleLoc,
3449*67e74705SXin Li                                                     TempTempParm,
3450*67e74705SXin Li                                                     Converted,
3451*67e74705SXin Li                                                     QualifierLoc);
3452*67e74705SXin Li   if (TName.isNull())
3453*67e74705SXin Li     return TemplateArgumentLoc();
3454*67e74705SXin Li 
3455*67e74705SXin Li   return TemplateArgumentLoc(TemplateArgument(TName),
3456*67e74705SXin Li                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3457*67e74705SXin Li                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3458*67e74705SXin Li }
3459*67e74705SXin Li 
3460*67e74705SXin Li /// \brief Check that the given template argument corresponds to the given
3461*67e74705SXin Li /// template parameter.
3462*67e74705SXin Li ///
3463*67e74705SXin Li /// \param Param The template parameter against which the argument will be
3464*67e74705SXin Li /// checked.
3465*67e74705SXin Li ///
3466*67e74705SXin Li /// \param Arg The template argument, which may be updated due to conversions.
3467*67e74705SXin Li ///
3468*67e74705SXin Li /// \param Template The template in which the template argument resides.
3469*67e74705SXin Li ///
3470*67e74705SXin Li /// \param TemplateLoc The location of the template name for the template
3471*67e74705SXin Li /// whose argument list we're matching.
3472*67e74705SXin Li ///
3473*67e74705SXin Li /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3474*67e74705SXin Li /// the template argument list.
3475*67e74705SXin Li ///
3476*67e74705SXin Li /// \param ArgumentPackIndex The index into the argument pack where this
3477*67e74705SXin Li /// argument will be placed. Only valid if the parameter is a parameter pack.
3478*67e74705SXin Li ///
3479*67e74705SXin Li /// \param Converted The checked, converted argument will be added to the
3480*67e74705SXin Li /// end of this small vector.
3481*67e74705SXin Li ///
3482*67e74705SXin Li /// \param CTAK Describes how we arrived at this particular template argument:
3483*67e74705SXin Li /// explicitly written, deduced, etc.
3484*67e74705SXin Li ///
3485*67e74705SXin Li /// \returns true on error, false otherwise.
CheckTemplateArgument(NamedDecl * Param,TemplateArgumentLoc & Arg,NamedDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,unsigned ArgumentPackIndex,SmallVectorImpl<TemplateArgument> & Converted,CheckTemplateArgumentKind CTAK)3486*67e74705SXin Li bool Sema::CheckTemplateArgument(NamedDecl *Param,
3487*67e74705SXin Li                                  TemplateArgumentLoc &Arg,
3488*67e74705SXin Li                                  NamedDecl *Template,
3489*67e74705SXin Li                                  SourceLocation TemplateLoc,
3490*67e74705SXin Li                                  SourceLocation RAngleLoc,
3491*67e74705SXin Li                                  unsigned ArgumentPackIndex,
3492*67e74705SXin Li                             SmallVectorImpl<TemplateArgument> &Converted,
3493*67e74705SXin Li                                  CheckTemplateArgumentKind CTAK) {
3494*67e74705SXin Li   // Check template type parameters.
3495*67e74705SXin Li   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3496*67e74705SXin Li     return CheckTemplateTypeArgument(TTP, Arg, Converted);
3497*67e74705SXin Li 
3498*67e74705SXin Li   // Check non-type template parameters.
3499*67e74705SXin Li   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3500*67e74705SXin Li     // Do substitution on the type of the non-type template parameter
3501*67e74705SXin Li     // with the template arguments we've seen thus far.  But if the
3502*67e74705SXin Li     // template has a dependent context then we cannot substitute yet.
3503*67e74705SXin Li     QualType NTTPType = NTTP->getType();
3504*67e74705SXin Li     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3505*67e74705SXin Li       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3506*67e74705SXin Li 
3507*67e74705SXin Li     if (NTTPType->isDependentType() &&
3508*67e74705SXin Li         !isa<TemplateTemplateParmDecl>(Template) &&
3509*67e74705SXin Li         !Template->getDeclContext()->isDependentContext()) {
3510*67e74705SXin Li       // Do substitution on the type of the non-type template parameter.
3511*67e74705SXin Li       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3512*67e74705SXin Li                                  NTTP, Converted,
3513*67e74705SXin Li                                  SourceRange(TemplateLoc, RAngleLoc));
3514*67e74705SXin Li       if (Inst.isInvalid())
3515*67e74705SXin Li         return true;
3516*67e74705SXin Li 
3517*67e74705SXin Li       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3518*67e74705SXin Li                                         Converted);
3519*67e74705SXin Li       NTTPType = SubstType(NTTPType,
3520*67e74705SXin Li                            MultiLevelTemplateArgumentList(TemplateArgs),
3521*67e74705SXin Li                            NTTP->getLocation(),
3522*67e74705SXin Li                            NTTP->getDeclName());
3523*67e74705SXin Li       // If that worked, check the non-type template parameter type
3524*67e74705SXin Li       // for validity.
3525*67e74705SXin Li       if (!NTTPType.isNull())
3526*67e74705SXin Li         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3527*67e74705SXin Li                                                      NTTP->getLocation());
3528*67e74705SXin Li       if (NTTPType.isNull())
3529*67e74705SXin Li         return true;
3530*67e74705SXin Li     }
3531*67e74705SXin Li 
3532*67e74705SXin Li     switch (Arg.getArgument().getKind()) {
3533*67e74705SXin Li     case TemplateArgument::Null:
3534*67e74705SXin Li       llvm_unreachable("Should never see a NULL template argument here");
3535*67e74705SXin Li 
3536*67e74705SXin Li     case TemplateArgument::Expression: {
3537*67e74705SXin Li       TemplateArgument Result;
3538*67e74705SXin Li       ExprResult Res =
3539*67e74705SXin Li         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3540*67e74705SXin Li                               Result, CTAK);
3541*67e74705SXin Li       if (Res.isInvalid())
3542*67e74705SXin Li         return true;
3543*67e74705SXin Li 
3544*67e74705SXin Li       // If the resulting expression is new, then use it in place of the
3545*67e74705SXin Li       // old expression in the template argument.
3546*67e74705SXin Li       if (Res.get() != Arg.getArgument().getAsExpr()) {
3547*67e74705SXin Li         TemplateArgument TA(Res.get());
3548*67e74705SXin Li         Arg = TemplateArgumentLoc(TA, Res.get());
3549*67e74705SXin Li       }
3550*67e74705SXin Li 
3551*67e74705SXin Li       Converted.push_back(Result);
3552*67e74705SXin Li       break;
3553*67e74705SXin Li     }
3554*67e74705SXin Li 
3555*67e74705SXin Li     case TemplateArgument::Declaration:
3556*67e74705SXin Li     case TemplateArgument::Integral:
3557*67e74705SXin Li     case TemplateArgument::NullPtr:
3558*67e74705SXin Li       // We've already checked this template argument, so just copy
3559*67e74705SXin Li       // it to the list of converted arguments.
3560*67e74705SXin Li       Converted.push_back(Arg.getArgument());
3561*67e74705SXin Li       break;
3562*67e74705SXin Li 
3563*67e74705SXin Li     case TemplateArgument::Template:
3564*67e74705SXin Li     case TemplateArgument::TemplateExpansion:
3565*67e74705SXin Li       // We were given a template template argument. It may not be ill-formed;
3566*67e74705SXin Li       // see below.
3567*67e74705SXin Li       if (DependentTemplateName *DTN
3568*67e74705SXin Li             = Arg.getArgument().getAsTemplateOrTemplatePattern()
3569*67e74705SXin Li                                               .getAsDependentTemplateName()) {
3570*67e74705SXin Li         // We have a template argument such as \c T::template X, which we
3571*67e74705SXin Li         // parsed as a template template argument. However, since we now
3572*67e74705SXin Li         // know that we need a non-type template argument, convert this
3573*67e74705SXin Li         // template name into an expression.
3574*67e74705SXin Li 
3575*67e74705SXin Li         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3576*67e74705SXin Li                                      Arg.getTemplateNameLoc());
3577*67e74705SXin Li 
3578*67e74705SXin Li         CXXScopeSpec SS;
3579*67e74705SXin Li         SS.Adopt(Arg.getTemplateQualifierLoc());
3580*67e74705SXin Li         // FIXME: the template-template arg was a DependentTemplateName,
3581*67e74705SXin Li         // so it was provided with a template keyword. However, its source
3582*67e74705SXin Li         // location is not stored in the template argument structure.
3583*67e74705SXin Li         SourceLocation TemplateKWLoc;
3584*67e74705SXin Li         ExprResult E = DependentScopeDeclRefExpr::Create(
3585*67e74705SXin Li             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3586*67e74705SXin Li             nullptr);
3587*67e74705SXin Li 
3588*67e74705SXin Li         // If we parsed the template argument as a pack expansion, create a
3589*67e74705SXin Li         // pack expansion expression.
3590*67e74705SXin Li         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3591*67e74705SXin Li           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3592*67e74705SXin Li           if (E.isInvalid())
3593*67e74705SXin Li             return true;
3594*67e74705SXin Li         }
3595*67e74705SXin Li 
3596*67e74705SXin Li         TemplateArgument Result;
3597*67e74705SXin Li         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3598*67e74705SXin Li         if (E.isInvalid())
3599*67e74705SXin Li           return true;
3600*67e74705SXin Li 
3601*67e74705SXin Li         Converted.push_back(Result);
3602*67e74705SXin Li         break;
3603*67e74705SXin Li       }
3604*67e74705SXin Li 
3605*67e74705SXin Li       // We have a template argument that actually does refer to a class
3606*67e74705SXin Li       // template, alias template, or template template parameter, and
3607*67e74705SXin Li       // therefore cannot be a non-type template argument.
3608*67e74705SXin Li       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3609*67e74705SXin Li         << Arg.getSourceRange();
3610*67e74705SXin Li 
3611*67e74705SXin Li       Diag(Param->getLocation(), diag::note_template_param_here);
3612*67e74705SXin Li       return true;
3613*67e74705SXin Li 
3614*67e74705SXin Li     case TemplateArgument::Type: {
3615*67e74705SXin Li       // We have a non-type template parameter but the template
3616*67e74705SXin Li       // argument is a type.
3617*67e74705SXin Li 
3618*67e74705SXin Li       // C++ [temp.arg]p2:
3619*67e74705SXin Li       //   In a template-argument, an ambiguity between a type-id and
3620*67e74705SXin Li       //   an expression is resolved to a type-id, regardless of the
3621*67e74705SXin Li       //   form of the corresponding template-parameter.
3622*67e74705SXin Li       //
3623*67e74705SXin Li       // We warn specifically about this case, since it can be rather
3624*67e74705SXin Li       // confusing for users.
3625*67e74705SXin Li       QualType T = Arg.getArgument().getAsType();
3626*67e74705SXin Li       SourceRange SR = Arg.getSourceRange();
3627*67e74705SXin Li       if (T->isFunctionType())
3628*67e74705SXin Li         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3629*67e74705SXin Li       else
3630*67e74705SXin Li         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3631*67e74705SXin Li       Diag(Param->getLocation(), diag::note_template_param_here);
3632*67e74705SXin Li       return true;
3633*67e74705SXin Li     }
3634*67e74705SXin Li 
3635*67e74705SXin Li     case TemplateArgument::Pack:
3636*67e74705SXin Li       llvm_unreachable("Caller must expand template argument packs");
3637*67e74705SXin Li     }
3638*67e74705SXin Li 
3639*67e74705SXin Li     return false;
3640*67e74705SXin Li   }
3641*67e74705SXin Li 
3642*67e74705SXin Li 
3643*67e74705SXin Li   // Check template template parameters.
3644*67e74705SXin Li   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3645*67e74705SXin Li 
3646*67e74705SXin Li   // Substitute into the template parameter list of the template
3647*67e74705SXin Li   // template parameter, since previously-supplied template arguments
3648*67e74705SXin Li   // may appear within the template template parameter.
3649*67e74705SXin Li   {
3650*67e74705SXin Li     // Set up a template instantiation context.
3651*67e74705SXin Li     LocalInstantiationScope Scope(*this);
3652*67e74705SXin Li     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3653*67e74705SXin Li                                TempParm, Converted,
3654*67e74705SXin Li                                SourceRange(TemplateLoc, RAngleLoc));
3655*67e74705SXin Li     if (Inst.isInvalid())
3656*67e74705SXin Li       return true;
3657*67e74705SXin Li 
3658*67e74705SXin Li     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
3659*67e74705SXin Li     TempParm = cast_or_null<TemplateTemplateParmDecl>(
3660*67e74705SXin Li                       SubstDecl(TempParm, CurContext,
3661*67e74705SXin Li                                 MultiLevelTemplateArgumentList(TemplateArgs)));
3662*67e74705SXin Li     if (!TempParm)
3663*67e74705SXin Li       return true;
3664*67e74705SXin Li   }
3665*67e74705SXin Li 
3666*67e74705SXin Li   switch (Arg.getArgument().getKind()) {
3667*67e74705SXin Li   case TemplateArgument::Null:
3668*67e74705SXin Li     llvm_unreachable("Should never see a NULL template argument here");
3669*67e74705SXin Li 
3670*67e74705SXin Li   case TemplateArgument::Template:
3671*67e74705SXin Li   case TemplateArgument::TemplateExpansion:
3672*67e74705SXin Li     if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3673*67e74705SXin Li       return true;
3674*67e74705SXin Li 
3675*67e74705SXin Li     Converted.push_back(Arg.getArgument());
3676*67e74705SXin Li     break;
3677*67e74705SXin Li 
3678*67e74705SXin Li   case TemplateArgument::Expression:
3679*67e74705SXin Li   case TemplateArgument::Type:
3680*67e74705SXin Li     // We have a template template parameter but the template
3681*67e74705SXin Li     // argument does not refer to a template.
3682*67e74705SXin Li     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3683*67e74705SXin Li       << getLangOpts().CPlusPlus11;
3684*67e74705SXin Li     return true;
3685*67e74705SXin Li 
3686*67e74705SXin Li   case TemplateArgument::Declaration:
3687*67e74705SXin Li     llvm_unreachable("Declaration argument with template template parameter");
3688*67e74705SXin Li   case TemplateArgument::Integral:
3689*67e74705SXin Li     llvm_unreachable("Integral argument with template template parameter");
3690*67e74705SXin Li   case TemplateArgument::NullPtr:
3691*67e74705SXin Li     llvm_unreachable("Null pointer argument with template template parameter");
3692*67e74705SXin Li 
3693*67e74705SXin Li   case TemplateArgument::Pack:
3694*67e74705SXin Li     llvm_unreachable("Caller must expand template argument packs");
3695*67e74705SXin Li   }
3696*67e74705SXin Li 
3697*67e74705SXin Li   return false;
3698*67e74705SXin Li }
3699*67e74705SXin Li 
3700*67e74705SXin Li /// \brief Diagnose an arity mismatch in the
diagnoseArityMismatch(Sema & S,TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3701*67e74705SXin Li static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3702*67e74705SXin Li                                   SourceLocation TemplateLoc,
3703*67e74705SXin Li                                   TemplateArgumentListInfo &TemplateArgs) {
3704*67e74705SXin Li   TemplateParameterList *Params = Template->getTemplateParameters();
3705*67e74705SXin Li   unsigned NumParams = Params->size();
3706*67e74705SXin Li   unsigned NumArgs = TemplateArgs.size();
3707*67e74705SXin Li 
3708*67e74705SXin Li   SourceRange Range;
3709*67e74705SXin Li   if (NumArgs > NumParams)
3710*67e74705SXin Li     Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3711*67e74705SXin Li                         TemplateArgs.getRAngleLoc());
3712*67e74705SXin Li   S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3713*67e74705SXin Li     << (NumArgs > NumParams)
3714*67e74705SXin Li     << (isa<ClassTemplateDecl>(Template)? 0 :
3715*67e74705SXin Li         isa<FunctionTemplateDecl>(Template)? 1 :
3716*67e74705SXin Li         isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3717*67e74705SXin Li     << Template << Range;
3718*67e74705SXin Li   S.Diag(Template->getLocation(), diag::note_template_decl_here)
3719*67e74705SXin Li     << Params->getSourceRange();
3720*67e74705SXin Li   return true;
3721*67e74705SXin Li }
3722*67e74705SXin Li 
3723*67e74705SXin Li /// \brief Check whether the template parameter is a pack expansion, and if so,
3724*67e74705SXin Li /// determine the number of parameters produced by that expansion. For instance:
3725*67e74705SXin Li ///
3726*67e74705SXin Li /// \code
3727*67e74705SXin Li /// template<typename ...Ts> struct A {
3728*67e74705SXin Li ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3729*67e74705SXin Li /// };
3730*67e74705SXin Li /// \endcode
3731*67e74705SXin Li ///
3732*67e74705SXin Li /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3733*67e74705SXin Li /// is not a pack expansion, so returns an empty Optional.
getExpandedPackSize(NamedDecl * Param)3734*67e74705SXin Li static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3735*67e74705SXin Li   if (NonTypeTemplateParmDecl *NTTP
3736*67e74705SXin Li         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3737*67e74705SXin Li     if (NTTP->isExpandedParameterPack())
3738*67e74705SXin Li       return NTTP->getNumExpansionTypes();
3739*67e74705SXin Li   }
3740*67e74705SXin Li 
3741*67e74705SXin Li   if (TemplateTemplateParmDecl *TTP
3742*67e74705SXin Li         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3743*67e74705SXin Li     if (TTP->isExpandedParameterPack())
3744*67e74705SXin Li       return TTP->getNumExpansionTemplateParameters();
3745*67e74705SXin Li   }
3746*67e74705SXin Li 
3747*67e74705SXin Li   return None;
3748*67e74705SXin Li }
3749*67e74705SXin Li 
3750*67e74705SXin Li /// Diagnose a missing template argument.
3751*67e74705SXin Li template<typename TemplateParmDecl>
diagnoseMissingArgument(Sema & S,SourceLocation Loc,TemplateDecl * TD,const TemplateParmDecl * D,TemplateArgumentListInfo & Args)3752*67e74705SXin Li static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3753*67e74705SXin Li                                     TemplateDecl *TD,
3754*67e74705SXin Li                                     const TemplateParmDecl *D,
3755*67e74705SXin Li                                     TemplateArgumentListInfo &Args) {
3756*67e74705SXin Li   // Dig out the most recent declaration of the template parameter; there may be
3757*67e74705SXin Li   // declarations of the template that are more recent than TD.
3758*67e74705SXin Li   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3759*67e74705SXin Li                                  ->getTemplateParameters()
3760*67e74705SXin Li                                  ->getParam(D->getIndex()));
3761*67e74705SXin Li 
3762*67e74705SXin Li   // If there's a default argument that's not visible, diagnose that we're
3763*67e74705SXin Li   // missing a module import.
3764*67e74705SXin Li   llvm::SmallVector<Module*, 8> Modules;
3765*67e74705SXin Li   if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3766*67e74705SXin Li     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3767*67e74705SXin Li                             D->getDefaultArgumentLoc(), Modules,
3768*67e74705SXin Li                             Sema::MissingImportKind::DefaultArgument,
3769*67e74705SXin Li                             /*Recover*/true);
3770*67e74705SXin Li     return true;
3771*67e74705SXin Li   }
3772*67e74705SXin Li 
3773*67e74705SXin Li   // FIXME: If there's a more recent default argument that *is* visible,
3774*67e74705SXin Li   // diagnose that it was declared too late.
3775*67e74705SXin Li 
3776*67e74705SXin Li   return diagnoseArityMismatch(S, TD, Loc, Args);
3777*67e74705SXin Li }
3778*67e74705SXin Li 
3779*67e74705SXin Li /// \brief Check that the given template argument list is well-formed
3780*67e74705SXin Li /// for specializing the given template.
CheckTemplateArgumentList(TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs,bool PartialTemplateArgs,SmallVectorImpl<TemplateArgument> & Converted)3781*67e74705SXin Li bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3782*67e74705SXin Li                                      SourceLocation TemplateLoc,
3783*67e74705SXin Li                                      TemplateArgumentListInfo &TemplateArgs,
3784*67e74705SXin Li                                      bool PartialTemplateArgs,
3785*67e74705SXin Li                           SmallVectorImpl<TemplateArgument> &Converted) {
3786*67e74705SXin Li   // Make a copy of the template arguments for processing.  Only make the
3787*67e74705SXin Li   // changes at the end when successful in matching the arguments to the
3788*67e74705SXin Li   // template.
3789*67e74705SXin Li   TemplateArgumentListInfo NewArgs = TemplateArgs;
3790*67e74705SXin Li 
3791*67e74705SXin Li   TemplateParameterList *Params = Template->getTemplateParameters();
3792*67e74705SXin Li 
3793*67e74705SXin Li   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3794*67e74705SXin Li 
3795*67e74705SXin Li   // C++ [temp.arg]p1:
3796*67e74705SXin Li   //   [...] The type and form of each template-argument specified in
3797*67e74705SXin Li   //   a template-id shall match the type and form specified for the
3798*67e74705SXin Li   //   corresponding parameter declared by the template in its
3799*67e74705SXin Li   //   template-parameter-list.
3800*67e74705SXin Li   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3801*67e74705SXin Li   SmallVector<TemplateArgument, 2> ArgumentPack;
3802*67e74705SXin Li   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3803*67e74705SXin Li   LocalInstantiationScope InstScope(*this, true);
3804*67e74705SXin Li   for (TemplateParameterList::iterator Param = Params->begin(),
3805*67e74705SXin Li                                        ParamEnd = Params->end();
3806*67e74705SXin Li        Param != ParamEnd; /* increment in loop */) {
3807*67e74705SXin Li     // If we have an expanded parameter pack, make sure we don't have too
3808*67e74705SXin Li     // many arguments.
3809*67e74705SXin Li     if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3810*67e74705SXin Li       if (*Expansions == ArgumentPack.size()) {
3811*67e74705SXin Li         // We're done with this parameter pack. Pack up its arguments and add
3812*67e74705SXin Li         // them to the list.
3813*67e74705SXin Li         Converted.push_back(
3814*67e74705SXin Li             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3815*67e74705SXin Li         ArgumentPack.clear();
3816*67e74705SXin Li 
3817*67e74705SXin Li         // This argument is assigned to the next parameter.
3818*67e74705SXin Li         ++Param;
3819*67e74705SXin Li         continue;
3820*67e74705SXin Li       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3821*67e74705SXin Li         // Not enough arguments for this parameter pack.
3822*67e74705SXin Li         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3823*67e74705SXin Li           << false
3824*67e74705SXin Li           << (isa<ClassTemplateDecl>(Template)? 0 :
3825*67e74705SXin Li               isa<FunctionTemplateDecl>(Template)? 1 :
3826*67e74705SXin Li               isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3827*67e74705SXin Li           << Template;
3828*67e74705SXin Li         Diag(Template->getLocation(), diag::note_template_decl_here)
3829*67e74705SXin Li           << Params->getSourceRange();
3830*67e74705SXin Li         return true;
3831*67e74705SXin Li       }
3832*67e74705SXin Li     }
3833*67e74705SXin Li 
3834*67e74705SXin Li     if (ArgIdx < NumArgs) {
3835*67e74705SXin Li       // Check the template argument we were given.
3836*67e74705SXin Li       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3837*67e74705SXin Li                                 TemplateLoc, RAngleLoc,
3838*67e74705SXin Li                                 ArgumentPack.size(), Converted))
3839*67e74705SXin Li         return true;
3840*67e74705SXin Li 
3841*67e74705SXin Li       bool PackExpansionIntoNonPack =
3842*67e74705SXin Li           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3843*67e74705SXin Li           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3844*67e74705SXin Li       if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3845*67e74705SXin Li         // Core issue 1430: we have a pack expansion as an argument to an
3846*67e74705SXin Li         // alias template, and it's not part of a parameter pack. This
3847*67e74705SXin Li         // can't be canonicalized, so reject it now.
3848*67e74705SXin Li         Diag(NewArgs[ArgIdx].getLocation(),
3849*67e74705SXin Li              diag::err_alias_template_expansion_into_fixed_list)
3850*67e74705SXin Li           << NewArgs[ArgIdx].getSourceRange();
3851*67e74705SXin Li         Diag((*Param)->getLocation(), diag::note_template_param_here);
3852*67e74705SXin Li         return true;
3853*67e74705SXin Li       }
3854*67e74705SXin Li 
3855*67e74705SXin Li       // We're now done with this argument.
3856*67e74705SXin Li       ++ArgIdx;
3857*67e74705SXin Li 
3858*67e74705SXin Li       if ((*Param)->isTemplateParameterPack()) {
3859*67e74705SXin Li         // The template parameter was a template parameter pack, so take the
3860*67e74705SXin Li         // deduced argument and place it on the argument pack. Note that we
3861*67e74705SXin Li         // stay on the same template parameter so that we can deduce more
3862*67e74705SXin Li         // arguments.
3863*67e74705SXin Li         ArgumentPack.push_back(Converted.pop_back_val());
3864*67e74705SXin Li       } else {
3865*67e74705SXin Li         // Move to the next template parameter.
3866*67e74705SXin Li         ++Param;
3867*67e74705SXin Li       }
3868*67e74705SXin Li 
3869*67e74705SXin Li       // If we just saw a pack expansion into a non-pack, then directly convert
3870*67e74705SXin Li       // the remaining arguments, because we don't know what parameters they'll
3871*67e74705SXin Li       // match up with.
3872*67e74705SXin Li       if (PackExpansionIntoNonPack) {
3873*67e74705SXin Li         if (!ArgumentPack.empty()) {
3874*67e74705SXin Li           // If we were part way through filling in an expanded parameter pack,
3875*67e74705SXin Li           // fall back to just producing individual arguments.
3876*67e74705SXin Li           Converted.insert(Converted.end(),
3877*67e74705SXin Li                            ArgumentPack.begin(), ArgumentPack.end());
3878*67e74705SXin Li           ArgumentPack.clear();
3879*67e74705SXin Li         }
3880*67e74705SXin Li 
3881*67e74705SXin Li         while (ArgIdx < NumArgs) {
3882*67e74705SXin Li           Converted.push_back(NewArgs[ArgIdx].getArgument());
3883*67e74705SXin Li           ++ArgIdx;
3884*67e74705SXin Li         }
3885*67e74705SXin Li 
3886*67e74705SXin Li         return false;
3887*67e74705SXin Li       }
3888*67e74705SXin Li 
3889*67e74705SXin Li       continue;
3890*67e74705SXin Li     }
3891*67e74705SXin Li 
3892*67e74705SXin Li     // If we're checking a partial template argument list, we're done.
3893*67e74705SXin Li     if (PartialTemplateArgs) {
3894*67e74705SXin Li       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3895*67e74705SXin Li         Converted.push_back(
3896*67e74705SXin Li             TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3897*67e74705SXin Li 
3898*67e74705SXin Li       return false;
3899*67e74705SXin Li     }
3900*67e74705SXin Li 
3901*67e74705SXin Li     // If we have a template parameter pack with no more corresponding
3902*67e74705SXin Li     // arguments, just break out now and we'll fill in the argument pack below.
3903*67e74705SXin Li     if ((*Param)->isTemplateParameterPack()) {
3904*67e74705SXin Li       assert(!getExpandedPackSize(*Param) &&
3905*67e74705SXin Li              "Should have dealt with this already");
3906*67e74705SXin Li 
3907*67e74705SXin Li       // A non-expanded parameter pack before the end of the parameter list
3908*67e74705SXin Li       // only occurs for an ill-formed template parameter list, unless we've
3909*67e74705SXin Li       // got a partial argument list for a function template, so just bail out.
3910*67e74705SXin Li       if (Param + 1 != ParamEnd)
3911*67e74705SXin Li         return true;
3912*67e74705SXin Li 
3913*67e74705SXin Li       Converted.push_back(
3914*67e74705SXin Li           TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3915*67e74705SXin Li       ArgumentPack.clear();
3916*67e74705SXin Li 
3917*67e74705SXin Li       ++Param;
3918*67e74705SXin Li       continue;
3919*67e74705SXin Li     }
3920*67e74705SXin Li 
3921*67e74705SXin Li     // Check whether we have a default argument.
3922*67e74705SXin Li     TemplateArgumentLoc Arg;
3923*67e74705SXin Li 
3924*67e74705SXin Li     // Retrieve the default template argument from the template
3925*67e74705SXin Li     // parameter. For each kind of template parameter, we substitute the
3926*67e74705SXin Li     // template arguments provided thus far and any "outer" template arguments
3927*67e74705SXin Li     // (when the template parameter was part of a nested template) into
3928*67e74705SXin Li     // the default argument.
3929*67e74705SXin Li     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3930*67e74705SXin Li       if (!hasVisibleDefaultArgument(TTP))
3931*67e74705SXin Li         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3932*67e74705SXin Li                                        NewArgs);
3933*67e74705SXin Li 
3934*67e74705SXin Li       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3935*67e74705SXin Li                                                              Template,
3936*67e74705SXin Li                                                              TemplateLoc,
3937*67e74705SXin Li                                                              RAngleLoc,
3938*67e74705SXin Li                                                              TTP,
3939*67e74705SXin Li                                                              Converted);
3940*67e74705SXin Li       if (!ArgType)
3941*67e74705SXin Li         return true;
3942*67e74705SXin Li 
3943*67e74705SXin Li       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3944*67e74705SXin Li                                 ArgType);
3945*67e74705SXin Li     } else if (NonTypeTemplateParmDecl *NTTP
3946*67e74705SXin Li                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3947*67e74705SXin Li       if (!hasVisibleDefaultArgument(NTTP))
3948*67e74705SXin Li         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3949*67e74705SXin Li                                        NewArgs);
3950*67e74705SXin Li 
3951*67e74705SXin Li       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3952*67e74705SXin Li                                                               TemplateLoc,
3953*67e74705SXin Li                                                               RAngleLoc,
3954*67e74705SXin Li                                                               NTTP,
3955*67e74705SXin Li                                                               Converted);
3956*67e74705SXin Li       if (E.isInvalid())
3957*67e74705SXin Li         return true;
3958*67e74705SXin Li 
3959*67e74705SXin Li       Expr *Ex = E.getAs<Expr>();
3960*67e74705SXin Li       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3961*67e74705SXin Li     } else {
3962*67e74705SXin Li       TemplateTemplateParmDecl *TempParm
3963*67e74705SXin Li         = cast<TemplateTemplateParmDecl>(*Param);
3964*67e74705SXin Li 
3965*67e74705SXin Li       if (!hasVisibleDefaultArgument(TempParm))
3966*67e74705SXin Li         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3967*67e74705SXin Li                                        NewArgs);
3968*67e74705SXin Li 
3969*67e74705SXin Li       NestedNameSpecifierLoc QualifierLoc;
3970*67e74705SXin Li       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3971*67e74705SXin Li                                                        TemplateLoc,
3972*67e74705SXin Li                                                        RAngleLoc,
3973*67e74705SXin Li                                                        TempParm,
3974*67e74705SXin Li                                                        Converted,
3975*67e74705SXin Li                                                        QualifierLoc);
3976*67e74705SXin Li       if (Name.isNull())
3977*67e74705SXin Li         return true;
3978*67e74705SXin Li 
3979*67e74705SXin Li       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3980*67e74705SXin Li                            TempParm->getDefaultArgument().getTemplateNameLoc());
3981*67e74705SXin Li     }
3982*67e74705SXin Li 
3983*67e74705SXin Li     // Introduce an instantiation record that describes where we are using
3984*67e74705SXin Li     // the default template argument.
3985*67e74705SXin Li     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3986*67e74705SXin Li                                SourceRange(TemplateLoc, RAngleLoc));
3987*67e74705SXin Li     if (Inst.isInvalid())
3988*67e74705SXin Li       return true;
3989*67e74705SXin Li 
3990*67e74705SXin Li     // Check the default template argument.
3991*67e74705SXin Li     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3992*67e74705SXin Li                               RAngleLoc, 0, Converted))
3993*67e74705SXin Li       return true;
3994*67e74705SXin Li 
3995*67e74705SXin Li     // Core issue 150 (assumed resolution): if this is a template template
3996*67e74705SXin Li     // parameter, keep track of the default template arguments from the
3997*67e74705SXin Li     // template definition.
3998*67e74705SXin Li     if (isTemplateTemplateParameter)
3999*67e74705SXin Li       NewArgs.addArgument(Arg);
4000*67e74705SXin Li 
4001*67e74705SXin Li     // Move to the next template parameter and argument.
4002*67e74705SXin Li     ++Param;
4003*67e74705SXin Li     ++ArgIdx;
4004*67e74705SXin Li   }
4005*67e74705SXin Li 
4006*67e74705SXin Li   // If we're performing a partial argument substitution, allow any trailing
4007*67e74705SXin Li   // pack expansions; they might be empty. This can happen even if
4008*67e74705SXin Li   // PartialTemplateArgs is false (the list of arguments is complete but
4009*67e74705SXin Li   // still dependent).
4010*67e74705SXin Li   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4011*67e74705SXin Li       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
4012*67e74705SXin Li     while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4013*67e74705SXin Li       Converted.push_back(NewArgs[ArgIdx++].getArgument());
4014*67e74705SXin Li   }
4015*67e74705SXin Li 
4016*67e74705SXin Li   // If we have any leftover arguments, then there were too many arguments.
4017*67e74705SXin Li   // Complain and fail.
4018*67e74705SXin Li   if (ArgIdx < NumArgs)
4019*67e74705SXin Li     return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4020*67e74705SXin Li 
4021*67e74705SXin Li   // No problems found with the new argument list, propagate changes back
4022*67e74705SXin Li   // to caller.
4023*67e74705SXin Li   TemplateArgs = std::move(NewArgs);
4024*67e74705SXin Li 
4025*67e74705SXin Li   return false;
4026*67e74705SXin Li }
4027*67e74705SXin Li 
4028*67e74705SXin Li namespace {
4029*67e74705SXin Li   class UnnamedLocalNoLinkageFinder
4030*67e74705SXin Li     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
4031*67e74705SXin Li   {
4032*67e74705SXin Li     Sema &S;
4033*67e74705SXin Li     SourceRange SR;
4034*67e74705SXin Li 
4035*67e74705SXin Li     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4036*67e74705SXin Li 
4037*67e74705SXin Li   public:
UnnamedLocalNoLinkageFinder(Sema & S,SourceRange SR)4038*67e74705SXin Li     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4039*67e74705SXin Li 
Visit(QualType T)4040*67e74705SXin Li     bool Visit(QualType T) {
4041*67e74705SXin Li       return inherited::Visit(T.getTypePtr());
4042*67e74705SXin Li     }
4043*67e74705SXin Li 
4044*67e74705SXin Li #define TYPE(Class, Parent) \
4045*67e74705SXin Li     bool Visit##Class##Type(const Class##Type *);
4046*67e74705SXin Li #define ABSTRACT_TYPE(Class, Parent) \
4047*67e74705SXin Li     bool Visit##Class##Type(const Class##Type *) { return false; }
4048*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Parent) \
4049*67e74705SXin Li     bool Visit##Class##Type(const Class##Type *) { return false; }
4050*67e74705SXin Li #include "clang/AST/TypeNodes.def"
4051*67e74705SXin Li 
4052*67e74705SXin Li     bool VisitTagDecl(const TagDecl *Tag);
4053*67e74705SXin Li     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4054*67e74705SXin Li   };
4055*67e74705SXin Li } // end anonymous namespace
4056*67e74705SXin Li 
VisitBuiltinType(const BuiltinType *)4057*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4058*67e74705SXin Li   return false;
4059*67e74705SXin Li }
4060*67e74705SXin Li 
VisitComplexType(const ComplexType * T)4061*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4062*67e74705SXin Li   return Visit(T->getElementType());
4063*67e74705SXin Li }
4064*67e74705SXin Li 
VisitPointerType(const PointerType * T)4065*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4066*67e74705SXin Li   return Visit(T->getPointeeType());
4067*67e74705SXin Li }
4068*67e74705SXin Li 
VisitBlockPointerType(const BlockPointerType * T)4069*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4070*67e74705SXin Li                                                     const BlockPointerType* T) {
4071*67e74705SXin Li   return Visit(T->getPointeeType());
4072*67e74705SXin Li }
4073*67e74705SXin Li 
VisitLValueReferenceType(const LValueReferenceType * T)4074*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4075*67e74705SXin Li                                                 const LValueReferenceType* T) {
4076*67e74705SXin Li   return Visit(T->getPointeeType());
4077*67e74705SXin Li }
4078*67e74705SXin Li 
VisitRValueReferenceType(const RValueReferenceType * T)4079*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4080*67e74705SXin Li                                                 const RValueReferenceType* T) {
4081*67e74705SXin Li   return Visit(T->getPointeeType());
4082*67e74705SXin Li }
4083*67e74705SXin Li 
VisitMemberPointerType(const MemberPointerType * T)4084*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4085*67e74705SXin Li                                                   const MemberPointerType* T) {
4086*67e74705SXin Li   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4087*67e74705SXin Li }
4088*67e74705SXin Li 
VisitConstantArrayType(const ConstantArrayType * T)4089*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4090*67e74705SXin Li                                                   const ConstantArrayType* T) {
4091*67e74705SXin Li   return Visit(T->getElementType());
4092*67e74705SXin Li }
4093*67e74705SXin Li 
VisitIncompleteArrayType(const IncompleteArrayType * T)4094*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4095*67e74705SXin Li                                                  const IncompleteArrayType* T) {
4096*67e74705SXin Li   return Visit(T->getElementType());
4097*67e74705SXin Li }
4098*67e74705SXin Li 
VisitVariableArrayType(const VariableArrayType * T)4099*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4100*67e74705SXin Li                                                    const VariableArrayType* T) {
4101*67e74705SXin Li   return Visit(T->getElementType());
4102*67e74705SXin Li }
4103*67e74705SXin Li 
VisitDependentSizedArrayType(const DependentSizedArrayType * T)4104*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4105*67e74705SXin Li                                             const DependentSizedArrayType* T) {
4106*67e74705SXin Li   return Visit(T->getElementType());
4107*67e74705SXin Li }
4108*67e74705SXin Li 
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)4109*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4110*67e74705SXin Li                                          const DependentSizedExtVectorType* T) {
4111*67e74705SXin Li   return Visit(T->getElementType());
4112*67e74705SXin Li }
4113*67e74705SXin Li 
VisitVectorType(const VectorType * T)4114*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4115*67e74705SXin Li   return Visit(T->getElementType());
4116*67e74705SXin Li }
4117*67e74705SXin Li 
VisitExtVectorType(const ExtVectorType * T)4118*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4119*67e74705SXin Li   return Visit(T->getElementType());
4120*67e74705SXin Li }
4121*67e74705SXin Li 
VisitFunctionProtoType(const FunctionProtoType * T)4122*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4123*67e74705SXin Li                                                   const FunctionProtoType* T) {
4124*67e74705SXin Li   for (const auto &A : T->param_types()) {
4125*67e74705SXin Li     if (Visit(A))
4126*67e74705SXin Li       return true;
4127*67e74705SXin Li   }
4128*67e74705SXin Li 
4129*67e74705SXin Li   return Visit(T->getReturnType());
4130*67e74705SXin Li }
4131*67e74705SXin Li 
VisitFunctionNoProtoType(const FunctionNoProtoType * T)4132*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4133*67e74705SXin Li                                                const FunctionNoProtoType* T) {
4134*67e74705SXin Li   return Visit(T->getReturnType());
4135*67e74705SXin Li }
4136*67e74705SXin Li 
VisitUnresolvedUsingType(const UnresolvedUsingType *)4137*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4138*67e74705SXin Li                                                   const UnresolvedUsingType*) {
4139*67e74705SXin Li   return false;
4140*67e74705SXin Li }
4141*67e74705SXin Li 
VisitTypeOfExprType(const TypeOfExprType *)4142*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4143*67e74705SXin Li   return false;
4144*67e74705SXin Li }
4145*67e74705SXin Li 
VisitTypeOfType(const TypeOfType * T)4146*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4147*67e74705SXin Li   return Visit(T->getUnderlyingType());
4148*67e74705SXin Li }
4149*67e74705SXin Li 
VisitDecltypeType(const DecltypeType *)4150*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4151*67e74705SXin Li   return false;
4152*67e74705SXin Li }
4153*67e74705SXin Li 
VisitUnaryTransformType(const UnaryTransformType *)4154*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4155*67e74705SXin Li                                                     const UnaryTransformType*) {
4156*67e74705SXin Li   return false;
4157*67e74705SXin Li }
4158*67e74705SXin Li 
VisitAutoType(const AutoType * T)4159*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4160*67e74705SXin Li   return Visit(T->getDeducedType());
4161*67e74705SXin Li }
4162*67e74705SXin Li 
VisitRecordType(const RecordType * T)4163*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4164*67e74705SXin Li   return VisitTagDecl(T->getDecl());
4165*67e74705SXin Li }
4166*67e74705SXin Li 
VisitEnumType(const EnumType * T)4167*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4168*67e74705SXin Li   return VisitTagDecl(T->getDecl());
4169*67e74705SXin Li }
4170*67e74705SXin Li 
VisitTemplateTypeParmType(const TemplateTypeParmType *)4171*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4172*67e74705SXin Li                                                  const TemplateTypeParmType*) {
4173*67e74705SXin Li   return false;
4174*67e74705SXin Li }
4175*67e74705SXin Li 
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *)4176*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4177*67e74705SXin Li                                         const SubstTemplateTypeParmPackType *) {
4178*67e74705SXin Li   return false;
4179*67e74705SXin Li }
4180*67e74705SXin Li 
VisitTemplateSpecializationType(const TemplateSpecializationType *)4181*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4182*67e74705SXin Li                                             const TemplateSpecializationType*) {
4183*67e74705SXin Li   return false;
4184*67e74705SXin Li }
4185*67e74705SXin Li 
VisitInjectedClassNameType(const InjectedClassNameType * T)4186*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4187*67e74705SXin Li                                               const InjectedClassNameType* T) {
4188*67e74705SXin Li   return VisitTagDecl(T->getDecl());
4189*67e74705SXin Li }
4190*67e74705SXin Li 
VisitDependentNameType(const DependentNameType * T)4191*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4192*67e74705SXin Li                                                    const DependentNameType* T) {
4193*67e74705SXin Li   return VisitNestedNameSpecifier(T->getQualifier());
4194*67e74705SXin Li }
4195*67e74705SXin Li 
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)4196*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4197*67e74705SXin Li                                  const DependentTemplateSpecializationType* T) {
4198*67e74705SXin Li   return VisitNestedNameSpecifier(T->getQualifier());
4199*67e74705SXin Li }
4200*67e74705SXin Li 
VisitPackExpansionType(const PackExpansionType * T)4201*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4202*67e74705SXin Li                                                    const PackExpansionType* T) {
4203*67e74705SXin Li   return Visit(T->getPattern());
4204*67e74705SXin Li }
4205*67e74705SXin Li 
VisitObjCObjectType(const ObjCObjectType *)4206*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4207*67e74705SXin Li   return false;
4208*67e74705SXin Li }
4209*67e74705SXin Li 
VisitObjCInterfaceType(const ObjCInterfaceType *)4210*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4211*67e74705SXin Li                                                    const ObjCInterfaceType *) {
4212*67e74705SXin Li   return false;
4213*67e74705SXin Li }
4214*67e74705SXin Li 
VisitObjCObjectPointerType(const ObjCObjectPointerType *)4215*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4216*67e74705SXin Li                                                 const ObjCObjectPointerType *) {
4217*67e74705SXin Li   return false;
4218*67e74705SXin Li }
4219*67e74705SXin Li 
VisitAtomicType(const AtomicType * T)4220*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4221*67e74705SXin Li   return Visit(T->getValueType());
4222*67e74705SXin Li }
4223*67e74705SXin Li 
VisitPipeType(const PipeType * T)4224*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4225*67e74705SXin Li   return false;
4226*67e74705SXin Li }
4227*67e74705SXin Li 
VisitTagDecl(const TagDecl * Tag)4228*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4229*67e74705SXin Li   if (Tag->getDeclContext()->isFunctionOrMethod()) {
4230*67e74705SXin Li     S.Diag(SR.getBegin(),
4231*67e74705SXin Li            S.getLangOpts().CPlusPlus11 ?
4232*67e74705SXin Li              diag::warn_cxx98_compat_template_arg_local_type :
4233*67e74705SXin Li              diag::ext_template_arg_local_type)
4234*67e74705SXin Li       << S.Context.getTypeDeclType(Tag) << SR;
4235*67e74705SXin Li     return true;
4236*67e74705SXin Li   }
4237*67e74705SXin Li 
4238*67e74705SXin Li   if (!Tag->hasNameForLinkage()) {
4239*67e74705SXin Li     S.Diag(SR.getBegin(),
4240*67e74705SXin Li            S.getLangOpts().CPlusPlus11 ?
4241*67e74705SXin Li              diag::warn_cxx98_compat_template_arg_unnamed_type :
4242*67e74705SXin Li              diag::ext_template_arg_unnamed_type) << SR;
4243*67e74705SXin Li     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4244*67e74705SXin Li     return true;
4245*67e74705SXin Li   }
4246*67e74705SXin Li 
4247*67e74705SXin Li   return false;
4248*67e74705SXin Li }
4249*67e74705SXin Li 
VisitNestedNameSpecifier(NestedNameSpecifier * NNS)4250*67e74705SXin Li bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4251*67e74705SXin Li                                                     NestedNameSpecifier *NNS) {
4252*67e74705SXin Li   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4253*67e74705SXin Li     return true;
4254*67e74705SXin Li 
4255*67e74705SXin Li   switch (NNS->getKind()) {
4256*67e74705SXin Li   case NestedNameSpecifier::Identifier:
4257*67e74705SXin Li   case NestedNameSpecifier::Namespace:
4258*67e74705SXin Li   case NestedNameSpecifier::NamespaceAlias:
4259*67e74705SXin Li   case NestedNameSpecifier::Global:
4260*67e74705SXin Li   case NestedNameSpecifier::Super:
4261*67e74705SXin Li     return false;
4262*67e74705SXin Li 
4263*67e74705SXin Li   case NestedNameSpecifier::TypeSpec:
4264*67e74705SXin Li   case NestedNameSpecifier::TypeSpecWithTemplate:
4265*67e74705SXin Li     return Visit(QualType(NNS->getAsType(), 0));
4266*67e74705SXin Li   }
4267*67e74705SXin Li   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4268*67e74705SXin Li }
4269*67e74705SXin Li 
4270*67e74705SXin Li /// \brief Check a template argument against its corresponding
4271*67e74705SXin Li /// template type parameter.
4272*67e74705SXin Li ///
4273*67e74705SXin Li /// This routine implements the semantics of C++ [temp.arg.type]. It
4274*67e74705SXin Li /// returns true if an error occurred, and false otherwise.
CheckTemplateArgument(TemplateTypeParmDecl * Param,TypeSourceInfo * ArgInfo)4275*67e74705SXin Li bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4276*67e74705SXin Li                                  TypeSourceInfo *ArgInfo) {
4277*67e74705SXin Li   assert(ArgInfo && "invalid TypeSourceInfo");
4278*67e74705SXin Li   QualType Arg = ArgInfo->getType();
4279*67e74705SXin Li   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4280*67e74705SXin Li 
4281*67e74705SXin Li   if (Arg->isVariablyModifiedType()) {
4282*67e74705SXin Li     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4283*67e74705SXin Li   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4284*67e74705SXin Li     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4285*67e74705SXin Li   }
4286*67e74705SXin Li 
4287*67e74705SXin Li   // C++03 [temp.arg.type]p2:
4288*67e74705SXin Li   //   A local type, a type with no linkage, an unnamed type or a type
4289*67e74705SXin Li   //   compounded from any of these types shall not be used as a
4290*67e74705SXin Li   //   template-argument for a template type-parameter.
4291*67e74705SXin Li   //
4292*67e74705SXin Li   // C++11 allows these, and even in C++03 we allow them as an extension with
4293*67e74705SXin Li   // a warning.
4294*67e74705SXin Li   bool NeedsCheck;
4295*67e74705SXin Li   if (LangOpts.CPlusPlus11)
4296*67e74705SXin Li     NeedsCheck =
4297*67e74705SXin Li         !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4298*67e74705SXin Li                          SR.getBegin()) ||
4299*67e74705SXin Li         !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4300*67e74705SXin Li                          SR.getBegin());
4301*67e74705SXin Li   else
4302*67e74705SXin Li     NeedsCheck = Arg->hasUnnamedOrLocalType();
4303*67e74705SXin Li 
4304*67e74705SXin Li   if (NeedsCheck) {
4305*67e74705SXin Li     UnnamedLocalNoLinkageFinder Finder(*this, SR);
4306*67e74705SXin Li     (void)Finder.Visit(Context.getCanonicalType(Arg));
4307*67e74705SXin Li   }
4308*67e74705SXin Li 
4309*67e74705SXin Li   return false;
4310*67e74705SXin Li }
4311*67e74705SXin Li 
4312*67e74705SXin Li enum NullPointerValueKind {
4313*67e74705SXin Li   NPV_NotNullPointer,
4314*67e74705SXin Li   NPV_NullPointer,
4315*67e74705SXin Li   NPV_Error
4316*67e74705SXin Li };
4317*67e74705SXin Li 
4318*67e74705SXin Li /// \brief Determine whether the given template argument is a null pointer
4319*67e74705SXin Li /// value of the appropriate type.
4320*67e74705SXin Li static NullPointerValueKind
isNullPointerValueTemplateArgument(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg)4321*67e74705SXin Li isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4322*67e74705SXin Li                                    QualType ParamType, Expr *Arg) {
4323*67e74705SXin Li   if (Arg->isValueDependent() || Arg->isTypeDependent())
4324*67e74705SXin Li     return NPV_NotNullPointer;
4325*67e74705SXin Li 
4326*67e74705SXin Li   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
4327*67e74705SXin Li     llvm_unreachable(
4328*67e74705SXin Li         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
4329*67e74705SXin Li 
4330*67e74705SXin Li   if (!S.getLangOpts().CPlusPlus11)
4331*67e74705SXin Li     return NPV_NotNullPointer;
4332*67e74705SXin Li 
4333*67e74705SXin Li   // Determine whether we have a constant expression.
4334*67e74705SXin Li   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4335*67e74705SXin Li   if (ArgRV.isInvalid())
4336*67e74705SXin Li     return NPV_Error;
4337*67e74705SXin Li   Arg = ArgRV.get();
4338*67e74705SXin Li 
4339*67e74705SXin Li   Expr::EvalResult EvalResult;
4340*67e74705SXin Li   SmallVector<PartialDiagnosticAt, 8> Notes;
4341*67e74705SXin Li   EvalResult.Diag = &Notes;
4342*67e74705SXin Li   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4343*67e74705SXin Li       EvalResult.HasSideEffects) {
4344*67e74705SXin Li     SourceLocation DiagLoc = Arg->getExprLoc();
4345*67e74705SXin Li 
4346*67e74705SXin Li     // If our only note is the usual "invalid subexpression" note, just point
4347*67e74705SXin Li     // the caret at its location rather than producing an essentially
4348*67e74705SXin Li     // redundant note.
4349*67e74705SXin Li     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4350*67e74705SXin Li         diag::note_invalid_subexpr_in_const_expr) {
4351*67e74705SXin Li       DiagLoc = Notes[0].first;
4352*67e74705SXin Li       Notes.clear();
4353*67e74705SXin Li     }
4354*67e74705SXin Li 
4355*67e74705SXin Li     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4356*67e74705SXin Li       << Arg->getType() << Arg->getSourceRange();
4357*67e74705SXin Li     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4358*67e74705SXin Li       S.Diag(Notes[I].first, Notes[I].second);
4359*67e74705SXin Li 
4360*67e74705SXin Li     S.Diag(Param->getLocation(), diag::note_template_param_here);
4361*67e74705SXin Li     return NPV_Error;
4362*67e74705SXin Li   }
4363*67e74705SXin Li 
4364*67e74705SXin Li   // C++11 [temp.arg.nontype]p1:
4365*67e74705SXin Li   //   - an address constant expression of type std::nullptr_t
4366*67e74705SXin Li   if (Arg->getType()->isNullPtrType())
4367*67e74705SXin Li     return NPV_NullPointer;
4368*67e74705SXin Li 
4369*67e74705SXin Li   //   - a constant expression that evaluates to a null pointer value (4.10); or
4370*67e74705SXin Li   //   - a constant expression that evaluates to a null member pointer value
4371*67e74705SXin Li   //     (4.11); or
4372*67e74705SXin Li   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4373*67e74705SXin Li       (EvalResult.Val.isMemberPointer() &&
4374*67e74705SXin Li        !EvalResult.Val.getMemberPointerDecl())) {
4375*67e74705SXin Li     // If our expression has an appropriate type, we've succeeded.
4376*67e74705SXin Li     bool ObjCLifetimeConversion;
4377*67e74705SXin Li     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4378*67e74705SXin Li         S.IsQualificationConversion(Arg->getType(), ParamType, false,
4379*67e74705SXin Li                                      ObjCLifetimeConversion))
4380*67e74705SXin Li       return NPV_NullPointer;
4381*67e74705SXin Li 
4382*67e74705SXin Li     // The types didn't match, but we know we got a null pointer; complain,
4383*67e74705SXin Li     // then recover as if the types were correct.
4384*67e74705SXin Li     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4385*67e74705SXin Li       << Arg->getType() << ParamType << Arg->getSourceRange();
4386*67e74705SXin Li     S.Diag(Param->getLocation(), diag::note_template_param_here);
4387*67e74705SXin Li     return NPV_NullPointer;
4388*67e74705SXin Li   }
4389*67e74705SXin Li 
4390*67e74705SXin Li   // If we don't have a null pointer value, but we do have a NULL pointer
4391*67e74705SXin Li   // constant, suggest a cast to the appropriate type.
4392*67e74705SXin Li   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4393*67e74705SXin Li     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4394*67e74705SXin Li     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4395*67e74705SXin Li         << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4396*67e74705SXin Li         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4397*67e74705SXin Li                                       ")");
4398*67e74705SXin Li     S.Diag(Param->getLocation(), diag::note_template_param_here);
4399*67e74705SXin Li     return NPV_NullPointer;
4400*67e74705SXin Li   }
4401*67e74705SXin Li 
4402*67e74705SXin Li   // FIXME: If we ever want to support general, address-constant expressions
4403*67e74705SXin Li   // as non-type template arguments, we should return the ExprResult here to
4404*67e74705SXin Li   // be interpreted by the caller.
4405*67e74705SXin Li   return NPV_NotNullPointer;
4406*67e74705SXin Li }
4407*67e74705SXin Li 
4408*67e74705SXin Li /// \brief Checks whether the given template argument is compatible with its
4409*67e74705SXin Li /// template parameter.
CheckTemplateArgumentIsCompatibleWithParameter(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,Expr * Arg,QualType ArgType)4410*67e74705SXin Li static bool CheckTemplateArgumentIsCompatibleWithParameter(
4411*67e74705SXin Li     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4412*67e74705SXin Li     Expr *Arg, QualType ArgType) {
4413*67e74705SXin Li   bool ObjCLifetimeConversion;
4414*67e74705SXin Li   if (ParamType->isPointerType() &&
4415*67e74705SXin Li       !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4416*67e74705SXin Li       S.IsQualificationConversion(ArgType, ParamType, false,
4417*67e74705SXin Li                                   ObjCLifetimeConversion)) {
4418*67e74705SXin Li     // For pointer-to-object types, qualification conversions are
4419*67e74705SXin Li     // permitted.
4420*67e74705SXin Li   } else {
4421*67e74705SXin Li     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4422*67e74705SXin Li       if (!ParamRef->getPointeeType()->isFunctionType()) {
4423*67e74705SXin Li         // C++ [temp.arg.nontype]p5b3:
4424*67e74705SXin Li         //   For a non-type template-parameter of type reference to
4425*67e74705SXin Li         //   object, no conversions apply. The type referred to by the
4426*67e74705SXin Li         //   reference may be more cv-qualified than the (otherwise
4427*67e74705SXin Li         //   identical) type of the template- argument. The
4428*67e74705SXin Li         //   template-parameter is bound directly to the
4429*67e74705SXin Li         //   template-argument, which shall be an lvalue.
4430*67e74705SXin Li 
4431*67e74705SXin Li         // FIXME: Other qualifiers?
4432*67e74705SXin Li         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4433*67e74705SXin Li         unsigned ArgQuals = ArgType.getCVRQualifiers();
4434*67e74705SXin Li 
4435*67e74705SXin Li         if ((ParamQuals | ArgQuals) != ParamQuals) {
4436*67e74705SXin Li           S.Diag(Arg->getLocStart(),
4437*67e74705SXin Li                  diag::err_template_arg_ref_bind_ignores_quals)
4438*67e74705SXin Li             << ParamType << Arg->getType() << Arg->getSourceRange();
4439*67e74705SXin Li           S.Diag(Param->getLocation(), diag::note_template_param_here);
4440*67e74705SXin Li           return true;
4441*67e74705SXin Li         }
4442*67e74705SXin Li       }
4443*67e74705SXin Li     }
4444*67e74705SXin Li 
4445*67e74705SXin Li     // At this point, the template argument refers to an object or
4446*67e74705SXin Li     // function with external linkage. We now need to check whether the
4447*67e74705SXin Li     // argument and parameter types are compatible.
4448*67e74705SXin Li     if (!S.Context.hasSameUnqualifiedType(ArgType,
4449*67e74705SXin Li                                           ParamType.getNonReferenceType())) {
4450*67e74705SXin Li       // We can't perform this conversion or binding.
4451*67e74705SXin Li       if (ParamType->isReferenceType())
4452*67e74705SXin Li         S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4453*67e74705SXin Li           << ParamType << ArgIn->getType() << Arg->getSourceRange();
4454*67e74705SXin Li       else
4455*67e74705SXin Li         S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
4456*67e74705SXin Li           << ArgIn->getType() << ParamType << Arg->getSourceRange();
4457*67e74705SXin Li       S.Diag(Param->getLocation(), diag::note_template_param_here);
4458*67e74705SXin Li       return true;
4459*67e74705SXin Li     }
4460*67e74705SXin Li   }
4461*67e74705SXin Li 
4462*67e74705SXin Li   return false;
4463*67e74705SXin Li }
4464*67e74705SXin Li 
4465*67e74705SXin Li /// \brief Checks whether the given template argument is the address
4466*67e74705SXin Li /// of an object or function according to C++ [temp.arg.nontype]p1.
4467*67e74705SXin Li static bool
CheckTemplateArgumentAddressOfObjectOrFunction(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,TemplateArgument & Converted)4468*67e74705SXin Li CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4469*67e74705SXin Li                                                NonTypeTemplateParmDecl *Param,
4470*67e74705SXin Li                                                QualType ParamType,
4471*67e74705SXin Li                                                Expr *ArgIn,
4472*67e74705SXin Li                                                TemplateArgument &Converted) {
4473*67e74705SXin Li   bool Invalid = false;
4474*67e74705SXin Li   Expr *Arg = ArgIn;
4475*67e74705SXin Li   QualType ArgType = Arg->getType();
4476*67e74705SXin Li 
4477*67e74705SXin Li   bool AddressTaken = false;
4478*67e74705SXin Li   SourceLocation AddrOpLoc;
4479*67e74705SXin Li   if (S.getLangOpts().MicrosoftExt) {
4480*67e74705SXin Li     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4481*67e74705SXin Li     // dereference and address-of operators.
4482*67e74705SXin Li     Arg = Arg->IgnoreParenCasts();
4483*67e74705SXin Li 
4484*67e74705SXin Li     bool ExtWarnMSTemplateArg = false;
4485*67e74705SXin Li     UnaryOperatorKind FirstOpKind;
4486*67e74705SXin Li     SourceLocation FirstOpLoc;
4487*67e74705SXin Li     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4488*67e74705SXin Li       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4489*67e74705SXin Li       if (UnOpKind == UO_Deref)
4490*67e74705SXin Li         ExtWarnMSTemplateArg = true;
4491*67e74705SXin Li       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4492*67e74705SXin Li         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4493*67e74705SXin Li         if (!AddrOpLoc.isValid()) {
4494*67e74705SXin Li           FirstOpKind = UnOpKind;
4495*67e74705SXin Li           FirstOpLoc = UnOp->getOperatorLoc();
4496*67e74705SXin Li         }
4497*67e74705SXin Li       } else
4498*67e74705SXin Li         break;
4499*67e74705SXin Li     }
4500*67e74705SXin Li     if (FirstOpLoc.isValid()) {
4501*67e74705SXin Li       if (ExtWarnMSTemplateArg)
4502*67e74705SXin Li         S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4503*67e74705SXin Li           << ArgIn->getSourceRange();
4504*67e74705SXin Li 
4505*67e74705SXin Li       if (FirstOpKind == UO_AddrOf)
4506*67e74705SXin Li         AddressTaken = true;
4507*67e74705SXin Li       else if (Arg->getType()->isPointerType()) {
4508*67e74705SXin Li         // We cannot let pointers get dereferenced here, that is obviously not a
4509*67e74705SXin Li         // constant expression.
4510*67e74705SXin Li         assert(FirstOpKind == UO_Deref);
4511*67e74705SXin Li         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4512*67e74705SXin Li           << Arg->getSourceRange();
4513*67e74705SXin Li       }
4514*67e74705SXin Li     }
4515*67e74705SXin Li   } else {
4516*67e74705SXin Li     // See through any implicit casts we added to fix the type.
4517*67e74705SXin Li     Arg = Arg->IgnoreImpCasts();
4518*67e74705SXin Li 
4519*67e74705SXin Li     // C++ [temp.arg.nontype]p1:
4520*67e74705SXin Li     //
4521*67e74705SXin Li     //   A template-argument for a non-type, non-template
4522*67e74705SXin Li     //   template-parameter shall be one of: [...]
4523*67e74705SXin Li     //
4524*67e74705SXin Li     //     -- the address of an object or function with external
4525*67e74705SXin Li     //        linkage, including function templates and function
4526*67e74705SXin Li     //        template-ids but excluding non-static class members,
4527*67e74705SXin Li     //        expressed as & id-expression where the & is optional if
4528*67e74705SXin Li     //        the name refers to a function or array, or if the
4529*67e74705SXin Li     //        corresponding template-parameter is a reference; or
4530*67e74705SXin Li 
4531*67e74705SXin Li     // In C++98/03 mode, give an extension warning on any extra parentheses.
4532*67e74705SXin Li     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4533*67e74705SXin Li     bool ExtraParens = false;
4534*67e74705SXin Li     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4535*67e74705SXin Li       if (!Invalid && !ExtraParens) {
4536*67e74705SXin Li         S.Diag(Arg->getLocStart(),
4537*67e74705SXin Li                S.getLangOpts().CPlusPlus11
4538*67e74705SXin Li                    ? diag::warn_cxx98_compat_template_arg_extra_parens
4539*67e74705SXin Li                    : diag::ext_template_arg_extra_parens)
4540*67e74705SXin Li             << Arg->getSourceRange();
4541*67e74705SXin Li         ExtraParens = true;
4542*67e74705SXin Li       }
4543*67e74705SXin Li 
4544*67e74705SXin Li       Arg = Parens->getSubExpr();
4545*67e74705SXin Li     }
4546*67e74705SXin Li 
4547*67e74705SXin Li     while (SubstNonTypeTemplateParmExpr *subst =
4548*67e74705SXin Li                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4549*67e74705SXin Li       Arg = subst->getReplacement()->IgnoreImpCasts();
4550*67e74705SXin Li 
4551*67e74705SXin Li     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4552*67e74705SXin Li       if (UnOp->getOpcode() == UO_AddrOf) {
4553*67e74705SXin Li         Arg = UnOp->getSubExpr();
4554*67e74705SXin Li         AddressTaken = true;
4555*67e74705SXin Li         AddrOpLoc = UnOp->getOperatorLoc();
4556*67e74705SXin Li       }
4557*67e74705SXin Li     }
4558*67e74705SXin Li 
4559*67e74705SXin Li     while (SubstNonTypeTemplateParmExpr *subst =
4560*67e74705SXin Li                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4561*67e74705SXin Li       Arg = subst->getReplacement()->IgnoreImpCasts();
4562*67e74705SXin Li   }
4563*67e74705SXin Li 
4564*67e74705SXin Li   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4565*67e74705SXin Li   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4566*67e74705SXin Li 
4567*67e74705SXin Li   // If our parameter has pointer type, check for a null template value.
4568*67e74705SXin Li   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4569*67e74705SXin Li     NullPointerValueKind NPV;
4570*67e74705SXin Li     // dllimport'd entities aren't constant but are available inside of template
4571*67e74705SXin Li     // arguments.
4572*67e74705SXin Li     if (Entity && Entity->hasAttr<DLLImportAttr>())
4573*67e74705SXin Li       NPV = NPV_NotNullPointer;
4574*67e74705SXin Li     else
4575*67e74705SXin Li       NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4576*67e74705SXin Li     switch (NPV) {
4577*67e74705SXin Li     case NPV_NullPointer:
4578*67e74705SXin Li       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4579*67e74705SXin Li       Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4580*67e74705SXin Li                                    /*isNullPtr=*/true);
4581*67e74705SXin Li       return false;
4582*67e74705SXin Li 
4583*67e74705SXin Li     case NPV_Error:
4584*67e74705SXin Li       return true;
4585*67e74705SXin Li 
4586*67e74705SXin Li     case NPV_NotNullPointer:
4587*67e74705SXin Li       break;
4588*67e74705SXin Li     }
4589*67e74705SXin Li   }
4590*67e74705SXin Li 
4591*67e74705SXin Li   // Stop checking the precise nature of the argument if it is value dependent,
4592*67e74705SXin Li   // it should be checked when instantiated.
4593*67e74705SXin Li   if (Arg->isValueDependent()) {
4594*67e74705SXin Li     Converted = TemplateArgument(ArgIn);
4595*67e74705SXin Li     return false;
4596*67e74705SXin Li   }
4597*67e74705SXin Li 
4598*67e74705SXin Li   if (isa<CXXUuidofExpr>(Arg)) {
4599*67e74705SXin Li     if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4600*67e74705SXin Li                                                        ArgIn, Arg, ArgType))
4601*67e74705SXin Li       return true;
4602*67e74705SXin Li 
4603*67e74705SXin Li     Converted = TemplateArgument(ArgIn);
4604*67e74705SXin Li     return false;
4605*67e74705SXin Li   }
4606*67e74705SXin Li 
4607*67e74705SXin Li   if (!DRE) {
4608*67e74705SXin Li     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4609*67e74705SXin Li     << Arg->getSourceRange();
4610*67e74705SXin Li     S.Diag(Param->getLocation(), diag::note_template_param_here);
4611*67e74705SXin Li     return true;
4612*67e74705SXin Li   }
4613*67e74705SXin Li 
4614*67e74705SXin Li   // Cannot refer to non-static data members
4615*67e74705SXin Li   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4616*67e74705SXin Li     S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4617*67e74705SXin Li       << Entity << Arg->getSourceRange();
4618*67e74705SXin Li     S.Diag(Param->getLocation(), diag::note_template_param_here);
4619*67e74705SXin Li     return true;
4620*67e74705SXin Li   }
4621*67e74705SXin Li 
4622*67e74705SXin Li   // Cannot refer to non-static member functions
4623*67e74705SXin Li   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4624*67e74705SXin Li     if (!Method->isStatic()) {
4625*67e74705SXin Li       S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4626*67e74705SXin Li         << Method << Arg->getSourceRange();
4627*67e74705SXin Li       S.Diag(Param->getLocation(), diag::note_template_param_here);
4628*67e74705SXin Li       return true;
4629*67e74705SXin Li     }
4630*67e74705SXin Li   }
4631*67e74705SXin Li 
4632*67e74705SXin Li   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4633*67e74705SXin Li   VarDecl *Var = dyn_cast<VarDecl>(Entity);
4634*67e74705SXin Li 
4635*67e74705SXin Li   // A non-type template argument must refer to an object or function.
4636*67e74705SXin Li   if (!Func && !Var) {
4637*67e74705SXin Li     // We found something, but we don't know specifically what it is.
4638*67e74705SXin Li     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4639*67e74705SXin Li       << Arg->getSourceRange();
4640*67e74705SXin Li     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4641*67e74705SXin Li     return true;
4642*67e74705SXin Li   }
4643*67e74705SXin Li 
4644*67e74705SXin Li   // Address / reference template args must have external linkage in C++98.
4645*67e74705SXin Li   if (Entity->getFormalLinkage() == InternalLinkage) {
4646*67e74705SXin Li     S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4647*67e74705SXin Li              diag::warn_cxx98_compat_template_arg_object_internal :
4648*67e74705SXin Li              diag::ext_template_arg_object_internal)
4649*67e74705SXin Li       << !Func << Entity << Arg->getSourceRange();
4650*67e74705SXin Li     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4651*67e74705SXin Li       << !Func;
4652*67e74705SXin Li   } else if (!Entity->hasLinkage()) {
4653*67e74705SXin Li     S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4654*67e74705SXin Li       << !Func << Entity << Arg->getSourceRange();
4655*67e74705SXin Li     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4656*67e74705SXin Li       << !Func;
4657*67e74705SXin Li     return true;
4658*67e74705SXin Li   }
4659*67e74705SXin Li 
4660*67e74705SXin Li   if (Func) {
4661*67e74705SXin Li     // If the template parameter has pointer type, the function decays.
4662*67e74705SXin Li     if (ParamType->isPointerType() && !AddressTaken)
4663*67e74705SXin Li       ArgType = S.Context.getPointerType(Func->getType());
4664*67e74705SXin Li     else if (AddressTaken && ParamType->isReferenceType()) {
4665*67e74705SXin Li       // If we originally had an address-of operator, but the
4666*67e74705SXin Li       // parameter has reference type, complain and (if things look
4667*67e74705SXin Li       // like they will work) drop the address-of operator.
4668*67e74705SXin Li       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4669*67e74705SXin Li                                             ParamType.getNonReferenceType())) {
4670*67e74705SXin Li         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4671*67e74705SXin Li           << ParamType;
4672*67e74705SXin Li         S.Diag(Param->getLocation(), diag::note_template_param_here);
4673*67e74705SXin Li         return true;
4674*67e74705SXin Li       }
4675*67e74705SXin Li 
4676*67e74705SXin Li       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4677*67e74705SXin Li         << ParamType
4678*67e74705SXin Li         << FixItHint::CreateRemoval(AddrOpLoc);
4679*67e74705SXin Li       S.Diag(Param->getLocation(), diag::note_template_param_here);
4680*67e74705SXin Li 
4681*67e74705SXin Li       ArgType = Func->getType();
4682*67e74705SXin Li     }
4683*67e74705SXin Li   } else {
4684*67e74705SXin Li     // A value of reference type is not an object.
4685*67e74705SXin Li     if (Var->getType()->isReferenceType()) {
4686*67e74705SXin Li       S.Diag(Arg->getLocStart(),
4687*67e74705SXin Li              diag::err_template_arg_reference_var)
4688*67e74705SXin Li         << Var->getType() << Arg->getSourceRange();
4689*67e74705SXin Li       S.Diag(Param->getLocation(), diag::note_template_param_here);
4690*67e74705SXin Li       return true;
4691*67e74705SXin Li     }
4692*67e74705SXin Li 
4693*67e74705SXin Li     // A template argument must have static storage duration.
4694*67e74705SXin Li     if (Var->getTLSKind()) {
4695*67e74705SXin Li       S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4696*67e74705SXin Li         << Arg->getSourceRange();
4697*67e74705SXin Li       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4698*67e74705SXin Li       return true;
4699*67e74705SXin Li     }
4700*67e74705SXin Li 
4701*67e74705SXin Li     // If the template parameter has pointer type, we must have taken
4702*67e74705SXin Li     // the address of this object.
4703*67e74705SXin Li     if (ParamType->isReferenceType()) {
4704*67e74705SXin Li       if (AddressTaken) {
4705*67e74705SXin Li         // If we originally had an address-of operator, but the
4706*67e74705SXin Li         // parameter has reference type, complain and (if things look
4707*67e74705SXin Li         // like they will work) drop the address-of operator.
4708*67e74705SXin Li         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4709*67e74705SXin Li                                             ParamType.getNonReferenceType())) {
4710*67e74705SXin Li           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4711*67e74705SXin Li             << ParamType;
4712*67e74705SXin Li           S.Diag(Param->getLocation(), diag::note_template_param_here);
4713*67e74705SXin Li           return true;
4714*67e74705SXin Li         }
4715*67e74705SXin Li 
4716*67e74705SXin Li         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4717*67e74705SXin Li           << ParamType
4718*67e74705SXin Li           << FixItHint::CreateRemoval(AddrOpLoc);
4719*67e74705SXin Li         S.Diag(Param->getLocation(), diag::note_template_param_here);
4720*67e74705SXin Li 
4721*67e74705SXin Li         ArgType = Var->getType();
4722*67e74705SXin Li       }
4723*67e74705SXin Li     } else if (!AddressTaken && ParamType->isPointerType()) {
4724*67e74705SXin Li       if (Var->getType()->isArrayType()) {
4725*67e74705SXin Li         // Array-to-pointer decay.
4726*67e74705SXin Li         ArgType = S.Context.getArrayDecayedType(Var->getType());
4727*67e74705SXin Li       } else {
4728*67e74705SXin Li         // If the template parameter has pointer type but the address of
4729*67e74705SXin Li         // this object was not taken, complain and (possibly) recover by
4730*67e74705SXin Li         // taking the address of the entity.
4731*67e74705SXin Li         ArgType = S.Context.getPointerType(Var->getType());
4732*67e74705SXin Li         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4733*67e74705SXin Li           S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4734*67e74705SXin Li             << ParamType;
4735*67e74705SXin Li           S.Diag(Param->getLocation(), diag::note_template_param_here);
4736*67e74705SXin Li           return true;
4737*67e74705SXin Li         }
4738*67e74705SXin Li 
4739*67e74705SXin Li         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4740*67e74705SXin Li           << ParamType
4741*67e74705SXin Li           << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4742*67e74705SXin Li 
4743*67e74705SXin Li         S.Diag(Param->getLocation(), diag::note_template_param_here);
4744*67e74705SXin Li       }
4745*67e74705SXin Li     }
4746*67e74705SXin Li   }
4747*67e74705SXin Li 
4748*67e74705SXin Li   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4749*67e74705SXin Li                                                      Arg, ArgType))
4750*67e74705SXin Li     return true;
4751*67e74705SXin Li 
4752*67e74705SXin Li   // Create the template argument.
4753*67e74705SXin Li   Converted =
4754*67e74705SXin Li       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4755*67e74705SXin Li   S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4756*67e74705SXin Li   return false;
4757*67e74705SXin Li }
4758*67e74705SXin Li 
4759*67e74705SXin Li /// \brief Checks whether the given template argument is a pointer to
4760*67e74705SXin Li /// member constant according to C++ [temp.arg.nontype]p1.
CheckTemplateArgumentPointerToMember(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * & ResultArg,TemplateArgument & Converted)4761*67e74705SXin Li static bool CheckTemplateArgumentPointerToMember(Sema &S,
4762*67e74705SXin Li                                                  NonTypeTemplateParmDecl *Param,
4763*67e74705SXin Li                                                  QualType ParamType,
4764*67e74705SXin Li                                                  Expr *&ResultArg,
4765*67e74705SXin Li                                                  TemplateArgument &Converted) {
4766*67e74705SXin Li   bool Invalid = false;
4767*67e74705SXin Li 
4768*67e74705SXin Li   // Check for a null pointer value.
4769*67e74705SXin Li   Expr *Arg = ResultArg;
4770*67e74705SXin Li   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4771*67e74705SXin Li   case NPV_Error:
4772*67e74705SXin Li     return true;
4773*67e74705SXin Li   case NPV_NullPointer:
4774*67e74705SXin Li     S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4775*67e74705SXin Li     Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4776*67e74705SXin Li                                  /*isNullPtr*/true);
4777*67e74705SXin Li     return false;
4778*67e74705SXin Li   case NPV_NotNullPointer:
4779*67e74705SXin Li     break;
4780*67e74705SXin Li   }
4781*67e74705SXin Li 
4782*67e74705SXin Li   bool ObjCLifetimeConversion;
4783*67e74705SXin Li   if (S.IsQualificationConversion(Arg->getType(),
4784*67e74705SXin Li                                   ParamType.getNonReferenceType(),
4785*67e74705SXin Li                                   false, ObjCLifetimeConversion)) {
4786*67e74705SXin Li     Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4787*67e74705SXin Li                               Arg->getValueKind()).get();
4788*67e74705SXin Li     ResultArg = Arg;
4789*67e74705SXin Li   } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4790*67e74705SXin Li                 ParamType.getNonReferenceType())) {
4791*67e74705SXin Li     // We can't perform this conversion.
4792*67e74705SXin Li     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4793*67e74705SXin Li       << Arg->getType() << ParamType << Arg->getSourceRange();
4794*67e74705SXin Li     S.Diag(Param->getLocation(), diag::note_template_param_here);
4795*67e74705SXin Li     return true;
4796*67e74705SXin Li   }
4797*67e74705SXin Li 
4798*67e74705SXin Li   // See through any implicit casts we added to fix the type.
4799*67e74705SXin Li   while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4800*67e74705SXin Li     Arg = Cast->getSubExpr();
4801*67e74705SXin Li 
4802*67e74705SXin Li   // C++ [temp.arg.nontype]p1:
4803*67e74705SXin Li   //
4804*67e74705SXin Li   //   A template-argument for a non-type, non-template
4805*67e74705SXin Li   //   template-parameter shall be one of: [...]
4806*67e74705SXin Li   //
4807*67e74705SXin Li   //     -- a pointer to member expressed as described in 5.3.1.
4808*67e74705SXin Li   DeclRefExpr *DRE = nullptr;
4809*67e74705SXin Li 
4810*67e74705SXin Li   // In C++98/03 mode, give an extension warning on any extra parentheses.
4811*67e74705SXin Li   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4812*67e74705SXin Li   bool ExtraParens = false;
4813*67e74705SXin Li   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4814*67e74705SXin Li     if (!Invalid && !ExtraParens) {
4815*67e74705SXin Li       S.Diag(Arg->getLocStart(),
4816*67e74705SXin Li              S.getLangOpts().CPlusPlus11 ?
4817*67e74705SXin Li                diag::warn_cxx98_compat_template_arg_extra_parens :
4818*67e74705SXin Li                diag::ext_template_arg_extra_parens)
4819*67e74705SXin Li         << Arg->getSourceRange();
4820*67e74705SXin Li       ExtraParens = true;
4821*67e74705SXin Li     }
4822*67e74705SXin Li 
4823*67e74705SXin Li     Arg = Parens->getSubExpr();
4824*67e74705SXin Li   }
4825*67e74705SXin Li 
4826*67e74705SXin Li   while (SubstNonTypeTemplateParmExpr *subst =
4827*67e74705SXin Li            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4828*67e74705SXin Li     Arg = subst->getReplacement()->IgnoreImpCasts();
4829*67e74705SXin Li 
4830*67e74705SXin Li   // A pointer-to-member constant written &Class::member.
4831*67e74705SXin Li   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4832*67e74705SXin Li     if (UnOp->getOpcode() == UO_AddrOf) {
4833*67e74705SXin Li       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4834*67e74705SXin Li       if (DRE && !DRE->getQualifier())
4835*67e74705SXin Li         DRE = nullptr;
4836*67e74705SXin Li     }
4837*67e74705SXin Li   }
4838*67e74705SXin Li   // A constant of pointer-to-member type.
4839*67e74705SXin Li   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4840*67e74705SXin Li     if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4841*67e74705SXin Li       if (VD->getType()->isMemberPointerType()) {
4842*67e74705SXin Li         if (isa<NonTypeTemplateParmDecl>(VD)) {
4843*67e74705SXin Li           if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4844*67e74705SXin Li             Converted = TemplateArgument(Arg);
4845*67e74705SXin Li           } else {
4846*67e74705SXin Li             VD = cast<ValueDecl>(VD->getCanonicalDecl());
4847*67e74705SXin Li             Converted = TemplateArgument(VD, ParamType);
4848*67e74705SXin Li           }
4849*67e74705SXin Li           return Invalid;
4850*67e74705SXin Li         }
4851*67e74705SXin Li       }
4852*67e74705SXin Li     }
4853*67e74705SXin Li 
4854*67e74705SXin Li     DRE = nullptr;
4855*67e74705SXin Li   }
4856*67e74705SXin Li 
4857*67e74705SXin Li   if (!DRE)
4858*67e74705SXin Li     return S.Diag(Arg->getLocStart(),
4859*67e74705SXin Li                   diag::err_template_arg_not_pointer_to_member_form)
4860*67e74705SXin Li       << Arg->getSourceRange();
4861*67e74705SXin Li 
4862*67e74705SXin Li   if (isa<FieldDecl>(DRE->getDecl()) ||
4863*67e74705SXin Li       isa<IndirectFieldDecl>(DRE->getDecl()) ||
4864*67e74705SXin Li       isa<CXXMethodDecl>(DRE->getDecl())) {
4865*67e74705SXin Li     assert((isa<FieldDecl>(DRE->getDecl()) ||
4866*67e74705SXin Li             isa<IndirectFieldDecl>(DRE->getDecl()) ||
4867*67e74705SXin Li             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4868*67e74705SXin Li            "Only non-static member pointers can make it here");
4869*67e74705SXin Li 
4870*67e74705SXin Li     // Okay: this is the address of a non-static member, and therefore
4871*67e74705SXin Li     // a member pointer constant.
4872*67e74705SXin Li     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4873*67e74705SXin Li       Converted = TemplateArgument(Arg);
4874*67e74705SXin Li     } else {
4875*67e74705SXin Li       ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4876*67e74705SXin Li       Converted = TemplateArgument(D, ParamType);
4877*67e74705SXin Li     }
4878*67e74705SXin Li     return Invalid;
4879*67e74705SXin Li   }
4880*67e74705SXin Li 
4881*67e74705SXin Li   // We found something else, but we don't know specifically what it is.
4882*67e74705SXin Li   S.Diag(Arg->getLocStart(),
4883*67e74705SXin Li          diag::err_template_arg_not_pointer_to_member_form)
4884*67e74705SXin Li     << Arg->getSourceRange();
4885*67e74705SXin Li   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4886*67e74705SXin Li   return true;
4887*67e74705SXin Li }
4888*67e74705SXin Li 
4889*67e74705SXin Li /// \brief Check a template argument against its corresponding
4890*67e74705SXin Li /// non-type template parameter.
4891*67e74705SXin Li ///
4892*67e74705SXin Li /// This routine implements the semantics of C++ [temp.arg.nontype].
4893*67e74705SXin Li /// If an error occurred, it returns ExprError(); otherwise, it
4894*67e74705SXin Li /// returns the converted template argument. \p ParamType is the
4895*67e74705SXin Li /// type of the non-type template parameter after it has been instantiated.
CheckTemplateArgument(NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,TemplateArgument & Converted,CheckTemplateArgumentKind CTAK)4896*67e74705SXin Li ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4897*67e74705SXin Li                                        QualType ParamType, Expr *Arg,
4898*67e74705SXin Li                                        TemplateArgument &Converted,
4899*67e74705SXin Li                                        CheckTemplateArgumentKind CTAK) {
4900*67e74705SXin Li   SourceLocation StartLoc = Arg->getLocStart();
4901*67e74705SXin Li 
4902*67e74705SXin Li   // If either the parameter has a dependent type or the argument is
4903*67e74705SXin Li   // type-dependent, there's nothing we can check now.
4904*67e74705SXin Li   if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4905*67e74705SXin Li     // FIXME: Produce a cloned, canonical expression?
4906*67e74705SXin Li     Converted = TemplateArgument(Arg);
4907*67e74705SXin Li     return Arg;
4908*67e74705SXin Li   }
4909*67e74705SXin Li 
4910*67e74705SXin Li   // We should have already dropped all cv-qualifiers by now.
4911*67e74705SXin Li   assert(!ParamType.hasQualifiers() &&
4912*67e74705SXin Li          "non-type template parameter type cannot be qualified");
4913*67e74705SXin Li 
4914*67e74705SXin Li   if (CTAK == CTAK_Deduced &&
4915*67e74705SXin Li       !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4916*67e74705SXin Li     // C++ [temp.deduct.type]p17:
4917*67e74705SXin Li     //   If, in the declaration of a function template with a non-type
4918*67e74705SXin Li     //   template-parameter, the non-type template-parameter is used
4919*67e74705SXin Li     //   in an expression in the function parameter-list and, if the
4920*67e74705SXin Li     //   corresponding template-argument is deduced, the
4921*67e74705SXin Li     //   template-argument type shall match the type of the
4922*67e74705SXin Li     //   template-parameter exactly, except that a template-argument
4923*67e74705SXin Li     //   deduced from an array bound may be of any integral type.
4924*67e74705SXin Li     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4925*67e74705SXin Li       << Arg->getType().getUnqualifiedType()
4926*67e74705SXin Li       << ParamType.getUnqualifiedType();
4927*67e74705SXin Li     Diag(Param->getLocation(), diag::note_template_param_here);
4928*67e74705SXin Li     return ExprError();
4929*67e74705SXin Li   }
4930*67e74705SXin Li 
4931*67e74705SXin Li   if (getLangOpts().CPlusPlus1z) {
4932*67e74705SXin Li     // FIXME: We can do some limited checking for a value-dependent but not
4933*67e74705SXin Li     // type-dependent argument.
4934*67e74705SXin Li     if (Arg->isValueDependent()) {
4935*67e74705SXin Li       Converted = TemplateArgument(Arg);
4936*67e74705SXin Li       return Arg;
4937*67e74705SXin Li     }
4938*67e74705SXin Li 
4939*67e74705SXin Li     // C++1z [temp.arg.nontype]p1:
4940*67e74705SXin Li     //   A template-argument for a non-type template parameter shall be
4941*67e74705SXin Li     //   a converted constant expression of the type of the template-parameter.
4942*67e74705SXin Li     APValue Value;
4943*67e74705SXin Li     ExprResult ArgResult = CheckConvertedConstantExpression(
4944*67e74705SXin Li         Arg, ParamType, Value, CCEK_TemplateArg);
4945*67e74705SXin Li     if (ArgResult.isInvalid())
4946*67e74705SXin Li       return ExprError();
4947*67e74705SXin Li 
4948*67e74705SXin Li     QualType CanonParamType = Context.getCanonicalType(ParamType);
4949*67e74705SXin Li 
4950*67e74705SXin Li     // Convert the APValue to a TemplateArgument.
4951*67e74705SXin Li     switch (Value.getKind()) {
4952*67e74705SXin Li     case APValue::Uninitialized:
4953*67e74705SXin Li       assert(ParamType->isNullPtrType());
4954*67e74705SXin Li       Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4955*67e74705SXin Li       break;
4956*67e74705SXin Li     case APValue::Int:
4957*67e74705SXin Li       assert(ParamType->isIntegralOrEnumerationType());
4958*67e74705SXin Li       Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4959*67e74705SXin Li       break;
4960*67e74705SXin Li     case APValue::MemberPointer: {
4961*67e74705SXin Li       assert(ParamType->isMemberPointerType());
4962*67e74705SXin Li 
4963*67e74705SXin Li       // FIXME: We need TemplateArgument representation and mangling for these.
4964*67e74705SXin Li       if (!Value.getMemberPointerPath().empty()) {
4965*67e74705SXin Li         Diag(Arg->getLocStart(),
4966*67e74705SXin Li              diag::err_template_arg_member_ptr_base_derived_not_supported)
4967*67e74705SXin Li             << Value.getMemberPointerDecl() << ParamType
4968*67e74705SXin Li             << Arg->getSourceRange();
4969*67e74705SXin Li         return ExprError();
4970*67e74705SXin Li       }
4971*67e74705SXin Li 
4972*67e74705SXin Li       auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4973*67e74705SXin Li       Converted = VD ? TemplateArgument(VD, CanonParamType)
4974*67e74705SXin Li                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4975*67e74705SXin Li       break;
4976*67e74705SXin Li     }
4977*67e74705SXin Li     case APValue::LValue: {
4978*67e74705SXin Li       //   For a non-type template-parameter of pointer or reference type,
4979*67e74705SXin Li       //   the value of the constant expression shall not refer to
4980*67e74705SXin Li       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4981*67e74705SXin Li              ParamType->isNullPtrType());
4982*67e74705SXin Li       // -- a temporary object
4983*67e74705SXin Li       // -- a string literal
4984*67e74705SXin Li       // -- the result of a typeid expression, or
4985*67e74705SXin Li       // -- a predefind __func__ variable
4986*67e74705SXin Li       if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4987*67e74705SXin Li         if (isa<CXXUuidofExpr>(E)) {
4988*67e74705SXin Li           Converted = TemplateArgument(const_cast<Expr*>(E));
4989*67e74705SXin Li           break;
4990*67e74705SXin Li         }
4991*67e74705SXin Li         Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4992*67e74705SXin Li           << Arg->getSourceRange();
4993*67e74705SXin Li         return ExprError();
4994*67e74705SXin Li       }
4995*67e74705SXin Li       auto *VD = const_cast<ValueDecl *>(
4996*67e74705SXin Li           Value.getLValueBase().dyn_cast<const ValueDecl *>());
4997*67e74705SXin Li       // -- a subobject
4998*67e74705SXin Li       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4999*67e74705SXin Li           VD && VD->getType()->isArrayType() &&
5000*67e74705SXin Li           Value.getLValuePath()[0].ArrayIndex == 0 &&
5001*67e74705SXin Li           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5002*67e74705SXin Li         // Per defect report (no number yet):
5003*67e74705SXin Li         //   ... other than a pointer to the first element of a complete array
5004*67e74705SXin Li         //       object.
5005*67e74705SXin Li       } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5006*67e74705SXin Li                  Value.isLValueOnePastTheEnd()) {
5007*67e74705SXin Li         Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5008*67e74705SXin Li           << Value.getAsString(Context, ParamType);
5009*67e74705SXin Li         return ExprError();
5010*67e74705SXin Li       }
5011*67e74705SXin Li       assert((VD || !ParamType->isReferenceType()) &&
5012*67e74705SXin Li              "null reference should not be a constant expression");
5013*67e74705SXin Li       assert((!VD || !ParamType->isNullPtrType()) &&
5014*67e74705SXin Li              "non-null value of type nullptr_t?");
5015*67e74705SXin Li       Converted = VD ? TemplateArgument(VD, CanonParamType)
5016*67e74705SXin Li                      : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5017*67e74705SXin Li       break;
5018*67e74705SXin Li     }
5019*67e74705SXin Li     case APValue::AddrLabelDiff:
5020*67e74705SXin Li       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5021*67e74705SXin Li     case APValue::Float:
5022*67e74705SXin Li     case APValue::ComplexInt:
5023*67e74705SXin Li     case APValue::ComplexFloat:
5024*67e74705SXin Li     case APValue::Vector:
5025*67e74705SXin Li     case APValue::Array:
5026*67e74705SXin Li     case APValue::Struct:
5027*67e74705SXin Li     case APValue::Union:
5028*67e74705SXin Li       llvm_unreachable("invalid kind for template argument");
5029*67e74705SXin Li     }
5030*67e74705SXin Li 
5031*67e74705SXin Li     return ArgResult.get();
5032*67e74705SXin Li   }
5033*67e74705SXin Li 
5034*67e74705SXin Li   // C++ [temp.arg.nontype]p5:
5035*67e74705SXin Li   //   The following conversions are performed on each expression used
5036*67e74705SXin Li   //   as a non-type template-argument. If a non-type
5037*67e74705SXin Li   //   template-argument cannot be converted to the type of the
5038*67e74705SXin Li   //   corresponding template-parameter then the program is
5039*67e74705SXin Li   //   ill-formed.
5040*67e74705SXin Li   if (ParamType->isIntegralOrEnumerationType()) {
5041*67e74705SXin Li     // C++11:
5042*67e74705SXin Li     //   -- for a non-type template-parameter of integral or
5043*67e74705SXin Li     //      enumeration type, conversions permitted in a converted
5044*67e74705SXin Li     //      constant expression are applied.
5045*67e74705SXin Li     //
5046*67e74705SXin Li     // C++98:
5047*67e74705SXin Li     //   -- for a non-type template-parameter of integral or
5048*67e74705SXin Li     //      enumeration type, integral promotions (4.5) and integral
5049*67e74705SXin Li     //      conversions (4.7) are applied.
5050*67e74705SXin Li 
5051*67e74705SXin Li     if (getLangOpts().CPlusPlus11) {
5052*67e74705SXin Li       // We can't check arbitrary value-dependent arguments.
5053*67e74705SXin Li       // FIXME: If there's no viable conversion to the template parameter type,
5054*67e74705SXin Li       // we should be able to diagnose that prior to instantiation.
5055*67e74705SXin Li       if (Arg->isValueDependent()) {
5056*67e74705SXin Li         Converted = TemplateArgument(Arg);
5057*67e74705SXin Li         return Arg;
5058*67e74705SXin Li       }
5059*67e74705SXin Li 
5060*67e74705SXin Li       // C++ [temp.arg.nontype]p1:
5061*67e74705SXin Li       //   A template-argument for a non-type, non-template template-parameter
5062*67e74705SXin Li       //   shall be one of:
5063*67e74705SXin Li       //
5064*67e74705SXin Li       //     -- for a non-type template-parameter of integral or enumeration
5065*67e74705SXin Li       //        type, a converted constant expression of the type of the
5066*67e74705SXin Li       //        template-parameter; or
5067*67e74705SXin Li       llvm::APSInt Value;
5068*67e74705SXin Li       ExprResult ArgResult =
5069*67e74705SXin Li         CheckConvertedConstantExpression(Arg, ParamType, Value,
5070*67e74705SXin Li                                          CCEK_TemplateArg);
5071*67e74705SXin Li       if (ArgResult.isInvalid())
5072*67e74705SXin Li         return ExprError();
5073*67e74705SXin Li 
5074*67e74705SXin Li       // Widen the argument value to sizeof(parameter type). This is almost
5075*67e74705SXin Li       // always a no-op, except when the parameter type is bool. In
5076*67e74705SXin Li       // that case, this may extend the argument from 1 bit to 8 bits.
5077*67e74705SXin Li       QualType IntegerType = ParamType;
5078*67e74705SXin Li       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5079*67e74705SXin Li         IntegerType = Enum->getDecl()->getIntegerType();
5080*67e74705SXin Li       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5081*67e74705SXin Li 
5082*67e74705SXin Li       Converted = TemplateArgument(Context, Value,
5083*67e74705SXin Li                                    Context.getCanonicalType(ParamType));
5084*67e74705SXin Li       return ArgResult;
5085*67e74705SXin Li     }
5086*67e74705SXin Li 
5087*67e74705SXin Li     ExprResult ArgResult = DefaultLvalueConversion(Arg);
5088*67e74705SXin Li     if (ArgResult.isInvalid())
5089*67e74705SXin Li       return ExprError();
5090*67e74705SXin Li     Arg = ArgResult.get();
5091*67e74705SXin Li 
5092*67e74705SXin Li     QualType ArgType = Arg->getType();
5093*67e74705SXin Li 
5094*67e74705SXin Li     // C++ [temp.arg.nontype]p1:
5095*67e74705SXin Li     //   A template-argument for a non-type, non-template
5096*67e74705SXin Li     //   template-parameter shall be one of:
5097*67e74705SXin Li     //
5098*67e74705SXin Li     //     -- an integral constant-expression of integral or enumeration
5099*67e74705SXin Li     //        type; or
5100*67e74705SXin Li     //     -- the name of a non-type template-parameter; or
5101*67e74705SXin Li     SourceLocation NonConstantLoc;
5102*67e74705SXin Li     llvm::APSInt Value;
5103*67e74705SXin Li     if (!ArgType->isIntegralOrEnumerationType()) {
5104*67e74705SXin Li       Diag(Arg->getLocStart(),
5105*67e74705SXin Li            diag::err_template_arg_not_integral_or_enumeral)
5106*67e74705SXin Li         << ArgType << Arg->getSourceRange();
5107*67e74705SXin Li       Diag(Param->getLocation(), diag::note_template_param_here);
5108*67e74705SXin Li       return ExprError();
5109*67e74705SXin Li     } else if (!Arg->isValueDependent()) {
5110*67e74705SXin Li       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5111*67e74705SXin Li         QualType T;
5112*67e74705SXin Li 
5113*67e74705SXin Li       public:
5114*67e74705SXin Li         TmplArgICEDiagnoser(QualType T) : T(T) { }
5115*67e74705SXin Li 
5116*67e74705SXin Li         void diagnoseNotICE(Sema &S, SourceLocation Loc,
5117*67e74705SXin Li                             SourceRange SR) override {
5118*67e74705SXin Li           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5119*67e74705SXin Li         }
5120*67e74705SXin Li       } Diagnoser(ArgType);
5121*67e74705SXin Li 
5122*67e74705SXin Li       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5123*67e74705SXin Li                                             false).get();
5124*67e74705SXin Li       if (!Arg)
5125*67e74705SXin Li         return ExprError();
5126*67e74705SXin Li     }
5127*67e74705SXin Li 
5128*67e74705SXin Li     // From here on out, all we care about is the unqualified form
5129*67e74705SXin Li     // of the argument type.
5130*67e74705SXin Li     ArgType = ArgType.getUnqualifiedType();
5131*67e74705SXin Li 
5132*67e74705SXin Li     // Try to convert the argument to the parameter's type.
5133*67e74705SXin Li     if (Context.hasSameType(ParamType, ArgType)) {
5134*67e74705SXin Li       // Okay: no conversion necessary
5135*67e74705SXin Li     } else if (ParamType->isBooleanType()) {
5136*67e74705SXin Li       // This is an integral-to-boolean conversion.
5137*67e74705SXin Li       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5138*67e74705SXin Li     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5139*67e74705SXin Li                !ParamType->isEnumeralType()) {
5140*67e74705SXin Li       // This is an integral promotion or conversion.
5141*67e74705SXin Li       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5142*67e74705SXin Li     } else {
5143*67e74705SXin Li       // We can't perform this conversion.
5144*67e74705SXin Li       Diag(Arg->getLocStart(),
5145*67e74705SXin Li            diag::err_template_arg_not_convertible)
5146*67e74705SXin Li         << Arg->getType() << ParamType << Arg->getSourceRange();
5147*67e74705SXin Li       Diag(Param->getLocation(), diag::note_template_param_here);
5148*67e74705SXin Li       return ExprError();
5149*67e74705SXin Li     }
5150*67e74705SXin Li 
5151*67e74705SXin Li     // Add the value of this argument to the list of converted
5152*67e74705SXin Li     // arguments. We use the bitwidth and signedness of the template
5153*67e74705SXin Li     // parameter.
5154*67e74705SXin Li     if (Arg->isValueDependent()) {
5155*67e74705SXin Li       // The argument is value-dependent. Create a new
5156*67e74705SXin Li       // TemplateArgument with the converted expression.
5157*67e74705SXin Li       Converted = TemplateArgument(Arg);
5158*67e74705SXin Li       return Arg;
5159*67e74705SXin Li     }
5160*67e74705SXin Li 
5161*67e74705SXin Li     QualType IntegerType = Context.getCanonicalType(ParamType);
5162*67e74705SXin Li     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5163*67e74705SXin Li       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5164*67e74705SXin Li 
5165*67e74705SXin Li     if (ParamType->isBooleanType()) {
5166*67e74705SXin Li       // Value must be zero or one.
5167*67e74705SXin Li       Value = Value != 0;
5168*67e74705SXin Li       unsigned AllowedBits = Context.getTypeSize(IntegerType);
5169*67e74705SXin Li       if (Value.getBitWidth() != AllowedBits)
5170*67e74705SXin Li         Value = Value.extOrTrunc(AllowedBits);
5171*67e74705SXin Li       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5172*67e74705SXin Li     } else {
5173*67e74705SXin Li       llvm::APSInt OldValue = Value;
5174*67e74705SXin Li 
5175*67e74705SXin Li       // Coerce the template argument's value to the value it will have
5176*67e74705SXin Li       // based on the template parameter's type.
5177*67e74705SXin Li       unsigned AllowedBits = Context.getTypeSize(IntegerType);
5178*67e74705SXin Li       if (Value.getBitWidth() != AllowedBits)
5179*67e74705SXin Li         Value = Value.extOrTrunc(AllowedBits);
5180*67e74705SXin Li       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5181*67e74705SXin Li 
5182*67e74705SXin Li       // Complain if an unsigned parameter received a negative value.
5183*67e74705SXin Li       if (IntegerType->isUnsignedIntegerOrEnumerationType()
5184*67e74705SXin Li                && (OldValue.isSigned() && OldValue.isNegative())) {
5185*67e74705SXin Li         Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5186*67e74705SXin Li           << OldValue.toString(10) << Value.toString(10) << Param->getType()
5187*67e74705SXin Li           << Arg->getSourceRange();
5188*67e74705SXin Li         Diag(Param->getLocation(), diag::note_template_param_here);
5189*67e74705SXin Li       }
5190*67e74705SXin Li 
5191*67e74705SXin Li       // Complain if we overflowed the template parameter's type.
5192*67e74705SXin Li       unsigned RequiredBits;
5193*67e74705SXin Li       if (IntegerType->isUnsignedIntegerOrEnumerationType())
5194*67e74705SXin Li         RequiredBits = OldValue.getActiveBits();
5195*67e74705SXin Li       else if (OldValue.isUnsigned())
5196*67e74705SXin Li         RequiredBits = OldValue.getActiveBits() + 1;
5197*67e74705SXin Li       else
5198*67e74705SXin Li         RequiredBits = OldValue.getMinSignedBits();
5199*67e74705SXin Li       if (RequiredBits > AllowedBits) {
5200*67e74705SXin Li         Diag(Arg->getLocStart(),
5201*67e74705SXin Li              diag::warn_template_arg_too_large)
5202*67e74705SXin Li           << OldValue.toString(10) << Value.toString(10) << Param->getType()
5203*67e74705SXin Li           << Arg->getSourceRange();
5204*67e74705SXin Li         Diag(Param->getLocation(), diag::note_template_param_here);
5205*67e74705SXin Li       }
5206*67e74705SXin Li     }
5207*67e74705SXin Li 
5208*67e74705SXin Li     Converted = TemplateArgument(Context, Value,
5209*67e74705SXin Li                                  ParamType->isEnumeralType()
5210*67e74705SXin Li                                    ? Context.getCanonicalType(ParamType)
5211*67e74705SXin Li                                    : IntegerType);
5212*67e74705SXin Li     return Arg;
5213*67e74705SXin Li   }
5214*67e74705SXin Li 
5215*67e74705SXin Li   QualType ArgType = Arg->getType();
5216*67e74705SXin Li   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5217*67e74705SXin Li 
5218*67e74705SXin Li   // Handle pointer-to-function, reference-to-function, and
5219*67e74705SXin Li   // pointer-to-member-function all in (roughly) the same way.
5220*67e74705SXin Li   if (// -- For a non-type template-parameter of type pointer to
5221*67e74705SXin Li       //    function, only the function-to-pointer conversion (4.3) is
5222*67e74705SXin Li       //    applied. If the template-argument represents a set of
5223*67e74705SXin Li       //    overloaded functions (or a pointer to such), the matching
5224*67e74705SXin Li       //    function is selected from the set (13.4).
5225*67e74705SXin Li       (ParamType->isPointerType() &&
5226*67e74705SXin Li        ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5227*67e74705SXin Li       // -- For a non-type template-parameter of type reference to
5228*67e74705SXin Li       //    function, no conversions apply. If the template-argument
5229*67e74705SXin Li       //    represents a set of overloaded functions, the matching
5230*67e74705SXin Li       //    function is selected from the set (13.4).
5231*67e74705SXin Li       (ParamType->isReferenceType() &&
5232*67e74705SXin Li        ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5233*67e74705SXin Li       // -- For a non-type template-parameter of type pointer to
5234*67e74705SXin Li       //    member function, no conversions apply. If the
5235*67e74705SXin Li       //    template-argument represents a set of overloaded member
5236*67e74705SXin Li       //    functions, the matching member function is selected from
5237*67e74705SXin Li       //    the set (13.4).
5238*67e74705SXin Li       (ParamType->isMemberPointerType() &&
5239*67e74705SXin Li        ParamType->getAs<MemberPointerType>()->getPointeeType()
5240*67e74705SXin Li          ->isFunctionType())) {
5241*67e74705SXin Li 
5242*67e74705SXin Li     if (Arg->getType() == Context.OverloadTy) {
5243*67e74705SXin Li       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5244*67e74705SXin Li                                                                 true,
5245*67e74705SXin Li                                                                 FoundResult)) {
5246*67e74705SXin Li         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5247*67e74705SXin Li           return ExprError();
5248*67e74705SXin Li 
5249*67e74705SXin Li         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5250*67e74705SXin Li         ArgType = Arg->getType();
5251*67e74705SXin Li       } else
5252*67e74705SXin Li         return ExprError();
5253*67e74705SXin Li     }
5254*67e74705SXin Li 
5255*67e74705SXin Li     if (!ParamType->isMemberPointerType()) {
5256*67e74705SXin Li       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5257*67e74705SXin Li                                                          ParamType,
5258*67e74705SXin Li                                                          Arg, Converted))
5259*67e74705SXin Li         return ExprError();
5260*67e74705SXin Li       return Arg;
5261*67e74705SXin Li     }
5262*67e74705SXin Li 
5263*67e74705SXin Li     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5264*67e74705SXin Li                                              Converted))
5265*67e74705SXin Li       return ExprError();
5266*67e74705SXin Li     return Arg;
5267*67e74705SXin Li   }
5268*67e74705SXin Li 
5269*67e74705SXin Li   if (ParamType->isPointerType()) {
5270*67e74705SXin Li     //   -- for a non-type template-parameter of type pointer to
5271*67e74705SXin Li     //      object, qualification conversions (4.4) and the
5272*67e74705SXin Li     //      array-to-pointer conversion (4.2) are applied.
5273*67e74705SXin Li     // C++0x also allows a value of std::nullptr_t.
5274*67e74705SXin Li     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5275*67e74705SXin Li            "Only object pointers allowed here");
5276*67e74705SXin Li 
5277*67e74705SXin Li     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5278*67e74705SXin Li                                                        ParamType,
5279*67e74705SXin Li                                                        Arg, Converted))
5280*67e74705SXin Li       return ExprError();
5281*67e74705SXin Li     return Arg;
5282*67e74705SXin Li   }
5283*67e74705SXin Li 
5284*67e74705SXin Li   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5285*67e74705SXin Li     //   -- For a non-type template-parameter of type reference to
5286*67e74705SXin Li     //      object, no conversions apply. The type referred to by the
5287*67e74705SXin Li     //      reference may be more cv-qualified than the (otherwise
5288*67e74705SXin Li     //      identical) type of the template-argument. The
5289*67e74705SXin Li     //      template-parameter is bound directly to the
5290*67e74705SXin Li     //      template-argument, which must be an lvalue.
5291*67e74705SXin Li     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5292*67e74705SXin Li            "Only object references allowed here");
5293*67e74705SXin Li 
5294*67e74705SXin Li     if (Arg->getType() == Context.OverloadTy) {
5295*67e74705SXin Li       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5296*67e74705SXin Li                                                  ParamRefType->getPointeeType(),
5297*67e74705SXin Li                                                                 true,
5298*67e74705SXin Li                                                                 FoundResult)) {
5299*67e74705SXin Li         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5300*67e74705SXin Li           return ExprError();
5301*67e74705SXin Li 
5302*67e74705SXin Li         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5303*67e74705SXin Li         ArgType = Arg->getType();
5304*67e74705SXin Li       } else
5305*67e74705SXin Li         return ExprError();
5306*67e74705SXin Li     }
5307*67e74705SXin Li 
5308*67e74705SXin Li     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5309*67e74705SXin Li                                                        ParamType,
5310*67e74705SXin Li                                                        Arg, Converted))
5311*67e74705SXin Li       return ExprError();
5312*67e74705SXin Li     return Arg;
5313*67e74705SXin Li   }
5314*67e74705SXin Li 
5315*67e74705SXin Li   // Deal with parameters of type std::nullptr_t.
5316*67e74705SXin Li   if (ParamType->isNullPtrType()) {
5317*67e74705SXin Li     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5318*67e74705SXin Li       Converted = TemplateArgument(Arg);
5319*67e74705SXin Li       return Arg;
5320*67e74705SXin Li     }
5321*67e74705SXin Li 
5322*67e74705SXin Li     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5323*67e74705SXin Li     case NPV_NotNullPointer:
5324*67e74705SXin Li       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5325*67e74705SXin Li         << Arg->getType() << ParamType;
5326*67e74705SXin Li       Diag(Param->getLocation(), diag::note_template_param_here);
5327*67e74705SXin Li       return ExprError();
5328*67e74705SXin Li 
5329*67e74705SXin Li     case NPV_Error:
5330*67e74705SXin Li       return ExprError();
5331*67e74705SXin Li 
5332*67e74705SXin Li     case NPV_NullPointer:
5333*67e74705SXin Li       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5334*67e74705SXin Li       Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5335*67e74705SXin Li                                    /*isNullPtr*/true);
5336*67e74705SXin Li       return Arg;
5337*67e74705SXin Li     }
5338*67e74705SXin Li   }
5339*67e74705SXin Li 
5340*67e74705SXin Li   //     -- For a non-type template-parameter of type pointer to data
5341*67e74705SXin Li   //        member, qualification conversions (4.4) are applied.
5342*67e74705SXin Li   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5343*67e74705SXin Li 
5344*67e74705SXin Li   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5345*67e74705SXin Li                                            Converted))
5346*67e74705SXin Li     return ExprError();
5347*67e74705SXin Li   return Arg;
5348*67e74705SXin Li }
5349*67e74705SXin Li 
5350*67e74705SXin Li /// \brief Check a template argument against its corresponding
5351*67e74705SXin Li /// template template parameter.
5352*67e74705SXin Li ///
5353*67e74705SXin Li /// This routine implements the semantics of C++ [temp.arg.template].
5354*67e74705SXin Li /// It returns true if an error occurred, and false otherwise.
CheckTemplateArgument(TemplateTemplateParmDecl * Param,TemplateArgumentLoc & Arg,unsigned ArgumentPackIndex)5355*67e74705SXin Li bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5356*67e74705SXin Li                                  TemplateArgumentLoc &Arg,
5357*67e74705SXin Li                                  unsigned ArgumentPackIndex) {
5358*67e74705SXin Li   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5359*67e74705SXin Li   TemplateDecl *Template = Name.getAsTemplateDecl();
5360*67e74705SXin Li   if (!Template) {
5361*67e74705SXin Li     // Any dependent template name is fine.
5362*67e74705SXin Li     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5363*67e74705SXin Li     return false;
5364*67e74705SXin Li   }
5365*67e74705SXin Li 
5366*67e74705SXin Li   // C++0x [temp.arg.template]p1:
5367*67e74705SXin Li   //   A template-argument for a template template-parameter shall be
5368*67e74705SXin Li   //   the name of a class template or an alias template, expressed as an
5369*67e74705SXin Li   //   id-expression. When the template-argument names a class template, only
5370*67e74705SXin Li   //   primary class templates are considered when matching the
5371*67e74705SXin Li   //   template template argument with the corresponding parameter;
5372*67e74705SXin Li   //   partial specializations are not considered even if their
5373*67e74705SXin Li   //   parameter lists match that of the template template parameter.
5374*67e74705SXin Li   //
5375*67e74705SXin Li   // Note that we also allow template template parameters here, which
5376*67e74705SXin Li   // will happen when we are dealing with, e.g., class template
5377*67e74705SXin Li   // partial specializations.
5378*67e74705SXin Li   if (!isa<ClassTemplateDecl>(Template) &&
5379*67e74705SXin Li       !isa<TemplateTemplateParmDecl>(Template) &&
5380*67e74705SXin Li       !isa<TypeAliasTemplateDecl>(Template) &&
5381*67e74705SXin Li       !isa<BuiltinTemplateDecl>(Template)) {
5382*67e74705SXin Li     assert(isa<FunctionTemplateDecl>(Template) &&
5383*67e74705SXin Li            "Only function templates are possible here");
5384*67e74705SXin Li     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
5385*67e74705SXin Li     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5386*67e74705SXin Li       << Template;
5387*67e74705SXin Li   }
5388*67e74705SXin Li 
5389*67e74705SXin Li   TemplateParameterList *Params = Param->getTemplateParameters();
5390*67e74705SXin Li   if (Param->isExpandedParameterPack())
5391*67e74705SXin Li     Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5392*67e74705SXin Li 
5393*67e74705SXin Li   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5394*67e74705SXin Li                                          Params,
5395*67e74705SXin Li                                          true,
5396*67e74705SXin Li                                          TPL_TemplateTemplateArgumentMatch,
5397*67e74705SXin Li                                          Arg.getLocation());
5398*67e74705SXin Li }
5399*67e74705SXin Li 
5400*67e74705SXin Li /// \brief Given a non-type template argument that refers to a
5401*67e74705SXin Li /// declaration and the type of its corresponding non-type template
5402*67e74705SXin Li /// parameter, produce an expression that properly refers to that
5403*67e74705SXin Li /// declaration.
5404*67e74705SXin Li ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument & Arg,QualType ParamType,SourceLocation Loc)5405*67e74705SXin Li Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5406*67e74705SXin Li                                               QualType ParamType,
5407*67e74705SXin Li                                               SourceLocation Loc) {
5408*67e74705SXin Li   // C++ [temp.param]p8:
5409*67e74705SXin Li   //
5410*67e74705SXin Li   //   A non-type template-parameter of type "array of T" or
5411*67e74705SXin Li   //   "function returning T" is adjusted to be of type "pointer to
5412*67e74705SXin Li   //   T" or "pointer to function returning T", respectively.
5413*67e74705SXin Li   if (ParamType->isArrayType())
5414*67e74705SXin Li     ParamType = Context.getArrayDecayedType(ParamType);
5415*67e74705SXin Li   else if (ParamType->isFunctionType())
5416*67e74705SXin Li     ParamType = Context.getPointerType(ParamType);
5417*67e74705SXin Li 
5418*67e74705SXin Li   // For a NULL non-type template argument, return nullptr casted to the
5419*67e74705SXin Li   // parameter's type.
5420*67e74705SXin Li   if (Arg.getKind() == TemplateArgument::NullPtr) {
5421*67e74705SXin Li     return ImpCastExprToType(
5422*67e74705SXin Li              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5423*67e74705SXin Li                              ParamType,
5424*67e74705SXin Li                              ParamType->getAs<MemberPointerType>()
5425*67e74705SXin Li                                ? CK_NullToMemberPointer
5426*67e74705SXin Li                                : CK_NullToPointer);
5427*67e74705SXin Li   }
5428*67e74705SXin Li   assert(Arg.getKind() == TemplateArgument::Declaration &&
5429*67e74705SXin Li          "Only declaration template arguments permitted here");
5430*67e74705SXin Li 
5431*67e74705SXin Li   ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5432*67e74705SXin Li 
5433*67e74705SXin Li   if (VD->getDeclContext()->isRecord() &&
5434*67e74705SXin Li       (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5435*67e74705SXin Li        isa<IndirectFieldDecl>(VD))) {
5436*67e74705SXin Li     // If the value is a class member, we might have a pointer-to-member.
5437*67e74705SXin Li     // Determine whether the non-type template template parameter is of
5438*67e74705SXin Li     // pointer-to-member type. If so, we need to build an appropriate
5439*67e74705SXin Li     // expression for a pointer-to-member, since a "normal" DeclRefExpr
5440*67e74705SXin Li     // would refer to the member itself.
5441*67e74705SXin Li     if (ParamType->isMemberPointerType()) {
5442*67e74705SXin Li       QualType ClassType
5443*67e74705SXin Li         = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5444*67e74705SXin Li       NestedNameSpecifier *Qualifier
5445*67e74705SXin Li         = NestedNameSpecifier::Create(Context, nullptr, false,
5446*67e74705SXin Li                                       ClassType.getTypePtr());
5447*67e74705SXin Li       CXXScopeSpec SS;
5448*67e74705SXin Li       SS.MakeTrivial(Context, Qualifier, Loc);
5449*67e74705SXin Li 
5450*67e74705SXin Li       // The actual value-ness of this is unimportant, but for
5451*67e74705SXin Li       // internal consistency's sake, references to instance methods
5452*67e74705SXin Li       // are r-values.
5453*67e74705SXin Li       ExprValueKind VK = VK_LValue;
5454*67e74705SXin Li       if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5455*67e74705SXin Li         VK = VK_RValue;
5456*67e74705SXin Li 
5457*67e74705SXin Li       ExprResult RefExpr = BuildDeclRefExpr(VD,
5458*67e74705SXin Li                                             VD->getType().getNonReferenceType(),
5459*67e74705SXin Li                                             VK,
5460*67e74705SXin Li                                             Loc,
5461*67e74705SXin Li                                             &SS);
5462*67e74705SXin Li       if (RefExpr.isInvalid())
5463*67e74705SXin Li         return ExprError();
5464*67e74705SXin Li 
5465*67e74705SXin Li       RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5466*67e74705SXin Li 
5467*67e74705SXin Li       // We might need to perform a trailing qualification conversion, since
5468*67e74705SXin Li       // the element type on the parameter could be more qualified than the
5469*67e74705SXin Li       // element type in the expression we constructed.
5470*67e74705SXin Li       bool ObjCLifetimeConversion;
5471*67e74705SXin Li       if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5472*67e74705SXin Li                                     ParamType.getUnqualifiedType(), false,
5473*67e74705SXin Li                                     ObjCLifetimeConversion))
5474*67e74705SXin Li         RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5475*67e74705SXin Li 
5476*67e74705SXin Li       assert(!RefExpr.isInvalid() &&
5477*67e74705SXin Li              Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5478*67e74705SXin Li                                  ParamType.getUnqualifiedType()));
5479*67e74705SXin Li       return RefExpr;
5480*67e74705SXin Li     }
5481*67e74705SXin Li   }
5482*67e74705SXin Li 
5483*67e74705SXin Li   QualType T = VD->getType().getNonReferenceType();
5484*67e74705SXin Li 
5485*67e74705SXin Li   if (ParamType->isPointerType()) {
5486*67e74705SXin Li     // When the non-type template parameter is a pointer, take the
5487*67e74705SXin Li     // address of the declaration.
5488*67e74705SXin Li     ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5489*67e74705SXin Li     if (RefExpr.isInvalid())
5490*67e74705SXin Li       return ExprError();
5491*67e74705SXin Li 
5492*67e74705SXin Li     if (T->isFunctionType() || T->isArrayType()) {
5493*67e74705SXin Li       // Decay functions and arrays.
5494*67e74705SXin Li       RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5495*67e74705SXin Li       if (RefExpr.isInvalid())
5496*67e74705SXin Li         return ExprError();
5497*67e74705SXin Li 
5498*67e74705SXin Li       return RefExpr;
5499*67e74705SXin Li     }
5500*67e74705SXin Li 
5501*67e74705SXin Li     // Take the address of everything else
5502*67e74705SXin Li     return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5503*67e74705SXin Li   }
5504*67e74705SXin Li 
5505*67e74705SXin Li   ExprValueKind VK = VK_RValue;
5506*67e74705SXin Li 
5507*67e74705SXin Li   // If the non-type template parameter has reference type, qualify the
5508*67e74705SXin Li   // resulting declaration reference with the extra qualifiers on the
5509*67e74705SXin Li   // type that the reference refers to.
5510*67e74705SXin Li   if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5511*67e74705SXin Li     VK = VK_LValue;
5512*67e74705SXin Li     T = Context.getQualifiedType(T,
5513*67e74705SXin Li                               TargetRef->getPointeeType().getQualifiers());
5514*67e74705SXin Li   } else if (isa<FunctionDecl>(VD)) {
5515*67e74705SXin Li     // References to functions are always lvalues.
5516*67e74705SXin Li     VK = VK_LValue;
5517*67e74705SXin Li   }
5518*67e74705SXin Li 
5519*67e74705SXin Li   return BuildDeclRefExpr(VD, T, VK, Loc);
5520*67e74705SXin Li }
5521*67e74705SXin Li 
5522*67e74705SXin Li /// \brief Construct a new expression that refers to the given
5523*67e74705SXin Li /// integral template argument with the given source-location
5524*67e74705SXin Li /// information.
5525*67e74705SXin Li ///
5526*67e74705SXin Li /// This routine takes care of the mapping from an integral template
5527*67e74705SXin Li /// argument (which may have any integral type) to the appropriate
5528*67e74705SXin Li /// literal value.
5529*67e74705SXin Li ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument & Arg,SourceLocation Loc)5530*67e74705SXin Li Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5531*67e74705SXin Li                                                   SourceLocation Loc) {
5532*67e74705SXin Li   assert(Arg.getKind() == TemplateArgument::Integral &&
5533*67e74705SXin Li          "Operation is only valid for integral template arguments");
5534*67e74705SXin Li   QualType OrigT = Arg.getIntegralType();
5535*67e74705SXin Li 
5536*67e74705SXin Li   // If this is an enum type that we're instantiating, we need to use an integer
5537*67e74705SXin Li   // type the same size as the enumerator.  We don't want to build an
5538*67e74705SXin Li   // IntegerLiteral with enum type.  The integer type of an enum type can be of
5539*67e74705SXin Li   // any integral type with C++11 enum classes, make sure we create the right
5540*67e74705SXin Li   // type of literal for it.
5541*67e74705SXin Li   QualType T = OrigT;
5542*67e74705SXin Li   if (const EnumType *ET = OrigT->getAs<EnumType>())
5543*67e74705SXin Li     T = ET->getDecl()->getIntegerType();
5544*67e74705SXin Li 
5545*67e74705SXin Li   Expr *E;
5546*67e74705SXin Li   if (T->isAnyCharacterType()) {
5547*67e74705SXin Li     // This does not need to handle u8 character literals because those are
5548*67e74705SXin Li     // of type char, and so can also be covered by an ASCII character literal.
5549*67e74705SXin Li     CharacterLiteral::CharacterKind Kind;
5550*67e74705SXin Li     if (T->isWideCharType())
5551*67e74705SXin Li       Kind = CharacterLiteral::Wide;
5552*67e74705SXin Li     else if (T->isChar16Type())
5553*67e74705SXin Li       Kind = CharacterLiteral::UTF16;
5554*67e74705SXin Li     else if (T->isChar32Type())
5555*67e74705SXin Li       Kind = CharacterLiteral::UTF32;
5556*67e74705SXin Li     else
5557*67e74705SXin Li       Kind = CharacterLiteral::Ascii;
5558*67e74705SXin Li 
5559*67e74705SXin Li     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5560*67e74705SXin Li                                        Kind, T, Loc);
5561*67e74705SXin Li   } else if (T->isBooleanType()) {
5562*67e74705SXin Li     E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5563*67e74705SXin Li                                          T, Loc);
5564*67e74705SXin Li   } else if (T->isNullPtrType()) {
5565*67e74705SXin Li     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5566*67e74705SXin Li   } else {
5567*67e74705SXin Li     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5568*67e74705SXin Li   }
5569*67e74705SXin Li 
5570*67e74705SXin Li   if (OrigT->isEnumeralType()) {
5571*67e74705SXin Li     // FIXME: This is a hack. We need a better way to handle substituted
5572*67e74705SXin Li     // non-type template parameters.
5573*67e74705SXin Li     E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5574*67e74705SXin Li                                nullptr,
5575*67e74705SXin Li                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
5576*67e74705SXin Li                                Loc, Loc);
5577*67e74705SXin Li   }
5578*67e74705SXin Li 
5579*67e74705SXin Li   return E;
5580*67e74705SXin Li }
5581*67e74705SXin Li 
5582*67e74705SXin Li /// \brief Match two template parameters within template parameter lists.
MatchTemplateParameterKind(Sema & S,NamedDecl * New,NamedDecl * Old,bool Complain,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)5583*67e74705SXin Li static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5584*67e74705SXin Li                                        bool Complain,
5585*67e74705SXin Li                                      Sema::TemplateParameterListEqualKind Kind,
5586*67e74705SXin Li                                        SourceLocation TemplateArgLoc) {
5587*67e74705SXin Li   // Check the actual kind (type, non-type, template).
5588*67e74705SXin Li   if (Old->getKind() != New->getKind()) {
5589*67e74705SXin Li     if (Complain) {
5590*67e74705SXin Li       unsigned NextDiag = diag::err_template_param_different_kind;
5591*67e74705SXin Li       if (TemplateArgLoc.isValid()) {
5592*67e74705SXin Li         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5593*67e74705SXin Li         NextDiag = diag::note_template_param_different_kind;
5594*67e74705SXin Li       }
5595*67e74705SXin Li       S.Diag(New->getLocation(), NextDiag)
5596*67e74705SXin Li         << (Kind != Sema::TPL_TemplateMatch);
5597*67e74705SXin Li       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5598*67e74705SXin Li         << (Kind != Sema::TPL_TemplateMatch);
5599*67e74705SXin Li     }
5600*67e74705SXin Li 
5601*67e74705SXin Li     return false;
5602*67e74705SXin Li   }
5603*67e74705SXin Li 
5604*67e74705SXin Li   // Check that both are parameter packs are neither are parameter packs.
5605*67e74705SXin Li   // However, if we are matching a template template argument to a
5606*67e74705SXin Li   // template template parameter, the template template parameter can have
5607*67e74705SXin Li   // a parameter pack where the template template argument does not.
5608*67e74705SXin Li   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5609*67e74705SXin Li       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5610*67e74705SXin Li         Old->isTemplateParameterPack())) {
5611*67e74705SXin Li     if (Complain) {
5612*67e74705SXin Li       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5613*67e74705SXin Li       if (TemplateArgLoc.isValid()) {
5614*67e74705SXin Li         S.Diag(TemplateArgLoc,
5615*67e74705SXin Li              diag::err_template_arg_template_params_mismatch);
5616*67e74705SXin Li         NextDiag = diag::note_template_parameter_pack_non_pack;
5617*67e74705SXin Li       }
5618*67e74705SXin Li 
5619*67e74705SXin Li       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5620*67e74705SXin Li                       : isa<NonTypeTemplateParmDecl>(New)? 1
5621*67e74705SXin Li                       : 2;
5622*67e74705SXin Li       S.Diag(New->getLocation(), NextDiag)
5623*67e74705SXin Li         << ParamKind << New->isParameterPack();
5624*67e74705SXin Li       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5625*67e74705SXin Li         << ParamKind << Old->isParameterPack();
5626*67e74705SXin Li     }
5627*67e74705SXin Li 
5628*67e74705SXin Li     return false;
5629*67e74705SXin Li   }
5630*67e74705SXin Li 
5631*67e74705SXin Li   // For non-type template parameters, check the type of the parameter.
5632*67e74705SXin Li   if (NonTypeTemplateParmDecl *OldNTTP
5633*67e74705SXin Li                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5634*67e74705SXin Li     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5635*67e74705SXin Li 
5636*67e74705SXin Li     // If we are matching a template template argument to a template
5637*67e74705SXin Li     // template parameter and one of the non-type template parameter types
5638*67e74705SXin Li     // is dependent, then we must wait until template instantiation time
5639*67e74705SXin Li     // to actually compare the arguments.
5640*67e74705SXin Li     if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5641*67e74705SXin Li         (OldNTTP->getType()->isDependentType() ||
5642*67e74705SXin Li          NewNTTP->getType()->isDependentType()))
5643*67e74705SXin Li       return true;
5644*67e74705SXin Li 
5645*67e74705SXin Li     if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5646*67e74705SXin Li       if (Complain) {
5647*67e74705SXin Li         unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5648*67e74705SXin Li         if (TemplateArgLoc.isValid()) {
5649*67e74705SXin Li           S.Diag(TemplateArgLoc,
5650*67e74705SXin Li                  diag::err_template_arg_template_params_mismatch);
5651*67e74705SXin Li           NextDiag = diag::note_template_nontype_parm_different_type;
5652*67e74705SXin Li         }
5653*67e74705SXin Li         S.Diag(NewNTTP->getLocation(), NextDiag)
5654*67e74705SXin Li           << NewNTTP->getType()
5655*67e74705SXin Li           << (Kind != Sema::TPL_TemplateMatch);
5656*67e74705SXin Li         S.Diag(OldNTTP->getLocation(),
5657*67e74705SXin Li                diag::note_template_nontype_parm_prev_declaration)
5658*67e74705SXin Li           << OldNTTP->getType();
5659*67e74705SXin Li       }
5660*67e74705SXin Li 
5661*67e74705SXin Li       return false;
5662*67e74705SXin Li     }
5663*67e74705SXin Li 
5664*67e74705SXin Li     return true;
5665*67e74705SXin Li   }
5666*67e74705SXin Li 
5667*67e74705SXin Li   // For template template parameters, check the template parameter types.
5668*67e74705SXin Li   // The template parameter lists of template template
5669*67e74705SXin Li   // parameters must agree.
5670*67e74705SXin Li   if (TemplateTemplateParmDecl *OldTTP
5671*67e74705SXin Li                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5672*67e74705SXin Li     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5673*67e74705SXin Li     return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5674*67e74705SXin Li                                             OldTTP->getTemplateParameters(),
5675*67e74705SXin Li                                             Complain,
5676*67e74705SXin Li                                         (Kind == Sema::TPL_TemplateMatch
5677*67e74705SXin Li                                            ? Sema::TPL_TemplateTemplateParmMatch
5678*67e74705SXin Li                                            : Kind),
5679*67e74705SXin Li                                             TemplateArgLoc);
5680*67e74705SXin Li   }
5681*67e74705SXin Li 
5682*67e74705SXin Li   return true;
5683*67e74705SXin Li }
5684*67e74705SXin Li 
5685*67e74705SXin Li /// \brief Diagnose a known arity mismatch when comparing template argument
5686*67e74705SXin Li /// lists.
5687*67e74705SXin Li static
DiagnoseTemplateParameterListArityMismatch(Sema & S,TemplateParameterList * New,TemplateParameterList * Old,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)5688*67e74705SXin Li void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5689*67e74705SXin Li                                                 TemplateParameterList *New,
5690*67e74705SXin Li                                                 TemplateParameterList *Old,
5691*67e74705SXin Li                                       Sema::TemplateParameterListEqualKind Kind,
5692*67e74705SXin Li                                                 SourceLocation TemplateArgLoc) {
5693*67e74705SXin Li   unsigned NextDiag = diag::err_template_param_list_different_arity;
5694*67e74705SXin Li   if (TemplateArgLoc.isValid()) {
5695*67e74705SXin Li     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5696*67e74705SXin Li     NextDiag = diag::note_template_param_list_different_arity;
5697*67e74705SXin Li   }
5698*67e74705SXin Li   S.Diag(New->getTemplateLoc(), NextDiag)
5699*67e74705SXin Li     << (New->size() > Old->size())
5700*67e74705SXin Li     << (Kind != Sema::TPL_TemplateMatch)
5701*67e74705SXin Li     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5702*67e74705SXin Li   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5703*67e74705SXin Li     << (Kind != Sema::TPL_TemplateMatch)
5704*67e74705SXin Li     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5705*67e74705SXin Li }
5706*67e74705SXin Li 
5707*67e74705SXin Li /// \brief Determine whether the given template parameter lists are
5708*67e74705SXin Li /// equivalent.
5709*67e74705SXin Li ///
5710*67e74705SXin Li /// \param New  The new template parameter list, typically written in the
5711*67e74705SXin Li /// source code as part of a new template declaration.
5712*67e74705SXin Li ///
5713*67e74705SXin Li /// \param Old  The old template parameter list, typically found via
5714*67e74705SXin Li /// name lookup of the template declared with this template parameter
5715*67e74705SXin Li /// list.
5716*67e74705SXin Li ///
5717*67e74705SXin Li /// \param Complain  If true, this routine will produce a diagnostic if
5718*67e74705SXin Li /// the template parameter lists are not equivalent.
5719*67e74705SXin Li ///
5720*67e74705SXin Li /// \param Kind describes how we are to match the template parameter lists.
5721*67e74705SXin Li ///
5722*67e74705SXin Li /// \param TemplateArgLoc If this source location is valid, then we
5723*67e74705SXin Li /// are actually checking the template parameter list of a template
5724*67e74705SXin Li /// argument (New) against the template parameter list of its
5725*67e74705SXin Li /// corresponding template template parameter (Old). We produce
5726*67e74705SXin Li /// slightly different diagnostics in this scenario.
5727*67e74705SXin Li ///
5728*67e74705SXin Li /// \returns True if the template parameter lists are equal, false
5729*67e74705SXin Li /// otherwise.
5730*67e74705SXin Li bool
TemplateParameterListsAreEqual(TemplateParameterList * New,TemplateParameterList * Old,bool Complain,TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)5731*67e74705SXin Li Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5732*67e74705SXin Li                                      TemplateParameterList *Old,
5733*67e74705SXin Li                                      bool Complain,
5734*67e74705SXin Li                                      TemplateParameterListEqualKind Kind,
5735*67e74705SXin Li                                      SourceLocation TemplateArgLoc) {
5736*67e74705SXin Li   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5737*67e74705SXin Li     if (Complain)
5738*67e74705SXin Li       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5739*67e74705SXin Li                                                  TemplateArgLoc);
5740*67e74705SXin Li 
5741*67e74705SXin Li     return false;
5742*67e74705SXin Li   }
5743*67e74705SXin Li 
5744*67e74705SXin Li   // C++0x [temp.arg.template]p3:
5745*67e74705SXin Li   //   A template-argument matches a template template-parameter (call it P)
5746*67e74705SXin Li   //   when each of the template parameters in the template-parameter-list of
5747*67e74705SXin Li   //   the template-argument's corresponding class template or alias template
5748*67e74705SXin Li   //   (call it A) matches the corresponding template parameter in the
5749*67e74705SXin Li   //   template-parameter-list of P. [...]
5750*67e74705SXin Li   TemplateParameterList::iterator NewParm = New->begin();
5751*67e74705SXin Li   TemplateParameterList::iterator NewParmEnd = New->end();
5752*67e74705SXin Li   for (TemplateParameterList::iterator OldParm = Old->begin(),
5753*67e74705SXin Li                                     OldParmEnd = Old->end();
5754*67e74705SXin Li        OldParm != OldParmEnd; ++OldParm) {
5755*67e74705SXin Li     if (Kind != TPL_TemplateTemplateArgumentMatch ||
5756*67e74705SXin Li         !(*OldParm)->isTemplateParameterPack()) {
5757*67e74705SXin Li       if (NewParm == NewParmEnd) {
5758*67e74705SXin Li         if (Complain)
5759*67e74705SXin Li           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5760*67e74705SXin Li                                                      TemplateArgLoc);
5761*67e74705SXin Li 
5762*67e74705SXin Li         return false;
5763*67e74705SXin Li       }
5764*67e74705SXin Li 
5765*67e74705SXin Li       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5766*67e74705SXin Li                                       Kind, TemplateArgLoc))
5767*67e74705SXin Li         return false;
5768*67e74705SXin Li 
5769*67e74705SXin Li       ++NewParm;
5770*67e74705SXin Li       continue;
5771*67e74705SXin Li     }
5772*67e74705SXin Li 
5773*67e74705SXin Li     // C++0x [temp.arg.template]p3:
5774*67e74705SXin Li     //   [...] When P's template- parameter-list contains a template parameter
5775*67e74705SXin Li     //   pack (14.5.3), the template parameter pack will match zero or more
5776*67e74705SXin Li     //   template parameters or template parameter packs in the
5777*67e74705SXin Li     //   template-parameter-list of A with the same type and form as the
5778*67e74705SXin Li     //   template parameter pack in P (ignoring whether those template
5779*67e74705SXin Li     //   parameters are template parameter packs).
5780*67e74705SXin Li     for (; NewParm != NewParmEnd; ++NewParm) {
5781*67e74705SXin Li       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5782*67e74705SXin Li                                       Kind, TemplateArgLoc))
5783*67e74705SXin Li         return false;
5784*67e74705SXin Li     }
5785*67e74705SXin Li   }
5786*67e74705SXin Li 
5787*67e74705SXin Li   // Make sure we exhausted all of the arguments.
5788*67e74705SXin Li   if (NewParm != NewParmEnd) {
5789*67e74705SXin Li     if (Complain)
5790*67e74705SXin Li       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5791*67e74705SXin Li                                                  TemplateArgLoc);
5792*67e74705SXin Li 
5793*67e74705SXin Li     return false;
5794*67e74705SXin Li   }
5795*67e74705SXin Li 
5796*67e74705SXin Li   return true;
5797*67e74705SXin Li }
5798*67e74705SXin Li 
5799*67e74705SXin Li /// \brief Check whether a template can be declared within this scope.
5800*67e74705SXin Li ///
5801*67e74705SXin Li /// If the template declaration is valid in this scope, returns
5802*67e74705SXin Li /// false. Otherwise, issues a diagnostic and returns true.
5803*67e74705SXin Li bool
CheckTemplateDeclScope(Scope * S,TemplateParameterList * TemplateParams)5804*67e74705SXin Li Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5805*67e74705SXin Li   if (!S)
5806*67e74705SXin Li     return false;
5807*67e74705SXin Li 
5808*67e74705SXin Li   // Find the nearest enclosing declaration scope.
5809*67e74705SXin Li   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5810*67e74705SXin Li          (S->getFlags() & Scope::TemplateParamScope) != 0)
5811*67e74705SXin Li     S = S->getParent();
5812*67e74705SXin Li 
5813*67e74705SXin Li   // C++ [temp]p4:
5814*67e74705SXin Li   //   A template [...] shall not have C linkage.
5815*67e74705SXin Li   DeclContext *Ctx = S->getEntity();
5816*67e74705SXin Li   if (Ctx && Ctx->isExternCContext())
5817*67e74705SXin Li     return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5818*67e74705SXin Li              << TemplateParams->getSourceRange();
5819*67e74705SXin Li 
5820*67e74705SXin Li   while (Ctx && isa<LinkageSpecDecl>(Ctx))
5821*67e74705SXin Li     Ctx = Ctx->getParent();
5822*67e74705SXin Li 
5823*67e74705SXin Li   // C++ [temp]p2:
5824*67e74705SXin Li   //   A template-declaration can appear only as a namespace scope or
5825*67e74705SXin Li   //   class scope declaration.
5826*67e74705SXin Li   if (Ctx) {
5827*67e74705SXin Li     if (Ctx->isFileContext())
5828*67e74705SXin Li       return false;
5829*67e74705SXin Li     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5830*67e74705SXin Li       // C++ [temp.mem]p2:
5831*67e74705SXin Li       //   A local class shall not have member templates.
5832*67e74705SXin Li       if (RD->isLocalClass())
5833*67e74705SXin Li         return Diag(TemplateParams->getTemplateLoc(),
5834*67e74705SXin Li                     diag::err_template_inside_local_class)
5835*67e74705SXin Li           << TemplateParams->getSourceRange();
5836*67e74705SXin Li       else
5837*67e74705SXin Li         return false;
5838*67e74705SXin Li     }
5839*67e74705SXin Li   }
5840*67e74705SXin Li 
5841*67e74705SXin Li   return Diag(TemplateParams->getTemplateLoc(),
5842*67e74705SXin Li               diag::err_template_outside_namespace_or_class_scope)
5843*67e74705SXin Li     << TemplateParams->getSourceRange();
5844*67e74705SXin Li }
5845*67e74705SXin Li 
5846*67e74705SXin Li /// \brief Determine what kind of template specialization the given declaration
5847*67e74705SXin Li /// is.
getTemplateSpecializationKind(Decl * D)5848*67e74705SXin Li static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5849*67e74705SXin Li   if (!D)
5850*67e74705SXin Li     return TSK_Undeclared;
5851*67e74705SXin Li 
5852*67e74705SXin Li   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5853*67e74705SXin Li     return Record->getTemplateSpecializationKind();
5854*67e74705SXin Li   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5855*67e74705SXin Li     return Function->getTemplateSpecializationKind();
5856*67e74705SXin Li   if (VarDecl *Var = dyn_cast<VarDecl>(D))
5857*67e74705SXin Li     return Var->getTemplateSpecializationKind();
5858*67e74705SXin Li 
5859*67e74705SXin Li   return TSK_Undeclared;
5860*67e74705SXin Li }
5861*67e74705SXin Li 
5862*67e74705SXin Li /// \brief Check whether a specialization is well-formed in the current
5863*67e74705SXin Li /// context.
5864*67e74705SXin Li ///
5865*67e74705SXin Li /// This routine determines whether a template specialization can be declared
5866*67e74705SXin Li /// in the current context (C++ [temp.expl.spec]p2).
5867*67e74705SXin Li ///
5868*67e74705SXin Li /// \param S the semantic analysis object for which this check is being
5869*67e74705SXin Li /// performed.
5870*67e74705SXin Li ///
5871*67e74705SXin Li /// \param Specialized the entity being specialized or instantiated, which
5872*67e74705SXin Li /// may be a kind of template (class template, function template, etc.) or
5873*67e74705SXin Li /// a member of a class template (member function, static data member,
5874*67e74705SXin Li /// member class).
5875*67e74705SXin Li ///
5876*67e74705SXin Li /// \param PrevDecl the previous declaration of this entity, if any.
5877*67e74705SXin Li ///
5878*67e74705SXin Li /// \param Loc the location of the explicit specialization or instantiation of
5879*67e74705SXin Li /// this entity.
5880*67e74705SXin Li ///
5881*67e74705SXin Li /// \param IsPartialSpecialization whether this is a partial specialization of
5882*67e74705SXin Li /// a class template.
5883*67e74705SXin Li ///
5884*67e74705SXin Li /// \returns true if there was an error that we cannot recover from, false
5885*67e74705SXin Li /// otherwise.
CheckTemplateSpecializationScope(Sema & S,NamedDecl * Specialized,NamedDecl * PrevDecl,SourceLocation Loc,bool IsPartialSpecialization)5886*67e74705SXin Li static bool CheckTemplateSpecializationScope(Sema &S,
5887*67e74705SXin Li                                              NamedDecl *Specialized,
5888*67e74705SXin Li                                              NamedDecl *PrevDecl,
5889*67e74705SXin Li                                              SourceLocation Loc,
5890*67e74705SXin Li                                              bool IsPartialSpecialization) {
5891*67e74705SXin Li   // Keep these "kind" numbers in sync with the %select statements in the
5892*67e74705SXin Li   // various diagnostics emitted by this routine.
5893*67e74705SXin Li   int EntityKind = 0;
5894*67e74705SXin Li   if (isa<ClassTemplateDecl>(Specialized))
5895*67e74705SXin Li     EntityKind = IsPartialSpecialization? 1 : 0;
5896*67e74705SXin Li   else if (isa<VarTemplateDecl>(Specialized))
5897*67e74705SXin Li     EntityKind = IsPartialSpecialization ? 3 : 2;
5898*67e74705SXin Li   else if (isa<FunctionTemplateDecl>(Specialized))
5899*67e74705SXin Li     EntityKind = 4;
5900*67e74705SXin Li   else if (isa<CXXMethodDecl>(Specialized))
5901*67e74705SXin Li     EntityKind = 5;
5902*67e74705SXin Li   else if (isa<VarDecl>(Specialized))
5903*67e74705SXin Li     EntityKind = 6;
5904*67e74705SXin Li   else if (isa<RecordDecl>(Specialized))
5905*67e74705SXin Li     EntityKind = 7;
5906*67e74705SXin Li   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5907*67e74705SXin Li     EntityKind = 8;
5908*67e74705SXin Li   else {
5909*67e74705SXin Li     S.Diag(Loc, diag::err_template_spec_unknown_kind)
5910*67e74705SXin Li       << S.getLangOpts().CPlusPlus11;
5911*67e74705SXin Li     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5912*67e74705SXin Li     return true;
5913*67e74705SXin Li   }
5914*67e74705SXin Li 
5915*67e74705SXin Li   // C++ [temp.expl.spec]p2:
5916*67e74705SXin Li   //   An explicit specialization shall be declared in the namespace
5917*67e74705SXin Li   //   of which the template is a member, or, for member templates, in
5918*67e74705SXin Li   //   the namespace of which the enclosing class or enclosing class
5919*67e74705SXin Li   //   template is a member. An explicit specialization of a member
5920*67e74705SXin Li   //   function, member class or static data member of a class
5921*67e74705SXin Li   //   template shall be declared in the namespace of which the class
5922*67e74705SXin Li   //   template is a member. Such a declaration may also be a
5923*67e74705SXin Li   //   definition. If the declaration is not a definition, the
5924*67e74705SXin Li   //   specialization may be defined later in the name- space in which
5925*67e74705SXin Li   //   the explicit specialization was declared, or in a namespace
5926*67e74705SXin Li   //   that encloses the one in which the explicit specialization was
5927*67e74705SXin Li   //   declared.
5928*67e74705SXin Li   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5929*67e74705SXin Li     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5930*67e74705SXin Li       << Specialized;
5931*67e74705SXin Li     return true;
5932*67e74705SXin Li   }
5933*67e74705SXin Li 
5934*67e74705SXin Li   if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5935*67e74705SXin Li     if (S.getLangOpts().MicrosoftExt) {
5936*67e74705SXin Li       // Do not warn for class scope explicit specialization during
5937*67e74705SXin Li       // instantiation, warning was already emitted during pattern
5938*67e74705SXin Li       // semantic analysis.
5939*67e74705SXin Li       if (!S.ActiveTemplateInstantiations.size())
5940*67e74705SXin Li         S.Diag(Loc, diag::ext_function_specialization_in_class)
5941*67e74705SXin Li           << Specialized;
5942*67e74705SXin Li     } else {
5943*67e74705SXin Li       S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5944*67e74705SXin Li         << Specialized;
5945*67e74705SXin Li       return true;
5946*67e74705SXin Li     }
5947*67e74705SXin Li   }
5948*67e74705SXin Li 
5949*67e74705SXin Li   if (S.CurContext->isRecord() &&
5950*67e74705SXin Li       !S.CurContext->Equals(Specialized->getDeclContext())) {
5951*67e74705SXin Li     // Make sure that we're specializing in the right record context.
5952*67e74705SXin Li     // Otherwise, things can go horribly wrong.
5953*67e74705SXin Li     S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5954*67e74705SXin Li       << Specialized;
5955*67e74705SXin Li     return true;
5956*67e74705SXin Li   }
5957*67e74705SXin Li 
5958*67e74705SXin Li   // C++ [temp.class.spec]p6:
5959*67e74705SXin Li   //   A class template partial specialization may be declared or redeclared
5960*67e74705SXin Li   //   in any namespace scope in which its definition may be defined (14.5.1
5961*67e74705SXin Li   //   and 14.5.2).
5962*67e74705SXin Li   DeclContext *SpecializedContext
5963*67e74705SXin Li     = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5964*67e74705SXin Li   DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5965*67e74705SXin Li 
5966*67e74705SXin Li   // Make sure that this redeclaration (or definition) occurs in an enclosing
5967*67e74705SXin Li   // namespace.
5968*67e74705SXin Li   // Note that HandleDeclarator() performs this check for explicit
5969*67e74705SXin Li   // specializations of function templates, static data members, and member
5970*67e74705SXin Li   // functions, so we skip the check here for those kinds of entities.
5971*67e74705SXin Li   // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5972*67e74705SXin Li   // Should we refactor that check, so that it occurs later?
5973*67e74705SXin Li   if (!DC->Encloses(SpecializedContext) &&
5974*67e74705SXin Li       !(isa<FunctionTemplateDecl>(Specialized) ||
5975*67e74705SXin Li         isa<FunctionDecl>(Specialized) ||
5976*67e74705SXin Li         isa<VarTemplateDecl>(Specialized) ||
5977*67e74705SXin Li         isa<VarDecl>(Specialized))) {
5978*67e74705SXin Li     if (isa<TranslationUnitDecl>(SpecializedContext))
5979*67e74705SXin Li       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5980*67e74705SXin Li         << EntityKind << Specialized;
5981*67e74705SXin Li     else if (isa<NamespaceDecl>(SpecializedContext)) {
5982*67e74705SXin Li       int Diag = diag::err_template_spec_redecl_out_of_scope;
5983*67e74705SXin Li       if (S.getLangOpts().MicrosoftExt)
5984*67e74705SXin Li         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5985*67e74705SXin Li       S.Diag(Loc, Diag) << EntityKind << Specialized
5986*67e74705SXin Li                         << cast<NamedDecl>(SpecializedContext);
5987*67e74705SXin Li     } else
5988*67e74705SXin Li       llvm_unreachable("unexpected namespace context for specialization");
5989*67e74705SXin Li 
5990*67e74705SXin Li     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5991*67e74705SXin Li   } else if ((!PrevDecl ||
5992*67e74705SXin Li               getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5993*67e74705SXin Li               getTemplateSpecializationKind(PrevDecl) ==
5994*67e74705SXin Li                   TSK_ImplicitInstantiation)) {
5995*67e74705SXin Li     // C++ [temp.exp.spec]p2:
5996*67e74705SXin Li     //   An explicit specialization shall be declared in the namespace of which
5997*67e74705SXin Li     //   the template is a member, or, for member templates, in the namespace
5998*67e74705SXin Li     //   of which the enclosing class or enclosing class template is a member.
5999*67e74705SXin Li     //   An explicit specialization of a member function, member class or
6000*67e74705SXin Li     //   static data member of a class template shall be declared in the
6001*67e74705SXin Li     //   namespace of which the class template is a member.
6002*67e74705SXin Li     //
6003*67e74705SXin Li     // C++11 [temp.expl.spec]p2:
6004*67e74705SXin Li     //   An explicit specialization shall be declared in a namespace enclosing
6005*67e74705SXin Li     //   the specialized template.
6006*67e74705SXin Li     // C++11 [temp.explicit]p3:
6007*67e74705SXin Li     //   An explicit instantiation shall appear in an enclosing namespace of its
6008*67e74705SXin Li     //   template.
6009*67e74705SXin Li     if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
6010*67e74705SXin Li       bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
6011*67e74705SXin Li       if (isa<TranslationUnitDecl>(SpecializedContext)) {
6012*67e74705SXin Li         assert(!IsCPlusPlus11Extension &&
6013*67e74705SXin Li                "DC encloses TU but isn't in enclosing namespace set");
6014*67e74705SXin Li         S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
6015*67e74705SXin Li           << EntityKind << Specialized;
6016*67e74705SXin Li       } else if (isa<NamespaceDecl>(SpecializedContext)) {
6017*67e74705SXin Li         int Diag;
6018*67e74705SXin Li         if (!IsCPlusPlus11Extension)
6019*67e74705SXin Li           Diag = diag::err_template_spec_decl_out_of_scope;
6020*67e74705SXin Li         else if (!S.getLangOpts().CPlusPlus11)
6021*67e74705SXin Li           Diag = diag::ext_template_spec_decl_out_of_scope;
6022*67e74705SXin Li         else
6023*67e74705SXin Li           Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6024*67e74705SXin Li         S.Diag(Loc, Diag)
6025*67e74705SXin Li           << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6026*67e74705SXin Li       }
6027*67e74705SXin Li 
6028*67e74705SXin Li       S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6029*67e74705SXin Li     }
6030*67e74705SXin Li   }
6031*67e74705SXin Li 
6032*67e74705SXin Li   return false;
6033*67e74705SXin Li }
6034*67e74705SXin Li 
findTemplateParameter(unsigned Depth,Expr * E)6035*67e74705SXin Li static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6036*67e74705SXin Li   if (!E->isInstantiationDependent())
6037*67e74705SXin Li     return SourceLocation();
6038*67e74705SXin Li   DependencyChecker Checker(Depth);
6039*67e74705SXin Li   Checker.TraverseStmt(E);
6040*67e74705SXin Li   if (Checker.Match && Checker.MatchLoc.isInvalid())
6041*67e74705SXin Li     return E->getSourceRange();
6042*67e74705SXin Li   return Checker.MatchLoc;
6043*67e74705SXin Li }
6044*67e74705SXin Li 
findTemplateParameter(unsigned Depth,TypeLoc TL)6045*67e74705SXin Li static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6046*67e74705SXin Li   if (!TL.getType()->isDependentType())
6047*67e74705SXin Li     return SourceLocation();
6048*67e74705SXin Li   DependencyChecker Checker(Depth);
6049*67e74705SXin Li   Checker.TraverseTypeLoc(TL);
6050*67e74705SXin Li   if (Checker.Match && Checker.MatchLoc.isInvalid())
6051*67e74705SXin Li     return TL.getSourceRange();
6052*67e74705SXin Li   return Checker.MatchLoc;
6053*67e74705SXin Li }
6054*67e74705SXin Li 
6055*67e74705SXin Li /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
6056*67e74705SXin Li /// that checks non-type template partial specialization arguments.
CheckNonTypeTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,NonTypeTemplateParmDecl * Param,const TemplateArgument * Args,unsigned NumArgs,bool IsDefaultArgument)6057*67e74705SXin Li static bool CheckNonTypeTemplatePartialSpecializationArgs(
6058*67e74705SXin Li     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6059*67e74705SXin Li     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
6060*67e74705SXin Li   for (unsigned I = 0; I != NumArgs; ++I) {
6061*67e74705SXin Li     if (Args[I].getKind() == TemplateArgument::Pack) {
6062*67e74705SXin Li       if (CheckNonTypeTemplatePartialSpecializationArgs(
6063*67e74705SXin Li               S, TemplateNameLoc, Param, Args[I].pack_begin(),
6064*67e74705SXin Li               Args[I].pack_size(), IsDefaultArgument))
6065*67e74705SXin Li         return true;
6066*67e74705SXin Li 
6067*67e74705SXin Li       continue;
6068*67e74705SXin Li     }
6069*67e74705SXin Li 
6070*67e74705SXin Li     if (Args[I].getKind() != TemplateArgument::Expression)
6071*67e74705SXin Li       continue;
6072*67e74705SXin Li 
6073*67e74705SXin Li     Expr *ArgExpr = Args[I].getAsExpr();
6074*67e74705SXin Li 
6075*67e74705SXin Li     // We can have a pack expansion of any of the bullets below.
6076*67e74705SXin Li     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6077*67e74705SXin Li       ArgExpr = Expansion->getPattern();
6078*67e74705SXin Li 
6079*67e74705SXin Li     // Strip off any implicit casts we added as part of type checking.
6080*67e74705SXin Li     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6081*67e74705SXin Li       ArgExpr = ICE->getSubExpr();
6082*67e74705SXin Li 
6083*67e74705SXin Li     // C++ [temp.class.spec]p8:
6084*67e74705SXin Li     //   A non-type argument is non-specialized if it is the name of a
6085*67e74705SXin Li     //   non-type parameter. All other non-type arguments are
6086*67e74705SXin Li     //   specialized.
6087*67e74705SXin Li     //
6088*67e74705SXin Li     // Below, we check the two conditions that only apply to
6089*67e74705SXin Li     // specialized non-type arguments, so skip any non-specialized
6090*67e74705SXin Li     // arguments.
6091*67e74705SXin Li     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
6092*67e74705SXin Li       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
6093*67e74705SXin Li         continue;
6094*67e74705SXin Li 
6095*67e74705SXin Li     // C++ [temp.class.spec]p9:
6096*67e74705SXin Li     //   Within the argument list of a class template partial
6097*67e74705SXin Li     //   specialization, the following restrictions apply:
6098*67e74705SXin Li     //     -- A partially specialized non-type argument expression
6099*67e74705SXin Li     //        shall not involve a template parameter of the partial
6100*67e74705SXin Li     //        specialization except when the argument expression is a
6101*67e74705SXin Li     //        simple identifier.
6102*67e74705SXin Li     SourceRange ParamUseRange =
6103*67e74705SXin Li         findTemplateParameter(Param->getDepth(), ArgExpr);
6104*67e74705SXin Li     if (ParamUseRange.isValid()) {
6105*67e74705SXin Li       if (IsDefaultArgument) {
6106*67e74705SXin Li         S.Diag(TemplateNameLoc,
6107*67e74705SXin Li                diag::err_dependent_non_type_arg_in_partial_spec);
6108*67e74705SXin Li         S.Diag(ParamUseRange.getBegin(),
6109*67e74705SXin Li                diag::note_dependent_non_type_default_arg_in_partial_spec)
6110*67e74705SXin Li           << ParamUseRange;
6111*67e74705SXin Li       } else {
6112*67e74705SXin Li         S.Diag(ParamUseRange.getBegin(),
6113*67e74705SXin Li                diag::err_dependent_non_type_arg_in_partial_spec)
6114*67e74705SXin Li           << ParamUseRange;
6115*67e74705SXin Li       }
6116*67e74705SXin Li       return true;
6117*67e74705SXin Li     }
6118*67e74705SXin Li 
6119*67e74705SXin Li     //     -- The type of a template parameter corresponding to a
6120*67e74705SXin Li     //        specialized non-type argument shall not be dependent on a
6121*67e74705SXin Li     //        parameter of the specialization.
6122*67e74705SXin Li     //
6123*67e74705SXin Li     // FIXME: We need to delay this check until instantiation in some cases:
6124*67e74705SXin Li     //
6125*67e74705SXin Li     //   template<template<typename> class X> struct A {
6126*67e74705SXin Li     //     template<typename T, X<T> N> struct B;
6127*67e74705SXin Li     //     template<typename T> struct B<T, 0>;
6128*67e74705SXin Li     //   };
6129*67e74705SXin Li     //   template<typename> using X = int;
6130*67e74705SXin Li     //   A<X>::B<int, 0> b;
6131*67e74705SXin Li     ParamUseRange = findTemplateParameter(
6132*67e74705SXin Li             Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6133*67e74705SXin Li     if (ParamUseRange.isValid()) {
6134*67e74705SXin Li       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6135*67e74705SXin Li              diag::err_dependent_typed_non_type_arg_in_partial_spec)
6136*67e74705SXin Li         << Param->getType() << ParamUseRange;
6137*67e74705SXin Li       S.Diag(Param->getLocation(), diag::note_template_param_here)
6138*67e74705SXin Li         << (IsDefaultArgument ? ParamUseRange : SourceRange());
6139*67e74705SXin Li       return true;
6140*67e74705SXin Li     }
6141*67e74705SXin Li   }
6142*67e74705SXin Li 
6143*67e74705SXin Li   return false;
6144*67e74705SXin Li }
6145*67e74705SXin Li 
6146*67e74705SXin Li /// \brief Check the non-type template arguments of a class template
6147*67e74705SXin Li /// partial specialization according to C++ [temp.class.spec]p9.
6148*67e74705SXin Li ///
6149*67e74705SXin Li /// \param TemplateNameLoc the location of the template name.
6150*67e74705SXin Li /// \param TemplateParams the template parameters of the primary class
6151*67e74705SXin Li ///        template.
6152*67e74705SXin Li /// \param NumExplicit the number of explicitly-specified template arguments.
6153*67e74705SXin Li /// \param TemplateArgs the template arguments of the class template
6154*67e74705SXin Li ///        partial specialization.
6155*67e74705SXin Li ///
6156*67e74705SXin Li /// \returns \c true if there was an error, \c false otherwise.
CheckTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,TemplateParameterList * TemplateParams,unsigned NumExplicit,SmallVectorImpl<TemplateArgument> & TemplateArgs)6157*67e74705SXin Li static bool CheckTemplatePartialSpecializationArgs(
6158*67e74705SXin Li     Sema &S, SourceLocation TemplateNameLoc,
6159*67e74705SXin Li     TemplateParameterList *TemplateParams, unsigned NumExplicit,
6160*67e74705SXin Li     SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6161*67e74705SXin Li   const TemplateArgument *ArgList = TemplateArgs.data();
6162*67e74705SXin Li 
6163*67e74705SXin Li   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6164*67e74705SXin Li     NonTypeTemplateParmDecl *Param
6165*67e74705SXin Li       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6166*67e74705SXin Li     if (!Param)
6167*67e74705SXin Li       continue;
6168*67e74705SXin Li 
6169*67e74705SXin Li     if (CheckNonTypeTemplatePartialSpecializationArgs(
6170*67e74705SXin Li             S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6171*67e74705SXin Li       return true;
6172*67e74705SXin Li   }
6173*67e74705SXin Li 
6174*67e74705SXin Li   return false;
6175*67e74705SXin Li }
6176*67e74705SXin Li 
6177*67e74705SXin Li DeclResult
ActOnClassTemplateSpecialization(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,SourceLocation ModulePrivateLoc,TemplateIdAnnotation & TemplateId,AttributeList * Attr,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)6178*67e74705SXin Li Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6179*67e74705SXin Li                                        TagUseKind TUK,
6180*67e74705SXin Li                                        SourceLocation KWLoc,
6181*67e74705SXin Li                                        SourceLocation ModulePrivateLoc,
6182*67e74705SXin Li                                        TemplateIdAnnotation &TemplateId,
6183*67e74705SXin Li                                        AttributeList *Attr,
6184*67e74705SXin Li                                        MultiTemplateParamsArg
6185*67e74705SXin Li                                            TemplateParameterLists,
6186*67e74705SXin Li                                        SkipBodyInfo *SkipBody) {
6187*67e74705SXin Li   assert(TUK != TUK_Reference && "References are not specializations");
6188*67e74705SXin Li 
6189*67e74705SXin Li   CXXScopeSpec &SS = TemplateId.SS;
6190*67e74705SXin Li 
6191*67e74705SXin Li   // NOTE: KWLoc is the location of the tag keyword. This will instead
6192*67e74705SXin Li   // store the location of the outermost template keyword in the declaration.
6193*67e74705SXin Li   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6194*67e74705SXin Li     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6195*67e74705SXin Li   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6196*67e74705SXin Li   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6197*67e74705SXin Li   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6198*67e74705SXin Li 
6199*67e74705SXin Li   // Find the class template we're specializing
6200*67e74705SXin Li   TemplateName Name = TemplateId.Template.get();
6201*67e74705SXin Li   ClassTemplateDecl *ClassTemplate
6202*67e74705SXin Li     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6203*67e74705SXin Li 
6204*67e74705SXin Li   if (!ClassTemplate) {
6205*67e74705SXin Li     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6206*67e74705SXin Li       << (Name.getAsTemplateDecl() &&
6207*67e74705SXin Li           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6208*67e74705SXin Li     return true;
6209*67e74705SXin Li   }
6210*67e74705SXin Li 
6211*67e74705SXin Li   bool isExplicitSpecialization = false;
6212*67e74705SXin Li   bool isPartialSpecialization = false;
6213*67e74705SXin Li 
6214*67e74705SXin Li   // Check the validity of the template headers that introduce this
6215*67e74705SXin Li   // template.
6216*67e74705SXin Li   // FIXME: We probably shouldn't complain about these headers for
6217*67e74705SXin Li   // friend declarations.
6218*67e74705SXin Li   bool Invalid = false;
6219*67e74705SXin Li   TemplateParameterList *TemplateParams =
6220*67e74705SXin Li       MatchTemplateParametersToScopeSpecifier(
6221*67e74705SXin Li           KWLoc, TemplateNameLoc, SS, &TemplateId,
6222*67e74705SXin Li           TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6223*67e74705SXin Li           Invalid);
6224*67e74705SXin Li   if (Invalid)
6225*67e74705SXin Li     return true;
6226*67e74705SXin Li 
6227*67e74705SXin Li   if (TemplateParams && TemplateParams->size() > 0) {
6228*67e74705SXin Li     isPartialSpecialization = true;
6229*67e74705SXin Li 
6230*67e74705SXin Li     if (TUK == TUK_Friend) {
6231*67e74705SXin Li       Diag(KWLoc, diag::err_partial_specialization_friend)
6232*67e74705SXin Li         << SourceRange(LAngleLoc, RAngleLoc);
6233*67e74705SXin Li       return true;
6234*67e74705SXin Li     }
6235*67e74705SXin Li 
6236*67e74705SXin Li     // C++ [temp.class.spec]p10:
6237*67e74705SXin Li     //   The template parameter list of a specialization shall not
6238*67e74705SXin Li     //   contain default template argument values.
6239*67e74705SXin Li     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6240*67e74705SXin Li       Decl *Param = TemplateParams->getParam(I);
6241*67e74705SXin Li       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6242*67e74705SXin Li         if (TTP->hasDefaultArgument()) {
6243*67e74705SXin Li           Diag(TTP->getDefaultArgumentLoc(),
6244*67e74705SXin Li                diag::err_default_arg_in_partial_spec);
6245*67e74705SXin Li           TTP->removeDefaultArgument();
6246*67e74705SXin Li         }
6247*67e74705SXin Li       } else if (NonTypeTemplateParmDecl *NTTP
6248*67e74705SXin Li                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6249*67e74705SXin Li         if (Expr *DefArg = NTTP->getDefaultArgument()) {
6250*67e74705SXin Li           Diag(NTTP->getDefaultArgumentLoc(),
6251*67e74705SXin Li                diag::err_default_arg_in_partial_spec)
6252*67e74705SXin Li             << DefArg->getSourceRange();
6253*67e74705SXin Li           NTTP->removeDefaultArgument();
6254*67e74705SXin Li         }
6255*67e74705SXin Li       } else {
6256*67e74705SXin Li         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6257*67e74705SXin Li         if (TTP->hasDefaultArgument()) {
6258*67e74705SXin Li           Diag(TTP->getDefaultArgument().getLocation(),
6259*67e74705SXin Li                diag::err_default_arg_in_partial_spec)
6260*67e74705SXin Li             << TTP->getDefaultArgument().getSourceRange();
6261*67e74705SXin Li           TTP->removeDefaultArgument();
6262*67e74705SXin Li         }
6263*67e74705SXin Li       }
6264*67e74705SXin Li     }
6265*67e74705SXin Li   } else if (TemplateParams) {
6266*67e74705SXin Li     if (TUK == TUK_Friend)
6267*67e74705SXin Li       Diag(KWLoc, diag::err_template_spec_friend)
6268*67e74705SXin Li         << FixItHint::CreateRemoval(
6269*67e74705SXin Li                                 SourceRange(TemplateParams->getTemplateLoc(),
6270*67e74705SXin Li                                             TemplateParams->getRAngleLoc()))
6271*67e74705SXin Li         << SourceRange(LAngleLoc, RAngleLoc);
6272*67e74705SXin Li     else
6273*67e74705SXin Li       isExplicitSpecialization = true;
6274*67e74705SXin Li   } else {
6275*67e74705SXin Li     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6276*67e74705SXin Li   }
6277*67e74705SXin Li 
6278*67e74705SXin Li   // Check that the specialization uses the same tag kind as the
6279*67e74705SXin Li   // original template.
6280*67e74705SXin Li   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6281*67e74705SXin Li   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6282*67e74705SXin Li   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6283*67e74705SXin Li                                     Kind, TUK == TUK_Definition, KWLoc,
6284*67e74705SXin Li                                     ClassTemplate->getIdentifier())) {
6285*67e74705SXin Li     Diag(KWLoc, diag::err_use_with_wrong_tag)
6286*67e74705SXin Li       << ClassTemplate
6287*67e74705SXin Li       << FixItHint::CreateReplacement(KWLoc,
6288*67e74705SXin Li                             ClassTemplate->getTemplatedDecl()->getKindName());
6289*67e74705SXin Li     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6290*67e74705SXin Li          diag::note_previous_use);
6291*67e74705SXin Li     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6292*67e74705SXin Li   }
6293*67e74705SXin Li 
6294*67e74705SXin Li   // Translate the parser's template argument list in our AST format.
6295*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs =
6296*67e74705SXin Li       makeTemplateArgumentListInfo(*this, TemplateId);
6297*67e74705SXin Li 
6298*67e74705SXin Li   // Check for unexpanded parameter packs in any of the template arguments.
6299*67e74705SXin Li   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6300*67e74705SXin Li     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6301*67e74705SXin Li                                         UPPC_PartialSpecialization))
6302*67e74705SXin Li       return true;
6303*67e74705SXin Li 
6304*67e74705SXin Li   // Check that the template argument list is well-formed for this
6305*67e74705SXin Li   // template.
6306*67e74705SXin Li   SmallVector<TemplateArgument, 4> Converted;
6307*67e74705SXin Li   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6308*67e74705SXin Li                                 TemplateArgs, false, Converted))
6309*67e74705SXin Li     return true;
6310*67e74705SXin Li 
6311*67e74705SXin Li   // Find the class template (partial) specialization declaration that
6312*67e74705SXin Li   // corresponds to these arguments.
6313*67e74705SXin Li   if (isPartialSpecialization) {
6314*67e74705SXin Li     if (CheckTemplatePartialSpecializationArgs(
6315*67e74705SXin Li             *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6316*67e74705SXin Li             TemplateArgs.size(), Converted))
6317*67e74705SXin Li       return true;
6318*67e74705SXin Li 
6319*67e74705SXin Li     bool InstantiationDependent;
6320*67e74705SXin Li     if (!Name.isDependent() &&
6321*67e74705SXin Li         !TemplateSpecializationType::anyDependentTemplateArguments(
6322*67e74705SXin Li             TemplateArgs.arguments(), InstantiationDependent)) {
6323*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6324*67e74705SXin Li         << ClassTemplate->getDeclName();
6325*67e74705SXin Li       isPartialSpecialization = false;
6326*67e74705SXin Li     }
6327*67e74705SXin Li   }
6328*67e74705SXin Li 
6329*67e74705SXin Li   void *InsertPos = nullptr;
6330*67e74705SXin Li   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6331*67e74705SXin Li 
6332*67e74705SXin Li   if (isPartialSpecialization)
6333*67e74705SXin Li     // FIXME: Template parameter list matters, too
6334*67e74705SXin Li     PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6335*67e74705SXin Li   else
6336*67e74705SXin Li     PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6337*67e74705SXin Li 
6338*67e74705SXin Li   ClassTemplateSpecializationDecl *Specialization = nullptr;
6339*67e74705SXin Li 
6340*67e74705SXin Li   // Check whether we can declare a class template specialization in
6341*67e74705SXin Li   // the current scope.
6342*67e74705SXin Li   if (TUK != TUK_Friend &&
6343*67e74705SXin Li       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6344*67e74705SXin Li                                        TemplateNameLoc,
6345*67e74705SXin Li                                        isPartialSpecialization))
6346*67e74705SXin Li     return true;
6347*67e74705SXin Li 
6348*67e74705SXin Li   // The canonical type
6349*67e74705SXin Li   QualType CanonType;
6350*67e74705SXin Li   if (isPartialSpecialization) {
6351*67e74705SXin Li     // Build the canonical type that describes the converted template
6352*67e74705SXin Li     // arguments of the class template partial specialization.
6353*67e74705SXin Li     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6354*67e74705SXin Li     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6355*67e74705SXin Li                                                       Converted);
6356*67e74705SXin Li 
6357*67e74705SXin Li     if (Context.hasSameType(CanonType,
6358*67e74705SXin Li                         ClassTemplate->getInjectedClassNameSpecialization())) {
6359*67e74705SXin Li       // C++ [temp.class.spec]p9b3:
6360*67e74705SXin Li       //
6361*67e74705SXin Li       //   -- The argument list of the specialization shall not be identical
6362*67e74705SXin Li       //      to the implicit argument list of the primary template.
6363*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6364*67e74705SXin Li         << /*class template*/0 << (TUK == TUK_Definition)
6365*67e74705SXin Li         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6366*67e74705SXin Li       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6367*67e74705SXin Li                                 ClassTemplate->getIdentifier(),
6368*67e74705SXin Li                                 TemplateNameLoc,
6369*67e74705SXin Li                                 Attr,
6370*67e74705SXin Li                                 TemplateParams,
6371*67e74705SXin Li                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6372*67e74705SXin Li                                 /*FriendLoc*/SourceLocation(),
6373*67e74705SXin Li                                 TemplateParameterLists.size() - 1,
6374*67e74705SXin Li                                 TemplateParameterLists.data());
6375*67e74705SXin Li     }
6376*67e74705SXin Li 
6377*67e74705SXin Li     // Create a new class template partial specialization declaration node.
6378*67e74705SXin Li     ClassTemplatePartialSpecializationDecl *PrevPartial
6379*67e74705SXin Li       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6380*67e74705SXin Li     ClassTemplatePartialSpecializationDecl *Partial
6381*67e74705SXin Li       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6382*67e74705SXin Li                                              ClassTemplate->getDeclContext(),
6383*67e74705SXin Li                                                        KWLoc, TemplateNameLoc,
6384*67e74705SXin Li                                                        TemplateParams,
6385*67e74705SXin Li                                                        ClassTemplate,
6386*67e74705SXin Li                                                        Converted,
6387*67e74705SXin Li                                                        TemplateArgs,
6388*67e74705SXin Li                                                        CanonType,
6389*67e74705SXin Li                                                        PrevPartial);
6390*67e74705SXin Li     SetNestedNameSpecifier(Partial, SS);
6391*67e74705SXin Li     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6392*67e74705SXin Li       Partial->setTemplateParameterListsInfo(
6393*67e74705SXin Li           Context, TemplateParameterLists.drop_back(1));
6394*67e74705SXin Li     }
6395*67e74705SXin Li 
6396*67e74705SXin Li     if (!PrevPartial)
6397*67e74705SXin Li       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6398*67e74705SXin Li     Specialization = Partial;
6399*67e74705SXin Li 
6400*67e74705SXin Li     // If we are providing an explicit specialization of a member class
6401*67e74705SXin Li     // template specialization, make a note of that.
6402*67e74705SXin Li     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6403*67e74705SXin Li       PrevPartial->setMemberSpecialization();
6404*67e74705SXin Li 
6405*67e74705SXin Li     // Check that all of the template parameters of the class template
6406*67e74705SXin Li     // partial specialization are deducible from the template
6407*67e74705SXin Li     // arguments. If not, this class template partial specialization
6408*67e74705SXin Li     // will never be used.
6409*67e74705SXin Li     llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6410*67e74705SXin Li     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6411*67e74705SXin Li                                TemplateParams->getDepth(),
6412*67e74705SXin Li                                DeducibleParams);
6413*67e74705SXin Li 
6414*67e74705SXin Li     if (!DeducibleParams.all()) {
6415*67e74705SXin Li       unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6416*67e74705SXin Li       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6417*67e74705SXin Li         << /*class template*/0 << (NumNonDeducible > 1)
6418*67e74705SXin Li         << SourceRange(TemplateNameLoc, RAngleLoc);
6419*67e74705SXin Li       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6420*67e74705SXin Li         if (!DeducibleParams[I]) {
6421*67e74705SXin Li           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6422*67e74705SXin Li           if (Param->getDeclName())
6423*67e74705SXin Li             Diag(Param->getLocation(),
6424*67e74705SXin Li                  diag::note_partial_spec_unused_parameter)
6425*67e74705SXin Li               << Param->getDeclName();
6426*67e74705SXin Li           else
6427*67e74705SXin Li             Diag(Param->getLocation(),
6428*67e74705SXin Li                  diag::note_partial_spec_unused_parameter)
6429*67e74705SXin Li               << "(anonymous)";
6430*67e74705SXin Li         }
6431*67e74705SXin Li       }
6432*67e74705SXin Li     }
6433*67e74705SXin Li   } else {
6434*67e74705SXin Li     // Create a new class template specialization declaration node for
6435*67e74705SXin Li     // this explicit specialization or friend declaration.
6436*67e74705SXin Li     Specialization
6437*67e74705SXin Li       = ClassTemplateSpecializationDecl::Create(Context, Kind,
6438*67e74705SXin Li                                              ClassTemplate->getDeclContext(),
6439*67e74705SXin Li                                                 KWLoc, TemplateNameLoc,
6440*67e74705SXin Li                                                 ClassTemplate,
6441*67e74705SXin Li                                                 Converted,
6442*67e74705SXin Li                                                 PrevDecl);
6443*67e74705SXin Li     SetNestedNameSpecifier(Specialization, SS);
6444*67e74705SXin Li     if (TemplateParameterLists.size() > 0) {
6445*67e74705SXin Li       Specialization->setTemplateParameterListsInfo(Context,
6446*67e74705SXin Li                                                     TemplateParameterLists);
6447*67e74705SXin Li     }
6448*67e74705SXin Li 
6449*67e74705SXin Li     if (!PrevDecl)
6450*67e74705SXin Li       ClassTemplate->AddSpecialization(Specialization, InsertPos);
6451*67e74705SXin Li 
6452*67e74705SXin Li     if (CurContext->isDependentContext()) {
6453*67e74705SXin Li       // -fms-extensions permits specialization of nested classes without
6454*67e74705SXin Li       // fully specializing the outer class(es).
6455*67e74705SXin Li       assert(getLangOpts().MicrosoftExt &&
6456*67e74705SXin Li              "Only possible with -fms-extensions!");
6457*67e74705SXin Li       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6458*67e74705SXin Li       CanonType = Context.getTemplateSpecializationType(
6459*67e74705SXin Li           CanonTemplate, Converted);
6460*67e74705SXin Li     } else {
6461*67e74705SXin Li       CanonType = Context.getTypeDeclType(Specialization);
6462*67e74705SXin Li     }
6463*67e74705SXin Li   }
6464*67e74705SXin Li 
6465*67e74705SXin Li   // C++ [temp.expl.spec]p6:
6466*67e74705SXin Li   //   If a template, a member template or the member of a class template is
6467*67e74705SXin Li   //   explicitly specialized then that specialization shall be declared
6468*67e74705SXin Li   //   before the first use of that specialization that would cause an implicit
6469*67e74705SXin Li   //   instantiation to take place, in every translation unit in which such a
6470*67e74705SXin Li   //   use occurs; no diagnostic is required.
6471*67e74705SXin Li   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6472*67e74705SXin Li     bool Okay = false;
6473*67e74705SXin Li     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6474*67e74705SXin Li       // Is there any previous explicit specialization declaration?
6475*67e74705SXin Li       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6476*67e74705SXin Li         Okay = true;
6477*67e74705SXin Li         break;
6478*67e74705SXin Li       }
6479*67e74705SXin Li     }
6480*67e74705SXin Li 
6481*67e74705SXin Li     if (!Okay) {
6482*67e74705SXin Li       SourceRange Range(TemplateNameLoc, RAngleLoc);
6483*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6484*67e74705SXin Li         << Context.getTypeDeclType(Specialization) << Range;
6485*67e74705SXin Li 
6486*67e74705SXin Li       Diag(PrevDecl->getPointOfInstantiation(),
6487*67e74705SXin Li            diag::note_instantiation_required_here)
6488*67e74705SXin Li         << (PrevDecl->getTemplateSpecializationKind()
6489*67e74705SXin Li                                                 != TSK_ImplicitInstantiation);
6490*67e74705SXin Li       return true;
6491*67e74705SXin Li     }
6492*67e74705SXin Li   }
6493*67e74705SXin Li 
6494*67e74705SXin Li   // If this is not a friend, note that this is an explicit specialization.
6495*67e74705SXin Li   if (TUK != TUK_Friend)
6496*67e74705SXin Li     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6497*67e74705SXin Li 
6498*67e74705SXin Li   // Check that this isn't a redefinition of this specialization.
6499*67e74705SXin Li   if (TUK == TUK_Definition) {
6500*67e74705SXin Li     RecordDecl *Def = Specialization->getDefinition();
6501*67e74705SXin Li     NamedDecl *Hidden = nullptr;
6502*67e74705SXin Li     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6503*67e74705SXin Li       SkipBody->ShouldSkip = true;
6504*67e74705SXin Li       makeMergedDefinitionVisible(Hidden, KWLoc);
6505*67e74705SXin Li       // From here on out, treat this as just a redeclaration.
6506*67e74705SXin Li       TUK = TUK_Declaration;
6507*67e74705SXin Li     } else if (Def) {
6508*67e74705SXin Li       SourceRange Range(TemplateNameLoc, RAngleLoc);
6509*67e74705SXin Li       Diag(TemplateNameLoc, diag::err_redefinition)
6510*67e74705SXin Li         << Context.getTypeDeclType(Specialization) << Range;
6511*67e74705SXin Li       Diag(Def->getLocation(), diag::note_previous_definition);
6512*67e74705SXin Li       Specialization->setInvalidDecl();
6513*67e74705SXin Li       return true;
6514*67e74705SXin Li     }
6515*67e74705SXin Li   }
6516*67e74705SXin Li 
6517*67e74705SXin Li   if (Attr)
6518*67e74705SXin Li     ProcessDeclAttributeList(S, Specialization, Attr);
6519*67e74705SXin Li 
6520*67e74705SXin Li   // Add alignment attributes if necessary; these attributes are checked when
6521*67e74705SXin Li   // the ASTContext lays out the structure.
6522*67e74705SXin Li   if (TUK == TUK_Definition) {
6523*67e74705SXin Li     AddAlignmentAttributesForRecord(Specialization);
6524*67e74705SXin Li     AddMsStructLayoutForRecord(Specialization);
6525*67e74705SXin Li   }
6526*67e74705SXin Li 
6527*67e74705SXin Li   if (ModulePrivateLoc.isValid())
6528*67e74705SXin Li     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6529*67e74705SXin Li       << (isPartialSpecialization? 1 : 0)
6530*67e74705SXin Li       << FixItHint::CreateRemoval(ModulePrivateLoc);
6531*67e74705SXin Li 
6532*67e74705SXin Li   // Build the fully-sugared type for this class template
6533*67e74705SXin Li   // specialization as the user wrote in the specialization
6534*67e74705SXin Li   // itself. This means that we'll pretty-print the type retrieved
6535*67e74705SXin Li   // from the specialization's declaration the way that the user
6536*67e74705SXin Li   // actually wrote the specialization, rather than formatting the
6537*67e74705SXin Li   // name based on the "canonical" representation used to store the
6538*67e74705SXin Li   // template arguments in the specialization.
6539*67e74705SXin Li   TypeSourceInfo *WrittenTy
6540*67e74705SXin Li     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6541*67e74705SXin Li                                                 TemplateArgs, CanonType);
6542*67e74705SXin Li   if (TUK != TUK_Friend) {
6543*67e74705SXin Li     Specialization->setTypeAsWritten(WrittenTy);
6544*67e74705SXin Li     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6545*67e74705SXin Li   }
6546*67e74705SXin Li 
6547*67e74705SXin Li   // C++ [temp.expl.spec]p9:
6548*67e74705SXin Li   //   A template explicit specialization is in the scope of the
6549*67e74705SXin Li   //   namespace in which the template was defined.
6550*67e74705SXin Li   //
6551*67e74705SXin Li   // We actually implement this paragraph where we set the semantic
6552*67e74705SXin Li   // context (in the creation of the ClassTemplateSpecializationDecl),
6553*67e74705SXin Li   // but we also maintain the lexical context where the actual
6554*67e74705SXin Li   // definition occurs.
6555*67e74705SXin Li   Specialization->setLexicalDeclContext(CurContext);
6556*67e74705SXin Li 
6557*67e74705SXin Li   // We may be starting the definition of this specialization.
6558*67e74705SXin Li   if (TUK == TUK_Definition)
6559*67e74705SXin Li     Specialization->startDefinition();
6560*67e74705SXin Li 
6561*67e74705SXin Li   if (TUK == TUK_Friend) {
6562*67e74705SXin Li     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6563*67e74705SXin Li                                             TemplateNameLoc,
6564*67e74705SXin Li                                             WrittenTy,
6565*67e74705SXin Li                                             /*FIXME:*/KWLoc);
6566*67e74705SXin Li     Friend->setAccess(AS_public);
6567*67e74705SXin Li     CurContext->addDecl(Friend);
6568*67e74705SXin Li   } else {
6569*67e74705SXin Li     // Add the specialization into its lexical context, so that it can
6570*67e74705SXin Li     // be seen when iterating through the list of declarations in that
6571*67e74705SXin Li     // context. However, specializations are not found by name lookup.
6572*67e74705SXin Li     CurContext->addDecl(Specialization);
6573*67e74705SXin Li   }
6574*67e74705SXin Li   return Specialization;
6575*67e74705SXin Li }
6576*67e74705SXin Li 
ActOnTemplateDeclarator(Scope * S,MultiTemplateParamsArg TemplateParameterLists,Declarator & D)6577*67e74705SXin Li Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6578*67e74705SXin Li                               MultiTemplateParamsArg TemplateParameterLists,
6579*67e74705SXin Li                                     Declarator &D) {
6580*67e74705SXin Li   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6581*67e74705SXin Li   ActOnDocumentableDecl(NewDecl);
6582*67e74705SXin Li   return NewDecl;
6583*67e74705SXin Li }
6584*67e74705SXin Li 
6585*67e74705SXin Li /// \brief Strips various properties off an implicit instantiation
6586*67e74705SXin Li /// that has just been explicitly specialized.
StripImplicitInstantiation(NamedDecl * D)6587*67e74705SXin Li static void StripImplicitInstantiation(NamedDecl *D) {
6588*67e74705SXin Li   D->dropAttr<DLLImportAttr>();
6589*67e74705SXin Li   D->dropAttr<DLLExportAttr>();
6590*67e74705SXin Li 
6591*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6592*67e74705SXin Li     FD->setInlineSpecified(false);
6593*67e74705SXin Li }
6594*67e74705SXin Li 
6595*67e74705SXin Li /// \brief Compute the diagnostic location for an explicit instantiation
6596*67e74705SXin Li //  declaration or definition.
DiagLocForExplicitInstantiation(NamedDecl * D,SourceLocation PointOfInstantiation)6597*67e74705SXin Li static SourceLocation DiagLocForExplicitInstantiation(
6598*67e74705SXin Li     NamedDecl* D, SourceLocation PointOfInstantiation) {
6599*67e74705SXin Li   // Explicit instantiations following a specialization have no effect and
6600*67e74705SXin Li   // hence no PointOfInstantiation. In that case, walk decl backwards
6601*67e74705SXin Li   // until a valid name loc is found.
6602*67e74705SXin Li   SourceLocation PrevDiagLoc = PointOfInstantiation;
6603*67e74705SXin Li   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6604*67e74705SXin Li        Prev = Prev->getPreviousDecl()) {
6605*67e74705SXin Li     PrevDiagLoc = Prev->getLocation();
6606*67e74705SXin Li   }
6607*67e74705SXin Li   assert(PrevDiagLoc.isValid() &&
6608*67e74705SXin Li          "Explicit instantiation without point of instantiation?");
6609*67e74705SXin Li   return PrevDiagLoc;
6610*67e74705SXin Li }
6611*67e74705SXin Li 
6612*67e74705SXin Li /// \brief Diagnose cases where we have an explicit template specialization
6613*67e74705SXin Li /// before/after an explicit template instantiation, producing diagnostics
6614*67e74705SXin Li /// for those cases where they are required and determining whether the
6615*67e74705SXin Li /// new specialization/instantiation will have any effect.
6616*67e74705SXin Li ///
6617*67e74705SXin Li /// \param NewLoc the location of the new explicit specialization or
6618*67e74705SXin Li /// instantiation.
6619*67e74705SXin Li ///
6620*67e74705SXin Li /// \param NewTSK the kind of the new explicit specialization or instantiation.
6621*67e74705SXin Li ///
6622*67e74705SXin Li /// \param PrevDecl the previous declaration of the entity.
6623*67e74705SXin Li ///
6624*67e74705SXin Li /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6625*67e74705SXin Li ///
6626*67e74705SXin Li /// \param PrevPointOfInstantiation if valid, indicates where the previus
6627*67e74705SXin Li /// declaration was instantiated (either implicitly or explicitly).
6628*67e74705SXin Li ///
6629*67e74705SXin Li /// \param HasNoEffect will be set to true to indicate that the new
6630*67e74705SXin Li /// specialization or instantiation has no effect and should be ignored.
6631*67e74705SXin Li ///
6632*67e74705SXin Li /// \returns true if there was an error that should prevent the introduction of
6633*67e74705SXin Li /// the new declaration into the AST, false otherwise.
6634*67e74705SXin Li bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,TemplateSpecializationKind NewTSK,NamedDecl * PrevDecl,TemplateSpecializationKind PrevTSK,SourceLocation PrevPointOfInstantiation,bool & HasNoEffect)6635*67e74705SXin Li Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6636*67e74705SXin Li                                              TemplateSpecializationKind NewTSK,
6637*67e74705SXin Li                                              NamedDecl *PrevDecl,
6638*67e74705SXin Li                                              TemplateSpecializationKind PrevTSK,
6639*67e74705SXin Li                                         SourceLocation PrevPointOfInstantiation,
6640*67e74705SXin Li                                              bool &HasNoEffect) {
6641*67e74705SXin Li   HasNoEffect = false;
6642*67e74705SXin Li 
6643*67e74705SXin Li   switch (NewTSK) {
6644*67e74705SXin Li   case TSK_Undeclared:
6645*67e74705SXin Li   case TSK_ImplicitInstantiation:
6646*67e74705SXin Li     assert(
6647*67e74705SXin Li         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6648*67e74705SXin Li         "previous declaration must be implicit!");
6649*67e74705SXin Li     return false;
6650*67e74705SXin Li 
6651*67e74705SXin Li   case TSK_ExplicitSpecialization:
6652*67e74705SXin Li     switch (PrevTSK) {
6653*67e74705SXin Li     case TSK_Undeclared:
6654*67e74705SXin Li     case TSK_ExplicitSpecialization:
6655*67e74705SXin Li       // Okay, we're just specializing something that is either already
6656*67e74705SXin Li       // explicitly specialized or has merely been mentioned without any
6657*67e74705SXin Li       // instantiation.
6658*67e74705SXin Li       return false;
6659*67e74705SXin Li 
6660*67e74705SXin Li     case TSK_ImplicitInstantiation:
6661*67e74705SXin Li       if (PrevPointOfInstantiation.isInvalid()) {
6662*67e74705SXin Li         // The declaration itself has not actually been instantiated, so it is
6663*67e74705SXin Li         // still okay to specialize it.
6664*67e74705SXin Li         StripImplicitInstantiation(PrevDecl);
6665*67e74705SXin Li         return false;
6666*67e74705SXin Li       }
6667*67e74705SXin Li       // Fall through
6668*67e74705SXin Li 
6669*67e74705SXin Li     case TSK_ExplicitInstantiationDeclaration:
6670*67e74705SXin Li     case TSK_ExplicitInstantiationDefinition:
6671*67e74705SXin Li       assert((PrevTSK == TSK_ImplicitInstantiation ||
6672*67e74705SXin Li               PrevPointOfInstantiation.isValid()) &&
6673*67e74705SXin Li              "Explicit instantiation without point of instantiation?");
6674*67e74705SXin Li 
6675*67e74705SXin Li       // C++ [temp.expl.spec]p6:
6676*67e74705SXin Li       //   If a template, a member template or the member of a class template
6677*67e74705SXin Li       //   is explicitly specialized then that specialization shall be declared
6678*67e74705SXin Li       //   before the first use of that specialization that would cause an
6679*67e74705SXin Li       //   implicit instantiation to take place, in every translation unit in
6680*67e74705SXin Li       //   which such a use occurs; no diagnostic is required.
6681*67e74705SXin Li       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6682*67e74705SXin Li         // Is there any previous explicit specialization declaration?
6683*67e74705SXin Li         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6684*67e74705SXin Li           return false;
6685*67e74705SXin Li       }
6686*67e74705SXin Li 
6687*67e74705SXin Li       Diag(NewLoc, diag::err_specialization_after_instantiation)
6688*67e74705SXin Li         << PrevDecl;
6689*67e74705SXin Li       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6690*67e74705SXin Li         << (PrevTSK != TSK_ImplicitInstantiation);
6691*67e74705SXin Li 
6692*67e74705SXin Li       return true;
6693*67e74705SXin Li     }
6694*67e74705SXin Li 
6695*67e74705SXin Li   case TSK_ExplicitInstantiationDeclaration:
6696*67e74705SXin Li     switch (PrevTSK) {
6697*67e74705SXin Li     case TSK_ExplicitInstantiationDeclaration:
6698*67e74705SXin Li       // This explicit instantiation declaration is redundant (that's okay).
6699*67e74705SXin Li       HasNoEffect = true;
6700*67e74705SXin Li       return false;
6701*67e74705SXin Li 
6702*67e74705SXin Li     case TSK_Undeclared:
6703*67e74705SXin Li     case TSK_ImplicitInstantiation:
6704*67e74705SXin Li       // We're explicitly instantiating something that may have already been
6705*67e74705SXin Li       // implicitly instantiated; that's fine.
6706*67e74705SXin Li       return false;
6707*67e74705SXin Li 
6708*67e74705SXin Li     case TSK_ExplicitSpecialization:
6709*67e74705SXin Li       // C++0x [temp.explicit]p4:
6710*67e74705SXin Li       //   For a given set of template parameters, if an explicit instantiation
6711*67e74705SXin Li       //   of a template appears after a declaration of an explicit
6712*67e74705SXin Li       //   specialization for that template, the explicit instantiation has no
6713*67e74705SXin Li       //   effect.
6714*67e74705SXin Li       HasNoEffect = true;
6715*67e74705SXin Li       return false;
6716*67e74705SXin Li 
6717*67e74705SXin Li     case TSK_ExplicitInstantiationDefinition:
6718*67e74705SXin Li       // C++0x [temp.explicit]p10:
6719*67e74705SXin Li       //   If an entity is the subject of both an explicit instantiation
6720*67e74705SXin Li       //   declaration and an explicit instantiation definition in the same
6721*67e74705SXin Li       //   translation unit, the definition shall follow the declaration.
6722*67e74705SXin Li       Diag(NewLoc,
6723*67e74705SXin Li            diag::err_explicit_instantiation_declaration_after_definition);
6724*67e74705SXin Li 
6725*67e74705SXin Li       // Explicit instantiations following a specialization have no effect and
6726*67e74705SXin Li       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6727*67e74705SXin Li       // until a valid name loc is found.
6728*67e74705SXin Li       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6729*67e74705SXin Li            diag::note_explicit_instantiation_definition_here);
6730*67e74705SXin Li       HasNoEffect = true;
6731*67e74705SXin Li       return false;
6732*67e74705SXin Li     }
6733*67e74705SXin Li 
6734*67e74705SXin Li   case TSK_ExplicitInstantiationDefinition:
6735*67e74705SXin Li     switch (PrevTSK) {
6736*67e74705SXin Li     case TSK_Undeclared:
6737*67e74705SXin Li     case TSK_ImplicitInstantiation:
6738*67e74705SXin Li       // We're explicitly instantiating something that may have already been
6739*67e74705SXin Li       // implicitly instantiated; that's fine.
6740*67e74705SXin Li       return false;
6741*67e74705SXin Li 
6742*67e74705SXin Li     case TSK_ExplicitSpecialization:
6743*67e74705SXin Li       // C++ DR 259, C++0x [temp.explicit]p4:
6744*67e74705SXin Li       //   For a given set of template parameters, if an explicit
6745*67e74705SXin Li       //   instantiation of a template appears after a declaration of
6746*67e74705SXin Li       //   an explicit specialization for that template, the explicit
6747*67e74705SXin Li       //   instantiation has no effect.
6748*67e74705SXin Li       //
6749*67e74705SXin Li       // In C++98/03 mode, we only give an extension warning here, because it
6750*67e74705SXin Li       // is not harmful to try to explicitly instantiate something that
6751*67e74705SXin Li       // has been explicitly specialized.
6752*67e74705SXin Li       Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6753*67e74705SXin Li            diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6754*67e74705SXin Li            diag::ext_explicit_instantiation_after_specialization)
6755*67e74705SXin Li         << PrevDecl;
6756*67e74705SXin Li       Diag(PrevDecl->getLocation(),
6757*67e74705SXin Li            diag::note_previous_template_specialization);
6758*67e74705SXin Li       HasNoEffect = true;
6759*67e74705SXin Li       return false;
6760*67e74705SXin Li 
6761*67e74705SXin Li     case TSK_ExplicitInstantiationDeclaration:
6762*67e74705SXin Li       // We're explicity instantiating a definition for something for which we
6763*67e74705SXin Li       // were previously asked to suppress instantiations. That's fine.
6764*67e74705SXin Li 
6765*67e74705SXin Li       // C++0x [temp.explicit]p4:
6766*67e74705SXin Li       //   For a given set of template parameters, if an explicit instantiation
6767*67e74705SXin Li       //   of a template appears after a declaration of an explicit
6768*67e74705SXin Li       //   specialization for that template, the explicit instantiation has no
6769*67e74705SXin Li       //   effect.
6770*67e74705SXin Li       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6771*67e74705SXin Li         // Is there any previous explicit specialization declaration?
6772*67e74705SXin Li         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6773*67e74705SXin Li           HasNoEffect = true;
6774*67e74705SXin Li           break;
6775*67e74705SXin Li         }
6776*67e74705SXin Li       }
6777*67e74705SXin Li 
6778*67e74705SXin Li       return false;
6779*67e74705SXin Li 
6780*67e74705SXin Li     case TSK_ExplicitInstantiationDefinition:
6781*67e74705SXin Li       // C++0x [temp.spec]p5:
6782*67e74705SXin Li       //   For a given template and a given set of template-arguments,
6783*67e74705SXin Li       //     - an explicit instantiation definition shall appear at most once
6784*67e74705SXin Li       //       in a program,
6785*67e74705SXin Li 
6786*67e74705SXin Li       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6787*67e74705SXin Li       Diag(NewLoc, (getLangOpts().MSVCCompat)
6788*67e74705SXin Li                        ? diag::ext_explicit_instantiation_duplicate
6789*67e74705SXin Li                        : diag::err_explicit_instantiation_duplicate)
6790*67e74705SXin Li           << PrevDecl;
6791*67e74705SXin Li       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6792*67e74705SXin Li            diag::note_previous_explicit_instantiation);
6793*67e74705SXin Li       HasNoEffect = true;
6794*67e74705SXin Li       return false;
6795*67e74705SXin Li     }
6796*67e74705SXin Li   }
6797*67e74705SXin Li 
6798*67e74705SXin Li   llvm_unreachable("Missing specialization/instantiation case?");
6799*67e74705SXin Li }
6800*67e74705SXin Li 
6801*67e74705SXin Li /// \brief Perform semantic analysis for the given dependent function
6802*67e74705SXin Li /// template specialization.
6803*67e74705SXin Li ///
6804*67e74705SXin Li /// The only possible way to get a dependent function template specialization
6805*67e74705SXin Li /// is with a friend declaration, like so:
6806*67e74705SXin Li ///
6807*67e74705SXin Li /// \code
6808*67e74705SXin Li ///   template \<class T> void foo(T);
6809*67e74705SXin Li ///   template \<class T> class A {
6810*67e74705SXin Li ///     friend void foo<>(T);
6811*67e74705SXin Li ///   };
6812*67e74705SXin Li /// \endcode
6813*67e74705SXin Li ///
6814*67e74705SXin Li /// There really isn't any useful analysis we can do here, so we
6815*67e74705SXin Li /// just store the information.
6816*67e74705SXin Li bool
CheckDependentFunctionTemplateSpecialization(FunctionDecl * FD,const TemplateArgumentListInfo & ExplicitTemplateArgs,LookupResult & Previous)6817*67e74705SXin Li Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6818*67e74705SXin Li                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
6819*67e74705SXin Li                                                    LookupResult &Previous) {
6820*67e74705SXin Li   // Remove anything from Previous that isn't a function template in
6821*67e74705SXin Li   // the correct context.
6822*67e74705SXin Li   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6823*67e74705SXin Li   LookupResult::Filter F = Previous.makeFilter();
6824*67e74705SXin Li   while (F.hasNext()) {
6825*67e74705SXin Li     NamedDecl *D = F.next()->getUnderlyingDecl();
6826*67e74705SXin Li     if (!isa<FunctionTemplateDecl>(D) ||
6827*67e74705SXin Li         !FDLookupContext->InEnclosingNamespaceSetOf(
6828*67e74705SXin Li                               D->getDeclContext()->getRedeclContext()))
6829*67e74705SXin Li       F.erase();
6830*67e74705SXin Li   }
6831*67e74705SXin Li   F.done();
6832*67e74705SXin Li 
6833*67e74705SXin Li   // Should this be diagnosed here?
6834*67e74705SXin Li   if (Previous.empty()) return true;
6835*67e74705SXin Li 
6836*67e74705SXin Li   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6837*67e74705SXin Li                                          ExplicitTemplateArgs);
6838*67e74705SXin Li   return false;
6839*67e74705SXin Li }
6840*67e74705SXin Li 
6841*67e74705SXin Li /// \brief Perform semantic analysis for the given function template
6842*67e74705SXin Li /// specialization.
6843*67e74705SXin Li ///
6844*67e74705SXin Li /// This routine performs all of the semantic analysis required for an
6845*67e74705SXin Li /// explicit function template specialization. On successful completion,
6846*67e74705SXin Li /// the function declaration \p FD will become a function template
6847*67e74705SXin Li /// specialization.
6848*67e74705SXin Li ///
6849*67e74705SXin Li /// \param FD the function declaration, which will be updated to become a
6850*67e74705SXin Li /// function template specialization.
6851*67e74705SXin Li ///
6852*67e74705SXin Li /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6853*67e74705SXin Li /// if any. Note that this may be valid info even when 0 arguments are
6854*67e74705SXin Li /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6855*67e74705SXin Li /// as it anyway contains info on the angle brackets locations.
6856*67e74705SXin Li ///
6857*67e74705SXin Li /// \param Previous the set of declarations that may be specialized by
6858*67e74705SXin Li /// this function specialization.
CheckFunctionTemplateSpecialization(FunctionDecl * FD,TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous)6859*67e74705SXin Li bool Sema::CheckFunctionTemplateSpecialization(
6860*67e74705SXin Li     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6861*67e74705SXin Li     LookupResult &Previous) {
6862*67e74705SXin Li   // The set of function template specializations that could match this
6863*67e74705SXin Li   // explicit function template specialization.
6864*67e74705SXin Li   UnresolvedSet<8> Candidates;
6865*67e74705SXin Li   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6866*67e74705SXin Li                                             /*ForTakingAddress=*/false);
6867*67e74705SXin Li 
6868*67e74705SXin Li   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6869*67e74705SXin Li       ConvertedTemplateArgs;
6870*67e74705SXin Li 
6871*67e74705SXin Li   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6872*67e74705SXin Li   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6873*67e74705SXin Li          I != E; ++I) {
6874*67e74705SXin Li     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6875*67e74705SXin Li     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6876*67e74705SXin Li       // Only consider templates found within the same semantic lookup scope as
6877*67e74705SXin Li       // FD.
6878*67e74705SXin Li       if (!FDLookupContext->InEnclosingNamespaceSetOf(
6879*67e74705SXin Li                                 Ovl->getDeclContext()->getRedeclContext()))
6880*67e74705SXin Li         continue;
6881*67e74705SXin Li 
6882*67e74705SXin Li       // When matching a constexpr member function template specialization
6883*67e74705SXin Li       // against the primary template, we don't yet know whether the
6884*67e74705SXin Li       // specialization has an implicit 'const' (because we don't know whether
6885*67e74705SXin Li       // it will be a static member function until we know which template it
6886*67e74705SXin Li       // specializes), so adjust it now assuming it specializes this template.
6887*67e74705SXin Li       QualType FT = FD->getType();
6888*67e74705SXin Li       if (FD->isConstexpr()) {
6889*67e74705SXin Li         CXXMethodDecl *OldMD =
6890*67e74705SXin Li           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6891*67e74705SXin Li         if (OldMD && OldMD->isConst()) {
6892*67e74705SXin Li           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6893*67e74705SXin Li           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6894*67e74705SXin Li           EPI.TypeQuals |= Qualifiers::Const;
6895*67e74705SXin Li           FT = Context.getFunctionType(FPT->getReturnType(),
6896*67e74705SXin Li                                        FPT->getParamTypes(), EPI);
6897*67e74705SXin Li         }
6898*67e74705SXin Li       }
6899*67e74705SXin Li 
6900*67e74705SXin Li       TemplateArgumentListInfo Args;
6901*67e74705SXin Li       if (ExplicitTemplateArgs)
6902*67e74705SXin Li         Args = *ExplicitTemplateArgs;
6903*67e74705SXin Li 
6904*67e74705SXin Li       // C++ [temp.expl.spec]p11:
6905*67e74705SXin Li       //   A trailing template-argument can be left unspecified in the
6906*67e74705SXin Li       //   template-id naming an explicit function template specialization
6907*67e74705SXin Li       //   provided it can be deduced from the function argument type.
6908*67e74705SXin Li       // Perform template argument deduction to determine whether we may be
6909*67e74705SXin Li       // specializing this template.
6910*67e74705SXin Li       // FIXME: It is somewhat wasteful to build
6911*67e74705SXin Li       TemplateDeductionInfo Info(FailedCandidates.getLocation());
6912*67e74705SXin Li       FunctionDecl *Specialization = nullptr;
6913*67e74705SXin Li       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6914*67e74705SXin Li               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6915*67e74705SXin Li               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6916*67e74705SXin Li               Info)) {
6917*67e74705SXin Li         // Template argument deduction failed; record why it failed, so
6918*67e74705SXin Li         // that we can provide nifty diagnostics.
6919*67e74705SXin Li         FailedCandidates.addCandidate().set(
6920*67e74705SXin Li             I.getPair(), FunTmpl->getTemplatedDecl(),
6921*67e74705SXin Li             MakeDeductionFailureInfo(Context, TDK, Info));
6922*67e74705SXin Li         (void)TDK;
6923*67e74705SXin Li         continue;
6924*67e74705SXin Li       }
6925*67e74705SXin Li 
6926*67e74705SXin Li       // Record this candidate.
6927*67e74705SXin Li       if (ExplicitTemplateArgs)
6928*67e74705SXin Li         ConvertedTemplateArgs[Specialization] = std::move(Args);
6929*67e74705SXin Li       Candidates.addDecl(Specialization, I.getAccess());
6930*67e74705SXin Li     }
6931*67e74705SXin Li   }
6932*67e74705SXin Li 
6933*67e74705SXin Li   // Find the most specialized function template.
6934*67e74705SXin Li   UnresolvedSetIterator Result = getMostSpecialized(
6935*67e74705SXin Li       Candidates.begin(), Candidates.end(), FailedCandidates,
6936*67e74705SXin Li       FD->getLocation(),
6937*67e74705SXin Li       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6938*67e74705SXin Li       PDiag(diag::err_function_template_spec_ambiguous)
6939*67e74705SXin Li           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6940*67e74705SXin Li       PDiag(diag::note_function_template_spec_matched));
6941*67e74705SXin Li 
6942*67e74705SXin Li   if (Result == Candidates.end())
6943*67e74705SXin Li     return true;
6944*67e74705SXin Li 
6945*67e74705SXin Li   // Ignore access information;  it doesn't figure into redeclaration checking.
6946*67e74705SXin Li   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6947*67e74705SXin Li 
6948*67e74705SXin Li   // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6949*67e74705SXin Li   // an explicit specialization (14.8.3) [...] of a concept definition.
6950*67e74705SXin Li   if (Specialization->getPrimaryTemplate()->isConcept()) {
6951*67e74705SXin Li     Diag(FD->getLocation(), diag::err_concept_specialized)
6952*67e74705SXin Li         << 0 /*function*/ << 1 /*explicitly specialized*/;
6953*67e74705SXin Li     Diag(Specialization->getLocation(), diag::note_previous_declaration);
6954*67e74705SXin Li     return true;
6955*67e74705SXin Li   }
6956*67e74705SXin Li 
6957*67e74705SXin Li   FunctionTemplateSpecializationInfo *SpecInfo
6958*67e74705SXin Li     = Specialization->getTemplateSpecializationInfo();
6959*67e74705SXin Li   assert(SpecInfo && "Function template specialization info missing?");
6960*67e74705SXin Li 
6961*67e74705SXin Li   // Note: do not overwrite location info if previous template
6962*67e74705SXin Li   // specialization kind was explicit.
6963*67e74705SXin Li   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6964*67e74705SXin Li   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6965*67e74705SXin Li     Specialization->setLocation(FD->getLocation());
6966*67e74705SXin Li     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6967*67e74705SXin Li     // function can differ from the template declaration with respect to
6968*67e74705SXin Li     // the constexpr specifier.
6969*67e74705SXin Li     Specialization->setConstexpr(FD->isConstexpr());
6970*67e74705SXin Li   }
6971*67e74705SXin Li 
6972*67e74705SXin Li   // FIXME: Check if the prior specialization has a point of instantiation.
6973*67e74705SXin Li   // If so, we have run afoul of .
6974*67e74705SXin Li 
6975*67e74705SXin Li   // If this is a friend declaration, then we're not really declaring
6976*67e74705SXin Li   // an explicit specialization.
6977*67e74705SXin Li   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6978*67e74705SXin Li 
6979*67e74705SXin Li   // Check the scope of this explicit specialization.
6980*67e74705SXin Li   if (!isFriend &&
6981*67e74705SXin Li       CheckTemplateSpecializationScope(*this,
6982*67e74705SXin Li                                        Specialization->getPrimaryTemplate(),
6983*67e74705SXin Li                                        Specialization, FD->getLocation(),
6984*67e74705SXin Li                                        false))
6985*67e74705SXin Li     return true;
6986*67e74705SXin Li 
6987*67e74705SXin Li   // C++ [temp.expl.spec]p6:
6988*67e74705SXin Li   //   If a template, a member template or the member of a class template is
6989*67e74705SXin Li   //   explicitly specialized then that specialization shall be declared
6990*67e74705SXin Li   //   before the first use of that specialization that would cause an implicit
6991*67e74705SXin Li   //   instantiation to take place, in every translation unit in which such a
6992*67e74705SXin Li   //   use occurs; no diagnostic is required.
6993*67e74705SXin Li   bool HasNoEffect = false;
6994*67e74705SXin Li   if (!isFriend &&
6995*67e74705SXin Li       CheckSpecializationInstantiationRedecl(FD->getLocation(),
6996*67e74705SXin Li                                              TSK_ExplicitSpecialization,
6997*67e74705SXin Li                                              Specialization,
6998*67e74705SXin Li                                    SpecInfo->getTemplateSpecializationKind(),
6999*67e74705SXin Li                                          SpecInfo->getPointOfInstantiation(),
7000*67e74705SXin Li                                              HasNoEffect))
7001*67e74705SXin Li     return true;
7002*67e74705SXin Li 
7003*67e74705SXin Li   // Mark the prior declaration as an explicit specialization, so that later
7004*67e74705SXin Li   // clients know that this is an explicit specialization.
7005*67e74705SXin Li   if (!isFriend) {
7006*67e74705SXin Li     // Since explicit specializations do not inherit '=delete' from their
7007*67e74705SXin Li     // primary function template - check if the 'specialization' that was
7008*67e74705SXin Li     // implicitly generated (during template argument deduction for partial
7009*67e74705SXin Li     // ordering) from the most specialized of all the function templates that
7010*67e74705SXin Li     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
7011*67e74705SXin Li     // first check that it was implicitly generated during template argument
7012*67e74705SXin Li     // deduction by making sure it wasn't referenced, and then reset the deleted
7013*67e74705SXin Li     // flag to not-deleted, so that we can inherit that information from 'FD'.
7014*67e74705SXin Li     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7015*67e74705SXin Li         !Specialization->getCanonicalDecl()->isReferenced()) {
7016*67e74705SXin Li       assert(
7017*67e74705SXin Li           Specialization->getCanonicalDecl() == Specialization &&
7018*67e74705SXin Li           "This must be the only existing declaration of this specialization");
7019*67e74705SXin Li       Specialization->setDeletedAsWritten(false);
7020*67e74705SXin Li     }
7021*67e74705SXin Li     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
7022*67e74705SXin Li     MarkUnusedFileScopedDecl(Specialization);
7023*67e74705SXin Li   }
7024*67e74705SXin Li 
7025*67e74705SXin Li   // Turn the given function declaration into a function template
7026*67e74705SXin Li   // specialization, with the template arguments from the previous
7027*67e74705SXin Li   // specialization.
7028*67e74705SXin Li   // Take copies of (semantic and syntactic) template argument lists.
7029*67e74705SXin Li   const TemplateArgumentList* TemplArgs = new (Context)
7030*67e74705SXin Li     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
7031*67e74705SXin Li   FD->setFunctionTemplateSpecialization(
7032*67e74705SXin Li       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7033*67e74705SXin Li       SpecInfo->getTemplateSpecializationKind(),
7034*67e74705SXin Li       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
7035*67e74705SXin Li 
7036*67e74705SXin Li   // The "previous declaration" for this function template specialization is
7037*67e74705SXin Li   // the prior function template specialization.
7038*67e74705SXin Li   Previous.clear();
7039*67e74705SXin Li   Previous.addDecl(Specialization);
7040*67e74705SXin Li   return false;
7041*67e74705SXin Li }
7042*67e74705SXin Li 
7043*67e74705SXin Li /// \brief Perform semantic analysis for the given non-template member
7044*67e74705SXin Li /// specialization.
7045*67e74705SXin Li ///
7046*67e74705SXin Li /// This routine performs all of the semantic analysis required for an
7047*67e74705SXin Li /// explicit member function specialization. On successful completion,
7048*67e74705SXin Li /// the function declaration \p FD will become a member function
7049*67e74705SXin Li /// specialization.
7050*67e74705SXin Li ///
7051*67e74705SXin Li /// \param Member the member declaration, which will be updated to become a
7052*67e74705SXin Li /// specialization.
7053*67e74705SXin Li ///
7054*67e74705SXin Li /// \param Previous the set of declarations, one of which may be specialized
7055*67e74705SXin Li /// by this function specialization;  the set will be modified to contain the
7056*67e74705SXin Li /// redeclared member.
7057*67e74705SXin Li bool
CheckMemberSpecialization(NamedDecl * Member,LookupResult & Previous)7058*67e74705SXin Li Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
7059*67e74705SXin Li   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
7060*67e74705SXin Li 
7061*67e74705SXin Li   // Try to find the member we are instantiating.
7062*67e74705SXin Li   NamedDecl *FoundInstantiation = nullptr;
7063*67e74705SXin Li   NamedDecl *Instantiation = nullptr;
7064*67e74705SXin Li   NamedDecl *InstantiatedFrom = nullptr;
7065*67e74705SXin Li   MemberSpecializationInfo *MSInfo = nullptr;
7066*67e74705SXin Li 
7067*67e74705SXin Li   if (Previous.empty()) {
7068*67e74705SXin Li     // Nowhere to look anyway.
7069*67e74705SXin Li   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
7070*67e74705SXin Li     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7071*67e74705SXin Li            I != E; ++I) {
7072*67e74705SXin Li       NamedDecl *D = (*I)->getUnderlyingDecl();
7073*67e74705SXin Li       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
7074*67e74705SXin Li         QualType Adjusted = Function->getType();
7075*67e74705SXin Li         if (!hasExplicitCallingConv(Adjusted))
7076*67e74705SXin Li           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7077*67e74705SXin Li         if (Context.hasSameType(Adjusted, Method->getType())) {
7078*67e74705SXin Li           FoundInstantiation = *I;
7079*67e74705SXin Li           Instantiation = Method;
7080*67e74705SXin Li           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
7081*67e74705SXin Li           MSInfo = Method->getMemberSpecializationInfo();
7082*67e74705SXin Li           break;
7083*67e74705SXin Li         }
7084*67e74705SXin Li       }
7085*67e74705SXin Li     }
7086*67e74705SXin Li   } else if (isa<VarDecl>(Member)) {
7087*67e74705SXin Li     VarDecl *PrevVar;
7088*67e74705SXin Li     if (Previous.isSingleResult() &&
7089*67e74705SXin Li         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
7090*67e74705SXin Li       if (PrevVar->isStaticDataMember()) {
7091*67e74705SXin Li         FoundInstantiation = Previous.getRepresentativeDecl();
7092*67e74705SXin Li         Instantiation = PrevVar;
7093*67e74705SXin Li         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
7094*67e74705SXin Li         MSInfo = PrevVar->getMemberSpecializationInfo();
7095*67e74705SXin Li       }
7096*67e74705SXin Li   } else if (isa<RecordDecl>(Member)) {
7097*67e74705SXin Li     CXXRecordDecl *PrevRecord;
7098*67e74705SXin Li     if (Previous.isSingleResult() &&
7099*67e74705SXin Li         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7100*67e74705SXin Li       FoundInstantiation = Previous.getRepresentativeDecl();
7101*67e74705SXin Li       Instantiation = PrevRecord;
7102*67e74705SXin Li       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
7103*67e74705SXin Li       MSInfo = PrevRecord->getMemberSpecializationInfo();
7104*67e74705SXin Li     }
7105*67e74705SXin Li   } else if (isa<EnumDecl>(Member)) {
7106*67e74705SXin Li     EnumDecl *PrevEnum;
7107*67e74705SXin Li     if (Previous.isSingleResult() &&
7108*67e74705SXin Li         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7109*67e74705SXin Li       FoundInstantiation = Previous.getRepresentativeDecl();
7110*67e74705SXin Li       Instantiation = PrevEnum;
7111*67e74705SXin Li       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7112*67e74705SXin Li       MSInfo = PrevEnum->getMemberSpecializationInfo();
7113*67e74705SXin Li     }
7114*67e74705SXin Li   }
7115*67e74705SXin Li 
7116*67e74705SXin Li   if (!Instantiation) {
7117*67e74705SXin Li     // There is no previous declaration that matches. Since member
7118*67e74705SXin Li     // specializations are always out-of-line, the caller will complain about
7119*67e74705SXin Li     // this mismatch later.
7120*67e74705SXin Li     return false;
7121*67e74705SXin Li   }
7122*67e74705SXin Li 
7123*67e74705SXin Li   // If this is a friend, just bail out here before we start turning
7124*67e74705SXin Li   // things into explicit specializations.
7125*67e74705SXin Li   if (Member->getFriendObjectKind() != Decl::FOK_None) {
7126*67e74705SXin Li     // Preserve instantiation information.
7127*67e74705SXin Li     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7128*67e74705SXin Li       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7129*67e74705SXin Li                                       cast<CXXMethodDecl>(InstantiatedFrom),
7130*67e74705SXin Li         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7131*67e74705SXin Li     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7132*67e74705SXin Li       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7133*67e74705SXin Li                                       cast<CXXRecordDecl>(InstantiatedFrom),
7134*67e74705SXin Li         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7135*67e74705SXin Li     }
7136*67e74705SXin Li 
7137*67e74705SXin Li     Previous.clear();
7138*67e74705SXin Li     Previous.addDecl(FoundInstantiation);
7139*67e74705SXin Li     return false;
7140*67e74705SXin Li   }
7141*67e74705SXin Li 
7142*67e74705SXin Li   // Make sure that this is a specialization of a member.
7143*67e74705SXin Li   if (!InstantiatedFrom) {
7144*67e74705SXin Li     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7145*67e74705SXin Li       << Member;
7146*67e74705SXin Li     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7147*67e74705SXin Li     return true;
7148*67e74705SXin Li   }
7149*67e74705SXin Li 
7150*67e74705SXin Li   // C++ [temp.expl.spec]p6:
7151*67e74705SXin Li   //   If a template, a member template or the member of a class template is
7152*67e74705SXin Li   //   explicitly specialized then that specialization shall be declared
7153*67e74705SXin Li   //   before the first use of that specialization that would cause an implicit
7154*67e74705SXin Li   //   instantiation to take place, in every translation unit in which such a
7155*67e74705SXin Li   //   use occurs; no diagnostic is required.
7156*67e74705SXin Li   assert(MSInfo && "Member specialization info missing?");
7157*67e74705SXin Li 
7158*67e74705SXin Li   bool HasNoEffect = false;
7159*67e74705SXin Li   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7160*67e74705SXin Li                                              TSK_ExplicitSpecialization,
7161*67e74705SXin Li                                              Instantiation,
7162*67e74705SXin Li                                      MSInfo->getTemplateSpecializationKind(),
7163*67e74705SXin Li                                            MSInfo->getPointOfInstantiation(),
7164*67e74705SXin Li                                              HasNoEffect))
7165*67e74705SXin Li     return true;
7166*67e74705SXin Li 
7167*67e74705SXin Li   // Check the scope of this explicit specialization.
7168*67e74705SXin Li   if (CheckTemplateSpecializationScope(*this,
7169*67e74705SXin Li                                        InstantiatedFrom,
7170*67e74705SXin Li                                        Instantiation, Member->getLocation(),
7171*67e74705SXin Li                                        false))
7172*67e74705SXin Li     return true;
7173*67e74705SXin Li 
7174*67e74705SXin Li   // Note that this is an explicit instantiation of a member.
7175*67e74705SXin Li   // the original declaration to note that it is an explicit specialization
7176*67e74705SXin Li   // (if it was previously an implicit instantiation). This latter step
7177*67e74705SXin Li   // makes bookkeeping easier.
7178*67e74705SXin Li   if (isa<FunctionDecl>(Member)) {
7179*67e74705SXin Li     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7180*67e74705SXin Li     if (InstantiationFunction->getTemplateSpecializationKind() ==
7181*67e74705SXin Li           TSK_ImplicitInstantiation) {
7182*67e74705SXin Li       InstantiationFunction->setTemplateSpecializationKind(
7183*67e74705SXin Li                                                   TSK_ExplicitSpecialization);
7184*67e74705SXin Li       InstantiationFunction->setLocation(Member->getLocation());
7185*67e74705SXin Li       // Explicit specializations of member functions of class templates do not
7186*67e74705SXin Li       // inherit '=delete' from the member function they are specializing.
7187*67e74705SXin Li       if (InstantiationFunction->isDeleted()) {
7188*67e74705SXin Li         assert(InstantiationFunction->getCanonicalDecl() ==
7189*67e74705SXin Li                InstantiationFunction);
7190*67e74705SXin Li         InstantiationFunction->setDeletedAsWritten(false);
7191*67e74705SXin Li       }
7192*67e74705SXin Li     }
7193*67e74705SXin Li 
7194*67e74705SXin Li     cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7195*67e74705SXin Li                                         cast<CXXMethodDecl>(InstantiatedFrom),
7196*67e74705SXin Li                                                   TSK_ExplicitSpecialization);
7197*67e74705SXin Li     MarkUnusedFileScopedDecl(InstantiationFunction);
7198*67e74705SXin Li   } else if (isa<VarDecl>(Member)) {
7199*67e74705SXin Li     VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7200*67e74705SXin Li     if (InstantiationVar->getTemplateSpecializationKind() ==
7201*67e74705SXin Li           TSK_ImplicitInstantiation) {
7202*67e74705SXin Li       InstantiationVar->setTemplateSpecializationKind(
7203*67e74705SXin Li                                                   TSK_ExplicitSpecialization);
7204*67e74705SXin Li       InstantiationVar->setLocation(Member->getLocation());
7205*67e74705SXin Li     }
7206*67e74705SXin Li 
7207*67e74705SXin Li     cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7208*67e74705SXin Li         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7209*67e74705SXin Li     MarkUnusedFileScopedDecl(InstantiationVar);
7210*67e74705SXin Li   } else if (isa<CXXRecordDecl>(Member)) {
7211*67e74705SXin Li     CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7212*67e74705SXin Li     if (InstantiationClass->getTemplateSpecializationKind() ==
7213*67e74705SXin Li           TSK_ImplicitInstantiation) {
7214*67e74705SXin Li       InstantiationClass->setTemplateSpecializationKind(
7215*67e74705SXin Li                                                    TSK_ExplicitSpecialization);
7216*67e74705SXin Li       InstantiationClass->setLocation(Member->getLocation());
7217*67e74705SXin Li     }
7218*67e74705SXin Li 
7219*67e74705SXin Li     cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7220*67e74705SXin Li                                         cast<CXXRecordDecl>(InstantiatedFrom),
7221*67e74705SXin Li                                                    TSK_ExplicitSpecialization);
7222*67e74705SXin Li   } else {
7223*67e74705SXin Li     assert(isa<EnumDecl>(Member) && "Only member enums remain");
7224*67e74705SXin Li     EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7225*67e74705SXin Li     if (InstantiationEnum->getTemplateSpecializationKind() ==
7226*67e74705SXin Li           TSK_ImplicitInstantiation) {
7227*67e74705SXin Li       InstantiationEnum->setTemplateSpecializationKind(
7228*67e74705SXin Li                                                    TSK_ExplicitSpecialization);
7229*67e74705SXin Li       InstantiationEnum->setLocation(Member->getLocation());
7230*67e74705SXin Li     }
7231*67e74705SXin Li 
7232*67e74705SXin Li     cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7233*67e74705SXin Li         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7234*67e74705SXin Li   }
7235*67e74705SXin Li 
7236*67e74705SXin Li   // Save the caller the trouble of having to figure out which declaration
7237*67e74705SXin Li   // this specialization matches.
7238*67e74705SXin Li   Previous.clear();
7239*67e74705SXin Li   Previous.addDecl(FoundInstantiation);
7240*67e74705SXin Li   return false;
7241*67e74705SXin Li }
7242*67e74705SXin Li 
7243*67e74705SXin Li /// \brief Check the scope of an explicit instantiation.
7244*67e74705SXin Li ///
7245*67e74705SXin Li /// \returns true if a serious error occurs, false otherwise.
CheckExplicitInstantiationScope(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName)7246*67e74705SXin Li static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7247*67e74705SXin Li                                             SourceLocation InstLoc,
7248*67e74705SXin Li                                             bool WasQualifiedName) {
7249*67e74705SXin Li   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7250*67e74705SXin Li   DeclContext *CurContext = S.CurContext->getRedeclContext();
7251*67e74705SXin Li 
7252*67e74705SXin Li   if (CurContext->isRecord()) {
7253*67e74705SXin Li     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7254*67e74705SXin Li       << D;
7255*67e74705SXin Li     return true;
7256*67e74705SXin Li   }
7257*67e74705SXin Li 
7258*67e74705SXin Li   // C++11 [temp.explicit]p3:
7259*67e74705SXin Li   //   An explicit instantiation shall appear in an enclosing namespace of its
7260*67e74705SXin Li   //   template. If the name declared in the explicit instantiation is an
7261*67e74705SXin Li   //   unqualified name, the explicit instantiation shall appear in the
7262*67e74705SXin Li   //   namespace where its template is declared or, if that namespace is inline
7263*67e74705SXin Li   //   (7.3.1), any namespace from its enclosing namespace set.
7264*67e74705SXin Li   //
7265*67e74705SXin Li   // This is DR275, which we do not retroactively apply to C++98/03.
7266*67e74705SXin Li   if (WasQualifiedName) {
7267*67e74705SXin Li     if (CurContext->Encloses(OrigContext))
7268*67e74705SXin Li       return false;
7269*67e74705SXin Li   } else {
7270*67e74705SXin Li     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7271*67e74705SXin Li       return false;
7272*67e74705SXin Li   }
7273*67e74705SXin Li 
7274*67e74705SXin Li   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7275*67e74705SXin Li     if (WasQualifiedName)
7276*67e74705SXin Li       S.Diag(InstLoc,
7277*67e74705SXin Li              S.getLangOpts().CPlusPlus11?
7278*67e74705SXin Li                diag::err_explicit_instantiation_out_of_scope :
7279*67e74705SXin Li                diag::warn_explicit_instantiation_out_of_scope_0x)
7280*67e74705SXin Li         << D << NS;
7281*67e74705SXin Li     else
7282*67e74705SXin Li       S.Diag(InstLoc,
7283*67e74705SXin Li              S.getLangOpts().CPlusPlus11?
7284*67e74705SXin Li                diag::err_explicit_instantiation_unqualified_wrong_namespace :
7285*67e74705SXin Li                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7286*67e74705SXin Li         << D << NS;
7287*67e74705SXin Li   } else
7288*67e74705SXin Li     S.Diag(InstLoc,
7289*67e74705SXin Li            S.getLangOpts().CPlusPlus11?
7290*67e74705SXin Li              diag::err_explicit_instantiation_must_be_global :
7291*67e74705SXin Li              diag::warn_explicit_instantiation_must_be_global_0x)
7292*67e74705SXin Li       << D;
7293*67e74705SXin Li   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7294*67e74705SXin Li   return false;
7295*67e74705SXin Li }
7296*67e74705SXin Li 
7297*67e74705SXin Li /// \brief Determine whether the given scope specifier has a template-id in it.
ScopeSpecifierHasTemplateId(const CXXScopeSpec & SS)7298*67e74705SXin Li static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7299*67e74705SXin Li   if (!SS.isSet())
7300*67e74705SXin Li     return false;
7301*67e74705SXin Li 
7302*67e74705SXin Li   // C++11 [temp.explicit]p3:
7303*67e74705SXin Li   //   If the explicit instantiation is for a member function, a member class
7304*67e74705SXin Li   //   or a static data member of a class template specialization, the name of
7305*67e74705SXin Li   //   the class template specialization in the qualified-id for the member
7306*67e74705SXin Li   //   name shall be a simple-template-id.
7307*67e74705SXin Li   //
7308*67e74705SXin Li   // C++98 has the same restriction, just worded differently.
7309*67e74705SXin Li   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7310*67e74705SXin Li        NNS = NNS->getPrefix())
7311*67e74705SXin Li     if (const Type *T = NNS->getAsType())
7312*67e74705SXin Li       if (isa<TemplateSpecializationType>(T))
7313*67e74705SXin Li         return true;
7314*67e74705SXin Li 
7315*67e74705SXin Li   return false;
7316*67e74705SXin Li }
7317*67e74705SXin Li 
7318*67e74705SXin Li // Explicit instantiation of a class template specialization
7319*67e74705SXin Li DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,const CXXScopeSpec & SS,TemplateTy TemplateD,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,AttributeList * Attr)7320*67e74705SXin Li Sema::ActOnExplicitInstantiation(Scope *S,
7321*67e74705SXin Li                                  SourceLocation ExternLoc,
7322*67e74705SXin Li                                  SourceLocation TemplateLoc,
7323*67e74705SXin Li                                  unsigned TagSpec,
7324*67e74705SXin Li                                  SourceLocation KWLoc,
7325*67e74705SXin Li                                  const CXXScopeSpec &SS,
7326*67e74705SXin Li                                  TemplateTy TemplateD,
7327*67e74705SXin Li                                  SourceLocation TemplateNameLoc,
7328*67e74705SXin Li                                  SourceLocation LAngleLoc,
7329*67e74705SXin Li                                  ASTTemplateArgsPtr TemplateArgsIn,
7330*67e74705SXin Li                                  SourceLocation RAngleLoc,
7331*67e74705SXin Li                                  AttributeList *Attr) {
7332*67e74705SXin Li   // Find the class template we're specializing
7333*67e74705SXin Li   TemplateName Name = TemplateD.get();
7334*67e74705SXin Li   TemplateDecl *TD = Name.getAsTemplateDecl();
7335*67e74705SXin Li   // Check that the specialization uses the same tag kind as the
7336*67e74705SXin Li   // original template.
7337*67e74705SXin Li   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7338*67e74705SXin Li   assert(Kind != TTK_Enum &&
7339*67e74705SXin Li          "Invalid enum tag in class template explicit instantiation!");
7340*67e74705SXin Li 
7341*67e74705SXin Li   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7342*67e74705SXin Li 
7343*67e74705SXin Li   if (!ClassTemplate) {
7344*67e74705SXin Li     unsigned ErrorKind = 0;
7345*67e74705SXin Li     if (isa<TypeAliasTemplateDecl>(TD)) {
7346*67e74705SXin Li       ErrorKind = 4;
7347*67e74705SXin Li     } else if (isa<TemplateTemplateParmDecl>(TD)) {
7348*67e74705SXin Li       ErrorKind = 5;
7349*67e74705SXin Li     }
7350*67e74705SXin Li 
7351*67e74705SXin Li     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7352*67e74705SXin Li     Diag(TD->getLocation(), diag::note_previous_use);
7353*67e74705SXin Li     return true;
7354*67e74705SXin Li   }
7355*67e74705SXin Li 
7356*67e74705SXin Li   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7357*67e74705SXin Li                                     Kind, /*isDefinition*/false, KWLoc,
7358*67e74705SXin Li                                     ClassTemplate->getIdentifier())) {
7359*67e74705SXin Li     Diag(KWLoc, diag::err_use_with_wrong_tag)
7360*67e74705SXin Li       << ClassTemplate
7361*67e74705SXin Li       << FixItHint::CreateReplacement(KWLoc,
7362*67e74705SXin Li                             ClassTemplate->getTemplatedDecl()->getKindName());
7363*67e74705SXin Li     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7364*67e74705SXin Li          diag::note_previous_use);
7365*67e74705SXin Li     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7366*67e74705SXin Li   }
7367*67e74705SXin Li 
7368*67e74705SXin Li   // C++0x [temp.explicit]p2:
7369*67e74705SXin Li   //   There are two forms of explicit instantiation: an explicit instantiation
7370*67e74705SXin Li   //   definition and an explicit instantiation declaration. An explicit
7371*67e74705SXin Li   //   instantiation declaration begins with the extern keyword. [...]
7372*67e74705SXin Li   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7373*67e74705SXin Li                                        ? TSK_ExplicitInstantiationDefinition
7374*67e74705SXin Li                                        : TSK_ExplicitInstantiationDeclaration;
7375*67e74705SXin Li 
7376*67e74705SXin Li   if (TSK == TSK_ExplicitInstantiationDeclaration) {
7377*67e74705SXin Li     // Check for dllexport class template instantiation declarations.
7378*67e74705SXin Li     for (AttributeList *A = Attr; A; A = A->getNext()) {
7379*67e74705SXin Li       if (A->getKind() == AttributeList::AT_DLLExport) {
7380*67e74705SXin Li         Diag(ExternLoc,
7381*67e74705SXin Li              diag::warn_attribute_dllexport_explicit_instantiation_decl);
7382*67e74705SXin Li         Diag(A->getLoc(), diag::note_attribute);
7383*67e74705SXin Li         break;
7384*67e74705SXin Li       }
7385*67e74705SXin Li     }
7386*67e74705SXin Li 
7387*67e74705SXin Li     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7388*67e74705SXin Li       Diag(ExternLoc,
7389*67e74705SXin Li            diag::warn_attribute_dllexport_explicit_instantiation_decl);
7390*67e74705SXin Li       Diag(A->getLocation(), diag::note_attribute);
7391*67e74705SXin Li     }
7392*67e74705SXin Li   }
7393*67e74705SXin Li 
7394*67e74705SXin Li   // In MSVC mode, dllimported explicit instantiation definitions are treated as
7395*67e74705SXin Li   // instantiation declarations for most purposes.
7396*67e74705SXin Li   bool DLLImportExplicitInstantiationDef = false;
7397*67e74705SXin Li   if (TSK == TSK_ExplicitInstantiationDefinition &&
7398*67e74705SXin Li       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7399*67e74705SXin Li     // Check for dllimport class template instantiation definitions.
7400*67e74705SXin Li     bool DLLImport =
7401*67e74705SXin Li         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7402*67e74705SXin Li     for (AttributeList *A = Attr; A; A = A->getNext()) {
7403*67e74705SXin Li       if (A->getKind() == AttributeList::AT_DLLImport)
7404*67e74705SXin Li         DLLImport = true;
7405*67e74705SXin Li       if (A->getKind() == AttributeList::AT_DLLExport) {
7406*67e74705SXin Li         // dllexport trumps dllimport here.
7407*67e74705SXin Li         DLLImport = false;
7408*67e74705SXin Li         break;
7409*67e74705SXin Li       }
7410*67e74705SXin Li     }
7411*67e74705SXin Li     if (DLLImport) {
7412*67e74705SXin Li       TSK = TSK_ExplicitInstantiationDeclaration;
7413*67e74705SXin Li       DLLImportExplicitInstantiationDef = true;
7414*67e74705SXin Li     }
7415*67e74705SXin Li   }
7416*67e74705SXin Li 
7417*67e74705SXin Li   // Translate the parser's template argument list in our AST format.
7418*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7419*67e74705SXin Li   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7420*67e74705SXin Li 
7421*67e74705SXin Li   // Check that the template argument list is well-formed for this
7422*67e74705SXin Li   // template.
7423*67e74705SXin Li   SmallVector<TemplateArgument, 4> Converted;
7424*67e74705SXin Li   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7425*67e74705SXin Li                                 TemplateArgs, false, Converted))
7426*67e74705SXin Li     return true;
7427*67e74705SXin Li 
7428*67e74705SXin Li   // Find the class template specialization declaration that
7429*67e74705SXin Li   // corresponds to these arguments.
7430*67e74705SXin Li   void *InsertPos = nullptr;
7431*67e74705SXin Li   ClassTemplateSpecializationDecl *PrevDecl
7432*67e74705SXin Li     = ClassTemplate->findSpecialization(Converted, InsertPos);
7433*67e74705SXin Li 
7434*67e74705SXin Li   TemplateSpecializationKind PrevDecl_TSK
7435*67e74705SXin Li     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7436*67e74705SXin Li 
7437*67e74705SXin Li   // C++0x [temp.explicit]p2:
7438*67e74705SXin Li   //   [...] An explicit instantiation shall appear in an enclosing
7439*67e74705SXin Li   //   namespace of its template. [...]
7440*67e74705SXin Li   //
7441*67e74705SXin Li   // This is C++ DR 275.
7442*67e74705SXin Li   if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7443*67e74705SXin Li                                       SS.isSet()))
7444*67e74705SXin Li     return true;
7445*67e74705SXin Li 
7446*67e74705SXin Li   ClassTemplateSpecializationDecl *Specialization = nullptr;
7447*67e74705SXin Li 
7448*67e74705SXin Li   bool HasNoEffect = false;
7449*67e74705SXin Li   if (PrevDecl) {
7450*67e74705SXin Li     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7451*67e74705SXin Li                                                PrevDecl, PrevDecl_TSK,
7452*67e74705SXin Li                                             PrevDecl->getPointOfInstantiation(),
7453*67e74705SXin Li                                                HasNoEffect))
7454*67e74705SXin Li       return PrevDecl;
7455*67e74705SXin Li 
7456*67e74705SXin Li     // Even though HasNoEffect == true means that this explicit instantiation
7457*67e74705SXin Li     // has no effect on semantics, we go on to put its syntax in the AST.
7458*67e74705SXin Li 
7459*67e74705SXin Li     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7460*67e74705SXin Li         PrevDecl_TSK == TSK_Undeclared) {
7461*67e74705SXin Li       // Since the only prior class template specialization with these
7462*67e74705SXin Li       // arguments was referenced but not declared, reuse that
7463*67e74705SXin Li       // declaration node as our own, updating the source location
7464*67e74705SXin Li       // for the template name to reflect our new declaration.
7465*67e74705SXin Li       // (Other source locations will be updated later.)
7466*67e74705SXin Li       Specialization = PrevDecl;
7467*67e74705SXin Li       Specialization->setLocation(TemplateNameLoc);
7468*67e74705SXin Li       PrevDecl = nullptr;
7469*67e74705SXin Li     }
7470*67e74705SXin Li 
7471*67e74705SXin Li     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7472*67e74705SXin Li         DLLImportExplicitInstantiationDef) {
7473*67e74705SXin Li       // The new specialization might add a dllimport attribute.
7474*67e74705SXin Li       HasNoEffect = false;
7475*67e74705SXin Li     }
7476*67e74705SXin Li   }
7477*67e74705SXin Li 
7478*67e74705SXin Li   if (!Specialization) {
7479*67e74705SXin Li     // Create a new class template specialization declaration node for
7480*67e74705SXin Li     // this explicit specialization.
7481*67e74705SXin Li     Specialization
7482*67e74705SXin Li       = ClassTemplateSpecializationDecl::Create(Context, Kind,
7483*67e74705SXin Li                                              ClassTemplate->getDeclContext(),
7484*67e74705SXin Li                                                 KWLoc, TemplateNameLoc,
7485*67e74705SXin Li                                                 ClassTemplate,
7486*67e74705SXin Li                                                 Converted,
7487*67e74705SXin Li                                                 PrevDecl);
7488*67e74705SXin Li     SetNestedNameSpecifier(Specialization, SS);
7489*67e74705SXin Li 
7490*67e74705SXin Li     if (!HasNoEffect && !PrevDecl) {
7491*67e74705SXin Li       // Insert the new specialization.
7492*67e74705SXin Li       ClassTemplate->AddSpecialization(Specialization, InsertPos);
7493*67e74705SXin Li     }
7494*67e74705SXin Li   }
7495*67e74705SXin Li 
7496*67e74705SXin Li   // Build the fully-sugared type for this explicit instantiation as
7497*67e74705SXin Li   // the user wrote in the explicit instantiation itself. This means
7498*67e74705SXin Li   // that we'll pretty-print the type retrieved from the
7499*67e74705SXin Li   // specialization's declaration the way that the user actually wrote
7500*67e74705SXin Li   // the explicit instantiation, rather than formatting the name based
7501*67e74705SXin Li   // on the "canonical" representation used to store the template
7502*67e74705SXin Li   // arguments in the specialization.
7503*67e74705SXin Li   TypeSourceInfo *WrittenTy
7504*67e74705SXin Li     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7505*67e74705SXin Li                                                 TemplateArgs,
7506*67e74705SXin Li                                   Context.getTypeDeclType(Specialization));
7507*67e74705SXin Li   Specialization->setTypeAsWritten(WrittenTy);
7508*67e74705SXin Li 
7509*67e74705SXin Li   // Set source locations for keywords.
7510*67e74705SXin Li   Specialization->setExternLoc(ExternLoc);
7511*67e74705SXin Li   Specialization->setTemplateKeywordLoc(TemplateLoc);
7512*67e74705SXin Li   Specialization->setRBraceLoc(SourceLocation());
7513*67e74705SXin Li 
7514*67e74705SXin Li   if (Attr)
7515*67e74705SXin Li     ProcessDeclAttributeList(S, Specialization, Attr);
7516*67e74705SXin Li 
7517*67e74705SXin Li   // Add the explicit instantiation into its lexical context. However,
7518*67e74705SXin Li   // since explicit instantiations are never found by name lookup, we
7519*67e74705SXin Li   // just put it into the declaration context directly.
7520*67e74705SXin Li   Specialization->setLexicalDeclContext(CurContext);
7521*67e74705SXin Li   CurContext->addDecl(Specialization);
7522*67e74705SXin Li 
7523*67e74705SXin Li   // Syntax is now OK, so return if it has no other effect on semantics.
7524*67e74705SXin Li   if (HasNoEffect) {
7525*67e74705SXin Li     // Set the template specialization kind.
7526*67e74705SXin Li     Specialization->setTemplateSpecializationKind(TSK);
7527*67e74705SXin Li     return Specialization;
7528*67e74705SXin Li   }
7529*67e74705SXin Li 
7530*67e74705SXin Li   // C++ [temp.explicit]p3:
7531*67e74705SXin Li   //   A definition of a class template or class member template
7532*67e74705SXin Li   //   shall be in scope at the point of the explicit instantiation of
7533*67e74705SXin Li   //   the class template or class member template.
7534*67e74705SXin Li   //
7535*67e74705SXin Li   // This check comes when we actually try to perform the
7536*67e74705SXin Li   // instantiation.
7537*67e74705SXin Li   ClassTemplateSpecializationDecl *Def
7538*67e74705SXin Li     = cast_or_null<ClassTemplateSpecializationDecl>(
7539*67e74705SXin Li                                               Specialization->getDefinition());
7540*67e74705SXin Li   if (!Def)
7541*67e74705SXin Li     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7542*67e74705SXin Li   else if (TSK == TSK_ExplicitInstantiationDefinition) {
7543*67e74705SXin Li     MarkVTableUsed(TemplateNameLoc, Specialization, true);
7544*67e74705SXin Li     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7545*67e74705SXin Li   }
7546*67e74705SXin Li 
7547*67e74705SXin Li   // Instantiate the members of this class template specialization.
7548*67e74705SXin Li   Def = cast_or_null<ClassTemplateSpecializationDecl>(
7549*67e74705SXin Li                                        Specialization->getDefinition());
7550*67e74705SXin Li   if (Def) {
7551*67e74705SXin Li     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7552*67e74705SXin Li     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7553*67e74705SXin Li     // TSK_ExplicitInstantiationDefinition
7554*67e74705SXin Li     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7555*67e74705SXin Li         (TSK == TSK_ExplicitInstantiationDefinition ||
7556*67e74705SXin Li          DLLImportExplicitInstantiationDef)) {
7557*67e74705SXin Li       // FIXME: Need to notify the ASTMutationListener that we did this.
7558*67e74705SXin Li       Def->setTemplateSpecializationKind(TSK);
7559*67e74705SXin Li 
7560*67e74705SXin Li       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7561*67e74705SXin Li           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7562*67e74705SXin Li         // In the MS ABI, an explicit instantiation definition can add a dll
7563*67e74705SXin Li         // attribute to a template with a previous instantiation declaration.
7564*67e74705SXin Li         // MinGW doesn't allow this.
7565*67e74705SXin Li         auto *A = cast<InheritableAttr>(
7566*67e74705SXin Li             getDLLAttr(Specialization)->clone(getASTContext()));
7567*67e74705SXin Li         A->setInherited(true);
7568*67e74705SXin Li         Def->addAttr(A);
7569*67e74705SXin Li 
7570*67e74705SXin Li         // We reject explicit instantiations in class scope, so there should
7571*67e74705SXin Li         // never be any delayed exported classes to worry about.
7572*67e74705SXin Li         assert(DelayedDllExportClasses.empty() &&
7573*67e74705SXin Li                "delayed exports present at explicit instantiation");
7574*67e74705SXin Li         checkClassLevelDLLAttribute(Def);
7575*67e74705SXin Li         referenceDLLExportedClassMethods();
7576*67e74705SXin Li 
7577*67e74705SXin Li         // Propagate attribute to base class templates.
7578*67e74705SXin Li         for (auto &B : Def->bases()) {
7579*67e74705SXin Li           if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7580*67e74705SXin Li                   B.getType()->getAsCXXRecordDecl()))
7581*67e74705SXin Li             propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7582*67e74705SXin Li         }
7583*67e74705SXin Li       }
7584*67e74705SXin Li     }
7585*67e74705SXin Li 
7586*67e74705SXin Li     // Set the template specialization kind. Make sure it is set before
7587*67e74705SXin Li     // instantiating the members which will trigger ASTConsumer callbacks.
7588*67e74705SXin Li     Specialization->setTemplateSpecializationKind(TSK);
7589*67e74705SXin Li     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7590*67e74705SXin Li   } else {
7591*67e74705SXin Li 
7592*67e74705SXin Li     // Set the template specialization kind.
7593*67e74705SXin Li     Specialization->setTemplateSpecializationKind(TSK);
7594*67e74705SXin Li   }
7595*67e74705SXin Li 
7596*67e74705SXin Li   return Specialization;
7597*67e74705SXin Li }
7598*67e74705SXin Li 
7599*67e74705SXin Li // Explicit instantiation of a member class of a class template.
7600*67e74705SXin Li DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr)7601*67e74705SXin Li Sema::ActOnExplicitInstantiation(Scope *S,
7602*67e74705SXin Li                                  SourceLocation ExternLoc,
7603*67e74705SXin Li                                  SourceLocation TemplateLoc,
7604*67e74705SXin Li                                  unsigned TagSpec,
7605*67e74705SXin Li                                  SourceLocation KWLoc,
7606*67e74705SXin Li                                  CXXScopeSpec &SS,
7607*67e74705SXin Li                                  IdentifierInfo *Name,
7608*67e74705SXin Li                                  SourceLocation NameLoc,
7609*67e74705SXin Li                                  AttributeList *Attr) {
7610*67e74705SXin Li 
7611*67e74705SXin Li   bool Owned = false;
7612*67e74705SXin Li   bool IsDependent = false;
7613*67e74705SXin Li   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7614*67e74705SXin Li                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
7615*67e74705SXin Li                         /*ModulePrivateLoc=*/SourceLocation(),
7616*67e74705SXin Li                         MultiTemplateParamsArg(), Owned, IsDependent,
7617*67e74705SXin Li                         SourceLocation(), false, TypeResult(),
7618*67e74705SXin Li                         /*IsTypeSpecifier*/false);
7619*67e74705SXin Li   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7620*67e74705SXin Li 
7621*67e74705SXin Li   if (!TagD)
7622*67e74705SXin Li     return true;
7623*67e74705SXin Li 
7624*67e74705SXin Li   TagDecl *Tag = cast<TagDecl>(TagD);
7625*67e74705SXin Li   assert(!Tag->isEnum() && "shouldn't see enumerations here");
7626*67e74705SXin Li 
7627*67e74705SXin Li   if (Tag->isInvalidDecl())
7628*67e74705SXin Li     return true;
7629*67e74705SXin Li 
7630*67e74705SXin Li   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7631*67e74705SXin Li   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7632*67e74705SXin Li   if (!Pattern) {
7633*67e74705SXin Li     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7634*67e74705SXin Li       << Context.getTypeDeclType(Record);
7635*67e74705SXin Li     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7636*67e74705SXin Li     return true;
7637*67e74705SXin Li   }
7638*67e74705SXin Li 
7639*67e74705SXin Li   // C++0x [temp.explicit]p2:
7640*67e74705SXin Li   //   If the explicit instantiation is for a class or member class, the
7641*67e74705SXin Li   //   elaborated-type-specifier in the declaration shall include a
7642*67e74705SXin Li   //   simple-template-id.
7643*67e74705SXin Li   //
7644*67e74705SXin Li   // C++98 has the same restriction, just worded differently.
7645*67e74705SXin Li   if (!ScopeSpecifierHasTemplateId(SS))
7646*67e74705SXin Li     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7647*67e74705SXin Li       << Record << SS.getRange();
7648*67e74705SXin Li 
7649*67e74705SXin Li   // C++0x [temp.explicit]p2:
7650*67e74705SXin Li   //   There are two forms of explicit instantiation: an explicit instantiation
7651*67e74705SXin Li   //   definition and an explicit instantiation declaration. An explicit
7652*67e74705SXin Li   //   instantiation declaration begins with the extern keyword. [...]
7653*67e74705SXin Li   TemplateSpecializationKind TSK
7654*67e74705SXin Li     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7655*67e74705SXin Li                            : TSK_ExplicitInstantiationDeclaration;
7656*67e74705SXin Li 
7657*67e74705SXin Li   // C++0x [temp.explicit]p2:
7658*67e74705SXin Li   //   [...] An explicit instantiation shall appear in an enclosing
7659*67e74705SXin Li   //   namespace of its template. [...]
7660*67e74705SXin Li   //
7661*67e74705SXin Li   // This is C++ DR 275.
7662*67e74705SXin Li   CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7663*67e74705SXin Li 
7664*67e74705SXin Li   // Verify that it is okay to explicitly instantiate here.
7665*67e74705SXin Li   CXXRecordDecl *PrevDecl
7666*67e74705SXin Li     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7667*67e74705SXin Li   if (!PrevDecl && Record->getDefinition())
7668*67e74705SXin Li     PrevDecl = Record;
7669*67e74705SXin Li   if (PrevDecl) {
7670*67e74705SXin Li     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7671*67e74705SXin Li     bool HasNoEffect = false;
7672*67e74705SXin Li     assert(MSInfo && "No member specialization information?");
7673*67e74705SXin Li     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7674*67e74705SXin Li                                                PrevDecl,
7675*67e74705SXin Li                                         MSInfo->getTemplateSpecializationKind(),
7676*67e74705SXin Li                                              MSInfo->getPointOfInstantiation(),
7677*67e74705SXin Li                                                HasNoEffect))
7678*67e74705SXin Li       return true;
7679*67e74705SXin Li     if (HasNoEffect)
7680*67e74705SXin Li       return TagD;
7681*67e74705SXin Li   }
7682*67e74705SXin Li 
7683*67e74705SXin Li   CXXRecordDecl *RecordDef
7684*67e74705SXin Li     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7685*67e74705SXin Li   if (!RecordDef) {
7686*67e74705SXin Li     // C++ [temp.explicit]p3:
7687*67e74705SXin Li     //   A definition of a member class of a class template shall be in scope
7688*67e74705SXin Li     //   at the point of an explicit instantiation of the member class.
7689*67e74705SXin Li     CXXRecordDecl *Def
7690*67e74705SXin Li       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7691*67e74705SXin Li     if (!Def) {
7692*67e74705SXin Li       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7693*67e74705SXin Li         << 0 << Record->getDeclName() << Record->getDeclContext();
7694*67e74705SXin Li       Diag(Pattern->getLocation(), diag::note_forward_declaration)
7695*67e74705SXin Li         << Pattern;
7696*67e74705SXin Li       return true;
7697*67e74705SXin Li     } else {
7698*67e74705SXin Li       if (InstantiateClass(NameLoc, Record, Def,
7699*67e74705SXin Li                            getTemplateInstantiationArgs(Record),
7700*67e74705SXin Li                            TSK))
7701*67e74705SXin Li         return true;
7702*67e74705SXin Li 
7703*67e74705SXin Li       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7704*67e74705SXin Li       if (!RecordDef)
7705*67e74705SXin Li         return true;
7706*67e74705SXin Li     }
7707*67e74705SXin Li   }
7708*67e74705SXin Li 
7709*67e74705SXin Li   // Instantiate all of the members of the class.
7710*67e74705SXin Li   InstantiateClassMembers(NameLoc, RecordDef,
7711*67e74705SXin Li                           getTemplateInstantiationArgs(Record), TSK);
7712*67e74705SXin Li 
7713*67e74705SXin Li   if (TSK == TSK_ExplicitInstantiationDefinition)
7714*67e74705SXin Li     MarkVTableUsed(NameLoc, RecordDef, true);
7715*67e74705SXin Li 
7716*67e74705SXin Li   // FIXME: We don't have any representation for explicit instantiations of
7717*67e74705SXin Li   // member classes. Such a representation is not needed for compilation, but it
7718*67e74705SXin Li   // should be available for clients that want to see all of the declarations in
7719*67e74705SXin Li   // the source code.
7720*67e74705SXin Li   return TagD;
7721*67e74705SXin Li }
7722*67e74705SXin Li 
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,Declarator & D)7723*67e74705SXin Li DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7724*67e74705SXin Li                                             SourceLocation ExternLoc,
7725*67e74705SXin Li                                             SourceLocation TemplateLoc,
7726*67e74705SXin Li                                             Declarator &D) {
7727*67e74705SXin Li   // Explicit instantiations always require a name.
7728*67e74705SXin Li   // TODO: check if/when DNInfo should replace Name.
7729*67e74705SXin Li   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7730*67e74705SXin Li   DeclarationName Name = NameInfo.getName();
7731*67e74705SXin Li   if (!Name) {
7732*67e74705SXin Li     if (!D.isInvalidType())
7733*67e74705SXin Li       Diag(D.getDeclSpec().getLocStart(),
7734*67e74705SXin Li            diag::err_explicit_instantiation_requires_name)
7735*67e74705SXin Li         << D.getDeclSpec().getSourceRange()
7736*67e74705SXin Li         << D.getSourceRange();
7737*67e74705SXin Li 
7738*67e74705SXin Li     return true;
7739*67e74705SXin Li   }
7740*67e74705SXin Li 
7741*67e74705SXin Li   // The scope passed in may not be a decl scope.  Zip up the scope tree until
7742*67e74705SXin Li   // we find one that is.
7743*67e74705SXin Li   while ((S->getFlags() & Scope::DeclScope) == 0 ||
7744*67e74705SXin Li          (S->getFlags() & Scope::TemplateParamScope) != 0)
7745*67e74705SXin Li     S = S->getParent();
7746*67e74705SXin Li 
7747*67e74705SXin Li   // Determine the type of the declaration.
7748*67e74705SXin Li   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7749*67e74705SXin Li   QualType R = T->getType();
7750*67e74705SXin Li   if (R.isNull())
7751*67e74705SXin Li     return true;
7752*67e74705SXin Li 
7753*67e74705SXin Li   // C++ [dcl.stc]p1:
7754*67e74705SXin Li   //   A storage-class-specifier shall not be specified in [...] an explicit
7755*67e74705SXin Li   //   instantiation (14.7.2) directive.
7756*67e74705SXin Li   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7757*67e74705SXin Li     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7758*67e74705SXin Li       << Name;
7759*67e74705SXin Li     return true;
7760*67e74705SXin Li   } else if (D.getDeclSpec().getStorageClassSpec()
7761*67e74705SXin Li                                                 != DeclSpec::SCS_unspecified) {
7762*67e74705SXin Li     // Complain about then remove the storage class specifier.
7763*67e74705SXin Li     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7764*67e74705SXin Li       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7765*67e74705SXin Li 
7766*67e74705SXin Li     D.getMutableDeclSpec().ClearStorageClassSpecs();
7767*67e74705SXin Li   }
7768*67e74705SXin Li 
7769*67e74705SXin Li   // C++0x [temp.explicit]p1:
7770*67e74705SXin Li   //   [...] An explicit instantiation of a function template shall not use the
7771*67e74705SXin Li   //   inline or constexpr specifiers.
7772*67e74705SXin Li   // Presumably, this also applies to member functions of class templates as
7773*67e74705SXin Li   // well.
7774*67e74705SXin Li   if (D.getDeclSpec().isInlineSpecified())
7775*67e74705SXin Li     Diag(D.getDeclSpec().getInlineSpecLoc(),
7776*67e74705SXin Li          getLangOpts().CPlusPlus11 ?
7777*67e74705SXin Li            diag::err_explicit_instantiation_inline :
7778*67e74705SXin Li            diag::warn_explicit_instantiation_inline_0x)
7779*67e74705SXin Li       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7780*67e74705SXin Li   if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7781*67e74705SXin Li     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7782*67e74705SXin Li     // not already specified.
7783*67e74705SXin Li     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7784*67e74705SXin Li          diag::err_explicit_instantiation_constexpr);
7785*67e74705SXin Li 
7786*67e74705SXin Li   // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7787*67e74705SXin Li   // applied only to the definition of a function template or variable template,
7788*67e74705SXin Li   // declared in namespace scope.
7789*67e74705SXin Li   if (D.getDeclSpec().isConceptSpecified()) {
7790*67e74705SXin Li     Diag(D.getDeclSpec().getConceptSpecLoc(),
7791*67e74705SXin Li          diag::err_concept_specified_specialization) << 0;
7792*67e74705SXin Li     return true;
7793*67e74705SXin Li   }
7794*67e74705SXin Li 
7795*67e74705SXin Li   // C++0x [temp.explicit]p2:
7796*67e74705SXin Li   //   There are two forms of explicit instantiation: an explicit instantiation
7797*67e74705SXin Li   //   definition and an explicit instantiation declaration. An explicit
7798*67e74705SXin Li   //   instantiation declaration begins with the extern keyword. [...]
7799*67e74705SXin Li   TemplateSpecializationKind TSK
7800*67e74705SXin Li     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7801*67e74705SXin Li                            : TSK_ExplicitInstantiationDeclaration;
7802*67e74705SXin Li 
7803*67e74705SXin Li   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7804*67e74705SXin Li   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7805*67e74705SXin Li 
7806*67e74705SXin Li   if (!R->isFunctionType()) {
7807*67e74705SXin Li     // C++ [temp.explicit]p1:
7808*67e74705SXin Li     //   A [...] static data member of a class template can be explicitly
7809*67e74705SXin Li     //   instantiated from the member definition associated with its class
7810*67e74705SXin Li     //   template.
7811*67e74705SXin Li     // C++1y [temp.explicit]p1:
7812*67e74705SXin Li     //   A [...] variable [...] template specialization can be explicitly
7813*67e74705SXin Li     //   instantiated from its template.
7814*67e74705SXin Li     if (Previous.isAmbiguous())
7815*67e74705SXin Li       return true;
7816*67e74705SXin Li 
7817*67e74705SXin Li     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7818*67e74705SXin Li     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7819*67e74705SXin Li 
7820*67e74705SXin Li     if (!PrevTemplate) {
7821*67e74705SXin Li       if (!Prev || !Prev->isStaticDataMember()) {
7822*67e74705SXin Li         // We expect to see a data data member here.
7823*67e74705SXin Li         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7824*67e74705SXin Li             << Name;
7825*67e74705SXin Li         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7826*67e74705SXin Li              P != PEnd; ++P)
7827*67e74705SXin Li           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7828*67e74705SXin Li         return true;
7829*67e74705SXin Li       }
7830*67e74705SXin Li 
7831*67e74705SXin Li       if (!Prev->getInstantiatedFromStaticDataMember()) {
7832*67e74705SXin Li         // FIXME: Check for explicit specialization?
7833*67e74705SXin Li         Diag(D.getIdentifierLoc(),
7834*67e74705SXin Li              diag::err_explicit_instantiation_data_member_not_instantiated)
7835*67e74705SXin Li             << Prev;
7836*67e74705SXin Li         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7837*67e74705SXin Li         // FIXME: Can we provide a note showing where this was declared?
7838*67e74705SXin Li         return true;
7839*67e74705SXin Li       }
7840*67e74705SXin Li     } else {
7841*67e74705SXin Li       // Explicitly instantiate a variable template.
7842*67e74705SXin Li 
7843*67e74705SXin Li       // C++1y [dcl.spec.auto]p6:
7844*67e74705SXin Li       //   ... A program that uses auto or decltype(auto) in a context not
7845*67e74705SXin Li       //   explicitly allowed in this section is ill-formed.
7846*67e74705SXin Li       //
7847*67e74705SXin Li       // This includes auto-typed variable template instantiations.
7848*67e74705SXin Li       if (R->isUndeducedType()) {
7849*67e74705SXin Li         Diag(T->getTypeLoc().getLocStart(),
7850*67e74705SXin Li              diag::err_auto_not_allowed_var_inst);
7851*67e74705SXin Li         return true;
7852*67e74705SXin Li       }
7853*67e74705SXin Li 
7854*67e74705SXin Li       if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7855*67e74705SXin Li         // C++1y [temp.explicit]p3:
7856*67e74705SXin Li         //   If the explicit instantiation is for a variable, the unqualified-id
7857*67e74705SXin Li         //   in the declaration shall be a template-id.
7858*67e74705SXin Li         Diag(D.getIdentifierLoc(),
7859*67e74705SXin Li              diag::err_explicit_instantiation_without_template_id)
7860*67e74705SXin Li           << PrevTemplate;
7861*67e74705SXin Li         Diag(PrevTemplate->getLocation(),
7862*67e74705SXin Li              diag::note_explicit_instantiation_here);
7863*67e74705SXin Li         return true;
7864*67e74705SXin Li       }
7865*67e74705SXin Li 
7866*67e74705SXin Li       // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7867*67e74705SXin Li       // explicit instantiation (14.8.2) [...] of a concept definition.
7868*67e74705SXin Li       if (PrevTemplate->isConcept()) {
7869*67e74705SXin Li         Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7870*67e74705SXin Li             << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7871*67e74705SXin Li         Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7872*67e74705SXin Li         return true;
7873*67e74705SXin Li       }
7874*67e74705SXin Li 
7875*67e74705SXin Li       // Translate the parser's template argument list into our AST format.
7876*67e74705SXin Li       TemplateArgumentListInfo TemplateArgs =
7877*67e74705SXin Li           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7878*67e74705SXin Li 
7879*67e74705SXin Li       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7880*67e74705SXin Li                                           D.getIdentifierLoc(), TemplateArgs);
7881*67e74705SXin Li       if (Res.isInvalid())
7882*67e74705SXin Li         return true;
7883*67e74705SXin Li 
7884*67e74705SXin Li       // Ignore access control bits, we don't need them for redeclaration
7885*67e74705SXin Li       // checking.
7886*67e74705SXin Li       Prev = cast<VarDecl>(Res.get());
7887*67e74705SXin Li     }
7888*67e74705SXin Li 
7889*67e74705SXin Li     // C++0x [temp.explicit]p2:
7890*67e74705SXin Li     //   If the explicit instantiation is for a member function, a member class
7891*67e74705SXin Li     //   or a static data member of a class template specialization, the name of
7892*67e74705SXin Li     //   the class template specialization in the qualified-id for the member
7893*67e74705SXin Li     //   name shall be a simple-template-id.
7894*67e74705SXin Li     //
7895*67e74705SXin Li     // C++98 has the same restriction, just worded differently.
7896*67e74705SXin Li     //
7897*67e74705SXin Li     // This does not apply to variable template specializations, where the
7898*67e74705SXin Li     // template-id is in the unqualified-id instead.
7899*67e74705SXin Li     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7900*67e74705SXin Li       Diag(D.getIdentifierLoc(),
7901*67e74705SXin Li            diag::ext_explicit_instantiation_without_qualified_id)
7902*67e74705SXin Li         << Prev << D.getCXXScopeSpec().getRange();
7903*67e74705SXin Li 
7904*67e74705SXin Li     // Check the scope of this explicit instantiation.
7905*67e74705SXin Li     CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7906*67e74705SXin Li 
7907*67e74705SXin Li     // Verify that it is okay to explicitly instantiate here.
7908*67e74705SXin Li     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7909*67e74705SXin Li     SourceLocation POI = Prev->getPointOfInstantiation();
7910*67e74705SXin Li     bool HasNoEffect = false;
7911*67e74705SXin Li     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7912*67e74705SXin Li                                                PrevTSK, POI, HasNoEffect))
7913*67e74705SXin Li       return true;
7914*67e74705SXin Li 
7915*67e74705SXin Li     if (!HasNoEffect) {
7916*67e74705SXin Li       // Instantiate static data member or variable template.
7917*67e74705SXin Li 
7918*67e74705SXin Li       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7919*67e74705SXin Li       if (PrevTemplate) {
7920*67e74705SXin Li         // Merge attributes.
7921*67e74705SXin Li         if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7922*67e74705SXin Li           ProcessDeclAttributeList(S, Prev, Attr);
7923*67e74705SXin Li       }
7924*67e74705SXin Li       if (TSK == TSK_ExplicitInstantiationDefinition)
7925*67e74705SXin Li         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7926*67e74705SXin Li     }
7927*67e74705SXin Li 
7928*67e74705SXin Li     // Check the new variable specialization against the parsed input.
7929*67e74705SXin Li     if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7930*67e74705SXin Li       Diag(T->getTypeLoc().getLocStart(),
7931*67e74705SXin Li            diag::err_invalid_var_template_spec_type)
7932*67e74705SXin Li           << 0 << PrevTemplate << R << Prev->getType();
7933*67e74705SXin Li       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7934*67e74705SXin Li           << 2 << PrevTemplate->getDeclName();
7935*67e74705SXin Li       return true;
7936*67e74705SXin Li     }
7937*67e74705SXin Li 
7938*67e74705SXin Li     // FIXME: Create an ExplicitInstantiation node?
7939*67e74705SXin Li     return (Decl*) nullptr;
7940*67e74705SXin Li   }
7941*67e74705SXin Li 
7942*67e74705SXin Li   // If the declarator is a template-id, translate the parser's template
7943*67e74705SXin Li   // argument list into our AST format.
7944*67e74705SXin Li   bool HasExplicitTemplateArgs = false;
7945*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs;
7946*67e74705SXin Li   if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7947*67e74705SXin Li     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7948*67e74705SXin Li     HasExplicitTemplateArgs = true;
7949*67e74705SXin Li   }
7950*67e74705SXin Li 
7951*67e74705SXin Li   // C++ [temp.explicit]p1:
7952*67e74705SXin Li   //   A [...] function [...] can be explicitly instantiated from its template.
7953*67e74705SXin Li   //   A member function [...] of a class template can be explicitly
7954*67e74705SXin Li   //  instantiated from the member definition associated with its class
7955*67e74705SXin Li   //  template.
7956*67e74705SXin Li   UnresolvedSet<8> Matches;
7957*67e74705SXin Li   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7958*67e74705SXin Li   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7959*67e74705SXin Li        P != PEnd; ++P) {
7960*67e74705SXin Li     NamedDecl *Prev = *P;
7961*67e74705SXin Li     if (!HasExplicitTemplateArgs) {
7962*67e74705SXin Li       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7963*67e74705SXin Li         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7964*67e74705SXin Li         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7965*67e74705SXin Li           Matches.clear();
7966*67e74705SXin Li 
7967*67e74705SXin Li           Matches.addDecl(Method, P.getAccess());
7968*67e74705SXin Li           if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7969*67e74705SXin Li             break;
7970*67e74705SXin Li         }
7971*67e74705SXin Li       }
7972*67e74705SXin Li     }
7973*67e74705SXin Li 
7974*67e74705SXin Li     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7975*67e74705SXin Li     if (!FunTmpl)
7976*67e74705SXin Li       continue;
7977*67e74705SXin Li 
7978*67e74705SXin Li     TemplateDeductionInfo Info(FailedCandidates.getLocation());
7979*67e74705SXin Li     FunctionDecl *Specialization = nullptr;
7980*67e74705SXin Li     if (TemplateDeductionResult TDK
7981*67e74705SXin Li           = DeduceTemplateArguments(FunTmpl,
7982*67e74705SXin Li                                (HasExplicitTemplateArgs ? &TemplateArgs
7983*67e74705SXin Li                                                         : nullptr),
7984*67e74705SXin Li                                     R, Specialization, Info)) {
7985*67e74705SXin Li       // Keep track of almost-matches.
7986*67e74705SXin Li       FailedCandidates.addCandidate()
7987*67e74705SXin Li           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
7988*67e74705SXin Li                MakeDeductionFailureInfo(Context, TDK, Info));
7989*67e74705SXin Li       (void)TDK;
7990*67e74705SXin Li       continue;
7991*67e74705SXin Li     }
7992*67e74705SXin Li 
7993*67e74705SXin Li     Matches.addDecl(Specialization, P.getAccess());
7994*67e74705SXin Li   }
7995*67e74705SXin Li 
7996*67e74705SXin Li   // Find the most specialized function template specialization.
7997*67e74705SXin Li   UnresolvedSetIterator Result = getMostSpecialized(
7998*67e74705SXin Li       Matches.begin(), Matches.end(), FailedCandidates,
7999*67e74705SXin Li       D.getIdentifierLoc(),
8000*67e74705SXin Li       PDiag(diag::err_explicit_instantiation_not_known) << Name,
8001*67e74705SXin Li       PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8002*67e74705SXin Li       PDiag(diag::note_explicit_instantiation_candidate));
8003*67e74705SXin Li 
8004*67e74705SXin Li   if (Result == Matches.end())
8005*67e74705SXin Li     return true;
8006*67e74705SXin Li 
8007*67e74705SXin Li   // Ignore access control bits, we don't need them for redeclaration checking.
8008*67e74705SXin Li   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8009*67e74705SXin Li 
8010*67e74705SXin Li   // C++11 [except.spec]p4
8011*67e74705SXin Li   // In an explicit instantiation an exception-specification may be specified,
8012*67e74705SXin Li   // but is not required.
8013*67e74705SXin Li   // If an exception-specification is specified in an explicit instantiation
8014*67e74705SXin Li   // directive, it shall be compatible with the exception-specifications of
8015*67e74705SXin Li   // other declarations of that function.
8016*67e74705SXin Li   if (auto *FPT = R->getAs<FunctionProtoType>())
8017*67e74705SXin Li     if (FPT->hasExceptionSpec()) {
8018*67e74705SXin Li       unsigned DiagID =
8019*67e74705SXin Li           diag::err_mismatched_exception_spec_explicit_instantiation;
8020*67e74705SXin Li       if (getLangOpts().MicrosoftExt)
8021*67e74705SXin Li         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8022*67e74705SXin Li       bool Result = CheckEquivalentExceptionSpec(
8023*67e74705SXin Li           PDiag(DiagID) << Specialization->getType(),
8024*67e74705SXin Li           PDiag(diag::note_explicit_instantiation_here),
8025*67e74705SXin Li           Specialization->getType()->getAs<FunctionProtoType>(),
8026*67e74705SXin Li           Specialization->getLocation(), FPT, D.getLocStart());
8027*67e74705SXin Li       // In Microsoft mode, mismatching exception specifications just cause a
8028*67e74705SXin Li       // warning.
8029*67e74705SXin Li       if (!getLangOpts().MicrosoftExt && Result)
8030*67e74705SXin Li         return true;
8031*67e74705SXin Li     }
8032*67e74705SXin Li 
8033*67e74705SXin Li   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
8034*67e74705SXin Li     Diag(D.getIdentifierLoc(),
8035*67e74705SXin Li          diag::err_explicit_instantiation_member_function_not_instantiated)
8036*67e74705SXin Li       << Specialization
8037*67e74705SXin Li       << (Specialization->getTemplateSpecializationKind() ==
8038*67e74705SXin Li           TSK_ExplicitSpecialization);
8039*67e74705SXin Li     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8040*67e74705SXin Li     return true;
8041*67e74705SXin Li   }
8042*67e74705SXin Li 
8043*67e74705SXin Li   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
8044*67e74705SXin Li   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8045*67e74705SXin Li     PrevDecl = Specialization;
8046*67e74705SXin Li 
8047*67e74705SXin Li   if (PrevDecl) {
8048*67e74705SXin Li     bool HasNoEffect = false;
8049*67e74705SXin Li     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
8050*67e74705SXin Li                                                PrevDecl,
8051*67e74705SXin Li                                      PrevDecl->getTemplateSpecializationKind(),
8052*67e74705SXin Li                                           PrevDecl->getPointOfInstantiation(),
8053*67e74705SXin Li                                                HasNoEffect))
8054*67e74705SXin Li       return true;
8055*67e74705SXin Li 
8056*67e74705SXin Li     // FIXME: We may still want to build some representation of this
8057*67e74705SXin Li     // explicit specialization.
8058*67e74705SXin Li     if (HasNoEffect)
8059*67e74705SXin Li       return (Decl*) nullptr;
8060*67e74705SXin Li   }
8061*67e74705SXin Li 
8062*67e74705SXin Li   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8063*67e74705SXin Li   AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8064*67e74705SXin Li   if (Attr)
8065*67e74705SXin Li     ProcessDeclAttributeList(S, Specialization, Attr);
8066*67e74705SXin Li 
8067*67e74705SXin Li   if (Specialization->isDefined()) {
8068*67e74705SXin Li     // Let the ASTConsumer know that this function has been explicitly
8069*67e74705SXin Li     // instantiated now, and its linkage might have changed.
8070*67e74705SXin Li     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8071*67e74705SXin Li   } else if (TSK == TSK_ExplicitInstantiationDefinition)
8072*67e74705SXin Li     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
8073*67e74705SXin Li 
8074*67e74705SXin Li   // C++0x [temp.explicit]p2:
8075*67e74705SXin Li   //   If the explicit instantiation is for a member function, a member class
8076*67e74705SXin Li   //   or a static data member of a class template specialization, the name of
8077*67e74705SXin Li   //   the class template specialization in the qualified-id for the member
8078*67e74705SXin Li   //   name shall be a simple-template-id.
8079*67e74705SXin Li   //
8080*67e74705SXin Li   // C++98 has the same restriction, just worded differently.
8081*67e74705SXin Li   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
8082*67e74705SXin Li   if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
8083*67e74705SXin Li       D.getCXXScopeSpec().isSet() &&
8084*67e74705SXin Li       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
8085*67e74705SXin Li     Diag(D.getIdentifierLoc(),
8086*67e74705SXin Li          diag::ext_explicit_instantiation_without_qualified_id)
8087*67e74705SXin Li     << Specialization << D.getCXXScopeSpec().getRange();
8088*67e74705SXin Li 
8089*67e74705SXin Li   // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8090*67e74705SXin Li   // explicit instantiation (14.8.2) [...] of a concept definition.
8091*67e74705SXin Li   if (FunTmpl && FunTmpl->isConcept() &&
8092*67e74705SXin Li       !D.getDeclSpec().isConceptSpecified()) {
8093*67e74705SXin Li     Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8094*67e74705SXin Li         << 0 /*function*/ << 0 /*explicitly instantiated*/;
8095*67e74705SXin Li     Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8096*67e74705SXin Li     return true;
8097*67e74705SXin Li   }
8098*67e74705SXin Li 
8099*67e74705SXin Li   CheckExplicitInstantiationScope(*this,
8100*67e74705SXin Li                    FunTmpl? (NamedDecl *)FunTmpl
8101*67e74705SXin Li                           : Specialization->getInstantiatedFromMemberFunction(),
8102*67e74705SXin Li                                   D.getIdentifierLoc(),
8103*67e74705SXin Li                                   D.getCXXScopeSpec().isSet());
8104*67e74705SXin Li 
8105*67e74705SXin Li   // FIXME: Create some kind of ExplicitInstantiationDecl here.
8106*67e74705SXin Li   return (Decl*) nullptr;
8107*67e74705SXin Li }
8108*67e74705SXin Li 
8109*67e74705SXin Li TypeResult
ActOnDependentTag(Scope * S,unsigned TagSpec,TagUseKind TUK,const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation TagLoc,SourceLocation NameLoc)8110*67e74705SXin Li Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8111*67e74705SXin Li                         const CXXScopeSpec &SS, IdentifierInfo *Name,
8112*67e74705SXin Li                         SourceLocation TagLoc, SourceLocation NameLoc) {
8113*67e74705SXin Li   // This has to hold, because SS is expected to be defined.
8114*67e74705SXin Li   assert(Name && "Expected a name in a dependent tag");
8115*67e74705SXin Li 
8116*67e74705SXin Li   NestedNameSpecifier *NNS = SS.getScopeRep();
8117*67e74705SXin Li   if (!NNS)
8118*67e74705SXin Li     return true;
8119*67e74705SXin Li 
8120*67e74705SXin Li   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8121*67e74705SXin Li 
8122*67e74705SXin Li   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8123*67e74705SXin Li     Diag(NameLoc, diag::err_dependent_tag_decl)
8124*67e74705SXin Li       << (TUK == TUK_Definition) << Kind << SS.getRange();
8125*67e74705SXin Li     return true;
8126*67e74705SXin Li   }
8127*67e74705SXin Li 
8128*67e74705SXin Li   // Create the resulting type.
8129*67e74705SXin Li   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8130*67e74705SXin Li   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8131*67e74705SXin Li 
8132*67e74705SXin Li   // Create type-source location information for this type.
8133*67e74705SXin Li   TypeLocBuilder TLB;
8134*67e74705SXin Li   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
8135*67e74705SXin Li   TL.setElaboratedKeywordLoc(TagLoc);
8136*67e74705SXin Li   TL.setQualifierLoc(SS.getWithLocInContext(Context));
8137*67e74705SXin Li   TL.setNameLoc(NameLoc);
8138*67e74705SXin Li   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
8139*67e74705SXin Li }
8140*67e74705SXin Li 
8141*67e74705SXin Li TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,const IdentifierInfo & II,SourceLocation IdLoc)8142*67e74705SXin Li Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8143*67e74705SXin Li                         const CXXScopeSpec &SS, const IdentifierInfo &II,
8144*67e74705SXin Li                         SourceLocation IdLoc) {
8145*67e74705SXin Li   if (SS.isInvalid())
8146*67e74705SXin Li     return true;
8147*67e74705SXin Li 
8148*67e74705SXin Li   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8149*67e74705SXin Li     Diag(TypenameLoc,
8150*67e74705SXin Li          getLangOpts().CPlusPlus11 ?
8151*67e74705SXin Li            diag::warn_cxx98_compat_typename_outside_of_template :
8152*67e74705SXin Li            diag::ext_typename_outside_of_template)
8153*67e74705SXin Li       << FixItHint::CreateRemoval(TypenameLoc);
8154*67e74705SXin Li 
8155*67e74705SXin Li   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8156*67e74705SXin Li   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8157*67e74705SXin Li                                  TypenameLoc, QualifierLoc, II, IdLoc);
8158*67e74705SXin Li   if (T.isNull())
8159*67e74705SXin Li     return true;
8160*67e74705SXin Li 
8161*67e74705SXin Li   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8162*67e74705SXin Li   if (isa<DependentNameType>(T)) {
8163*67e74705SXin Li     DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
8164*67e74705SXin Li     TL.setElaboratedKeywordLoc(TypenameLoc);
8165*67e74705SXin Li     TL.setQualifierLoc(QualifierLoc);
8166*67e74705SXin Li     TL.setNameLoc(IdLoc);
8167*67e74705SXin Li   } else {
8168*67e74705SXin Li     ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
8169*67e74705SXin Li     TL.setElaboratedKeywordLoc(TypenameLoc);
8170*67e74705SXin Li     TL.setQualifierLoc(QualifierLoc);
8171*67e74705SXin Li     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
8172*67e74705SXin Li   }
8173*67e74705SXin Li 
8174*67e74705SXin Li   return CreateParsedType(T, TSI);
8175*67e74705SXin Li }
8176*67e74705SXin Li 
8177*67e74705SXin Li TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateIn,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)8178*67e74705SXin Li Sema::ActOnTypenameType(Scope *S,
8179*67e74705SXin Li                         SourceLocation TypenameLoc,
8180*67e74705SXin Li                         const CXXScopeSpec &SS,
8181*67e74705SXin Li                         SourceLocation TemplateKWLoc,
8182*67e74705SXin Li                         TemplateTy TemplateIn,
8183*67e74705SXin Li                         SourceLocation TemplateNameLoc,
8184*67e74705SXin Li                         SourceLocation LAngleLoc,
8185*67e74705SXin Li                         ASTTemplateArgsPtr TemplateArgsIn,
8186*67e74705SXin Li                         SourceLocation RAngleLoc) {
8187*67e74705SXin Li   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8188*67e74705SXin Li     Diag(TypenameLoc,
8189*67e74705SXin Li          getLangOpts().CPlusPlus11 ?
8190*67e74705SXin Li            diag::warn_cxx98_compat_typename_outside_of_template :
8191*67e74705SXin Li            diag::ext_typename_outside_of_template)
8192*67e74705SXin Li       << FixItHint::CreateRemoval(TypenameLoc);
8193*67e74705SXin Li 
8194*67e74705SXin Li   // Translate the parser's template argument list in our AST format.
8195*67e74705SXin Li   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8196*67e74705SXin Li   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8197*67e74705SXin Li 
8198*67e74705SXin Li   TemplateName Template = TemplateIn.get();
8199*67e74705SXin Li   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8200*67e74705SXin Li     // Construct a dependent template specialization type.
8201*67e74705SXin Li     assert(DTN && "dependent template has non-dependent name?");
8202*67e74705SXin Li     assert(DTN->getQualifier() == SS.getScopeRep());
8203*67e74705SXin Li     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8204*67e74705SXin Li                                                           DTN->getQualifier(),
8205*67e74705SXin Li                                                           DTN->getIdentifier(),
8206*67e74705SXin Li                                                                 TemplateArgs);
8207*67e74705SXin Li 
8208*67e74705SXin Li     // Create source-location information for this type.
8209*67e74705SXin Li     TypeLocBuilder Builder;
8210*67e74705SXin Li     DependentTemplateSpecializationTypeLoc SpecTL
8211*67e74705SXin Li     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
8212*67e74705SXin Li     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8213*67e74705SXin Li     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
8214*67e74705SXin Li     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8215*67e74705SXin Li     SpecTL.setTemplateNameLoc(TemplateNameLoc);
8216*67e74705SXin Li     SpecTL.setLAngleLoc(LAngleLoc);
8217*67e74705SXin Li     SpecTL.setRAngleLoc(RAngleLoc);
8218*67e74705SXin Li     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8219*67e74705SXin Li       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8220*67e74705SXin Li     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
8221*67e74705SXin Li   }
8222*67e74705SXin Li 
8223*67e74705SXin Li   QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8224*67e74705SXin Li   if (T.isNull())
8225*67e74705SXin Li     return true;
8226*67e74705SXin Li 
8227*67e74705SXin Li   // Provide source-location information for the template specialization type.
8228*67e74705SXin Li   TypeLocBuilder Builder;
8229*67e74705SXin Li   TemplateSpecializationTypeLoc SpecTL
8230*67e74705SXin Li     = Builder.push<TemplateSpecializationTypeLoc>(T);
8231*67e74705SXin Li   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8232*67e74705SXin Li   SpecTL.setTemplateNameLoc(TemplateNameLoc);
8233*67e74705SXin Li   SpecTL.setLAngleLoc(LAngleLoc);
8234*67e74705SXin Li   SpecTL.setRAngleLoc(RAngleLoc);
8235*67e74705SXin Li   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8236*67e74705SXin Li     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8237*67e74705SXin Li 
8238*67e74705SXin Li   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8239*67e74705SXin Li   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8240*67e74705SXin Li   TL.setElaboratedKeywordLoc(TypenameLoc);
8241*67e74705SXin Li   TL.setQualifierLoc(SS.getWithLocInContext(Context));
8242*67e74705SXin Li 
8243*67e74705SXin Li   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8244*67e74705SXin Li   return CreateParsedType(T, TSI);
8245*67e74705SXin Li }
8246*67e74705SXin Li 
8247*67e74705SXin Li 
8248*67e74705SXin Li /// Determine whether this failed name lookup should be treated as being
8249*67e74705SXin Li /// disabled by a usage of std::enable_if.
isEnableIf(NestedNameSpecifierLoc NNS,const IdentifierInfo & II,SourceRange & CondRange)8250*67e74705SXin Li static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8251*67e74705SXin Li                        SourceRange &CondRange) {
8252*67e74705SXin Li   // We must be looking for a ::type...
8253*67e74705SXin Li   if (!II.isStr("type"))
8254*67e74705SXin Li     return false;
8255*67e74705SXin Li 
8256*67e74705SXin Li   // ... within an explicitly-written template specialization...
8257*67e74705SXin Li   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8258*67e74705SXin Li     return false;
8259*67e74705SXin Li   TypeLoc EnableIfTy = NNS.getTypeLoc();
8260*67e74705SXin Li   TemplateSpecializationTypeLoc EnableIfTSTLoc =
8261*67e74705SXin Li       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8262*67e74705SXin Li   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8263*67e74705SXin Li     return false;
8264*67e74705SXin Li   const TemplateSpecializationType *EnableIfTST =
8265*67e74705SXin Li     cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8266*67e74705SXin Li 
8267*67e74705SXin Li   // ... which names a complete class template declaration...
8268*67e74705SXin Li   const TemplateDecl *EnableIfDecl =
8269*67e74705SXin Li     EnableIfTST->getTemplateName().getAsTemplateDecl();
8270*67e74705SXin Li   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8271*67e74705SXin Li     return false;
8272*67e74705SXin Li 
8273*67e74705SXin Li   // ... called "enable_if".
8274*67e74705SXin Li   const IdentifierInfo *EnableIfII =
8275*67e74705SXin Li     EnableIfDecl->getDeclName().getAsIdentifierInfo();
8276*67e74705SXin Li   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8277*67e74705SXin Li     return false;
8278*67e74705SXin Li 
8279*67e74705SXin Li   // Assume the first template argument is the condition.
8280*67e74705SXin Li   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8281*67e74705SXin Li   return true;
8282*67e74705SXin Li }
8283*67e74705SXin Li 
8284*67e74705SXin Li /// \brief Build the type that describes a C++ typename specifier,
8285*67e74705SXin Li /// e.g., "typename T::type".
8286*67e74705SXin Li QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc)8287*67e74705SXin Li Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8288*67e74705SXin Li                         SourceLocation KeywordLoc,
8289*67e74705SXin Li                         NestedNameSpecifierLoc QualifierLoc,
8290*67e74705SXin Li                         const IdentifierInfo &II,
8291*67e74705SXin Li                         SourceLocation IILoc) {
8292*67e74705SXin Li   CXXScopeSpec SS;
8293*67e74705SXin Li   SS.Adopt(QualifierLoc);
8294*67e74705SXin Li 
8295*67e74705SXin Li   DeclContext *Ctx = computeDeclContext(SS);
8296*67e74705SXin Li   if (!Ctx) {
8297*67e74705SXin Li     // If the nested-name-specifier is dependent and couldn't be
8298*67e74705SXin Li     // resolved to a type, build a typename type.
8299*67e74705SXin Li     assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8300*67e74705SXin Li     return Context.getDependentNameType(Keyword,
8301*67e74705SXin Li                                         QualifierLoc.getNestedNameSpecifier(),
8302*67e74705SXin Li                                         &II);
8303*67e74705SXin Li   }
8304*67e74705SXin Li 
8305*67e74705SXin Li   // If the nested-name-specifier refers to the current instantiation,
8306*67e74705SXin Li   // the "typename" keyword itself is superfluous. In C++03, the
8307*67e74705SXin Li   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8308*67e74705SXin Li   // allows such extraneous "typename" keywords, and we retroactively
8309*67e74705SXin Li   // apply this DR to C++03 code with only a warning. In any case we continue.
8310*67e74705SXin Li 
8311*67e74705SXin Li   if (RequireCompleteDeclContext(SS, Ctx))
8312*67e74705SXin Li     return QualType();
8313*67e74705SXin Li 
8314*67e74705SXin Li   DeclarationName Name(&II);
8315*67e74705SXin Li   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8316*67e74705SXin Li   LookupQualifiedName(Result, Ctx, SS);
8317*67e74705SXin Li   unsigned DiagID = 0;
8318*67e74705SXin Li   Decl *Referenced = nullptr;
8319*67e74705SXin Li   switch (Result.getResultKind()) {
8320*67e74705SXin Li   case LookupResult::NotFound: {
8321*67e74705SXin Li     // If we're looking up 'type' within a template named 'enable_if', produce
8322*67e74705SXin Li     // a more specific diagnostic.
8323*67e74705SXin Li     SourceRange CondRange;
8324*67e74705SXin Li     if (isEnableIf(QualifierLoc, II, CondRange)) {
8325*67e74705SXin Li       Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8326*67e74705SXin Li         << Ctx << CondRange;
8327*67e74705SXin Li       return QualType();
8328*67e74705SXin Li     }
8329*67e74705SXin Li 
8330*67e74705SXin Li     DiagID = diag::err_typename_nested_not_found;
8331*67e74705SXin Li     break;
8332*67e74705SXin Li   }
8333*67e74705SXin Li 
8334*67e74705SXin Li   case LookupResult::FoundUnresolvedValue: {
8335*67e74705SXin Li     // We found a using declaration that is a value. Most likely, the using
8336*67e74705SXin Li     // declaration itself is meant to have the 'typename' keyword.
8337*67e74705SXin Li     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8338*67e74705SXin Li                           IILoc);
8339*67e74705SXin Li     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8340*67e74705SXin Li       << Name << Ctx << FullRange;
8341*67e74705SXin Li     if (UnresolvedUsingValueDecl *Using
8342*67e74705SXin Li           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8343*67e74705SXin Li       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8344*67e74705SXin Li       Diag(Loc, diag::note_using_value_decl_missing_typename)
8345*67e74705SXin Li         << FixItHint::CreateInsertion(Loc, "typename ");
8346*67e74705SXin Li     }
8347*67e74705SXin Li   }
8348*67e74705SXin Li   // Fall through to create a dependent typename type, from which we can recover
8349*67e74705SXin Li   // better.
8350*67e74705SXin Li 
8351*67e74705SXin Li   case LookupResult::NotFoundInCurrentInstantiation:
8352*67e74705SXin Li     // Okay, it's a member of an unknown instantiation.
8353*67e74705SXin Li     return Context.getDependentNameType(Keyword,
8354*67e74705SXin Li                                         QualifierLoc.getNestedNameSpecifier(),
8355*67e74705SXin Li                                         &II);
8356*67e74705SXin Li 
8357*67e74705SXin Li   case LookupResult::Found:
8358*67e74705SXin Li     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8359*67e74705SXin Li       // We found a type. Build an ElaboratedType, since the
8360*67e74705SXin Li       // typename-specifier was just sugar.
8361*67e74705SXin Li       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8362*67e74705SXin Li       return Context.getElaboratedType(ETK_Typename,
8363*67e74705SXin Li                                        QualifierLoc.getNestedNameSpecifier(),
8364*67e74705SXin Li                                        Context.getTypeDeclType(Type));
8365*67e74705SXin Li     }
8366*67e74705SXin Li 
8367*67e74705SXin Li     DiagID = diag::err_typename_nested_not_type;
8368*67e74705SXin Li     Referenced = Result.getFoundDecl();
8369*67e74705SXin Li     break;
8370*67e74705SXin Li 
8371*67e74705SXin Li   case LookupResult::FoundOverloaded:
8372*67e74705SXin Li     DiagID = diag::err_typename_nested_not_type;
8373*67e74705SXin Li     Referenced = *Result.begin();
8374*67e74705SXin Li     break;
8375*67e74705SXin Li 
8376*67e74705SXin Li   case LookupResult::Ambiguous:
8377*67e74705SXin Li     return QualType();
8378*67e74705SXin Li   }
8379*67e74705SXin Li 
8380*67e74705SXin Li   // If we get here, it's because name lookup did not find a
8381*67e74705SXin Li   // type. Emit an appropriate diagnostic and return an error.
8382*67e74705SXin Li   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8383*67e74705SXin Li                         IILoc);
8384*67e74705SXin Li   Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8385*67e74705SXin Li   if (Referenced)
8386*67e74705SXin Li     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8387*67e74705SXin Li       << Name;
8388*67e74705SXin Li   return QualType();
8389*67e74705SXin Li }
8390*67e74705SXin Li 
8391*67e74705SXin Li namespace {
8392*67e74705SXin Li   // See Sema::RebuildTypeInCurrentInstantiation
8393*67e74705SXin Li   class CurrentInstantiationRebuilder
8394*67e74705SXin Li     : public TreeTransform<CurrentInstantiationRebuilder> {
8395*67e74705SXin Li     SourceLocation Loc;
8396*67e74705SXin Li     DeclarationName Entity;
8397*67e74705SXin Li 
8398*67e74705SXin Li   public:
8399*67e74705SXin Li     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8400*67e74705SXin Li 
CurrentInstantiationRebuilder(Sema & SemaRef,SourceLocation Loc,DeclarationName Entity)8401*67e74705SXin Li     CurrentInstantiationRebuilder(Sema &SemaRef,
8402*67e74705SXin Li                                   SourceLocation Loc,
8403*67e74705SXin Li                                   DeclarationName Entity)
8404*67e74705SXin Li     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8405*67e74705SXin Li       Loc(Loc), Entity(Entity) { }
8406*67e74705SXin Li 
8407*67e74705SXin Li     /// \brief Determine whether the given type \p T has already been
8408*67e74705SXin Li     /// transformed.
8409*67e74705SXin Li     ///
8410*67e74705SXin Li     /// For the purposes of type reconstruction, a type has already been
8411*67e74705SXin Li     /// transformed if it is NULL or if it is not dependent.
AlreadyTransformed(QualType T)8412*67e74705SXin Li     bool AlreadyTransformed(QualType T) {
8413*67e74705SXin Li       return T.isNull() || !T->isDependentType();
8414*67e74705SXin Li     }
8415*67e74705SXin Li 
8416*67e74705SXin Li     /// \brief Returns the location of the entity whose type is being
8417*67e74705SXin Li     /// rebuilt.
getBaseLocation()8418*67e74705SXin Li     SourceLocation getBaseLocation() { return Loc; }
8419*67e74705SXin Li 
8420*67e74705SXin Li     /// \brief Returns the name of the entity whose type is being rebuilt.
getBaseEntity()8421*67e74705SXin Li     DeclarationName getBaseEntity() { return Entity; }
8422*67e74705SXin Li 
8423*67e74705SXin Li     /// \brief Sets the "base" location and entity when that
8424*67e74705SXin Li     /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)8425*67e74705SXin Li     void setBase(SourceLocation Loc, DeclarationName Entity) {
8426*67e74705SXin Li       this->Loc = Loc;
8427*67e74705SXin Li       this->Entity = Entity;
8428*67e74705SXin Li     }
8429*67e74705SXin Li 
TransformLambdaExpr(LambdaExpr * E)8430*67e74705SXin Li     ExprResult TransformLambdaExpr(LambdaExpr *E) {
8431*67e74705SXin Li       // Lambdas never need to be transformed.
8432*67e74705SXin Li       return E;
8433*67e74705SXin Li     }
8434*67e74705SXin Li   };
8435*67e74705SXin Li } // end anonymous namespace
8436*67e74705SXin Li 
8437*67e74705SXin Li /// \brief Rebuilds a type within the context of the current instantiation.
8438*67e74705SXin Li ///
8439*67e74705SXin Li /// The type \p T is part of the type of an out-of-line member definition of
8440*67e74705SXin Li /// a class template (or class template partial specialization) that was parsed
8441*67e74705SXin Li /// and constructed before we entered the scope of the class template (or
8442*67e74705SXin Li /// partial specialization thereof). This routine will rebuild that type now
8443*67e74705SXin Li /// that we have entered the declarator's scope, which may produce different
8444*67e74705SXin Li /// canonical types, e.g.,
8445*67e74705SXin Li ///
8446*67e74705SXin Li /// \code
8447*67e74705SXin Li /// template<typename T>
8448*67e74705SXin Li /// struct X {
8449*67e74705SXin Li ///   typedef T* pointer;
8450*67e74705SXin Li ///   pointer data();
8451*67e74705SXin Li /// };
8452*67e74705SXin Li ///
8453*67e74705SXin Li /// template<typename T>
8454*67e74705SXin Li /// typename X<T>::pointer X<T>::data() { ... }
8455*67e74705SXin Li /// \endcode
8456*67e74705SXin Li ///
8457*67e74705SXin Li /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8458*67e74705SXin Li /// since we do not know that we can look into X<T> when we parsed the type.
8459*67e74705SXin Li /// This function will rebuild the type, performing the lookup of "pointer"
8460*67e74705SXin Li /// in X<T> and returning an ElaboratedType whose canonical type is the same
8461*67e74705SXin Li /// as the canonical type of T*, allowing the return types of the out-of-line
8462*67e74705SXin Li /// definition and the declaration to match.
RebuildTypeInCurrentInstantiation(TypeSourceInfo * T,SourceLocation Loc,DeclarationName Name)8463*67e74705SXin Li TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8464*67e74705SXin Li                                                         SourceLocation Loc,
8465*67e74705SXin Li                                                         DeclarationName Name) {
8466*67e74705SXin Li   if (!T || !T->getType()->isDependentType())
8467*67e74705SXin Li     return T;
8468*67e74705SXin Li 
8469*67e74705SXin Li   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8470*67e74705SXin Li   return Rebuilder.TransformType(T);
8471*67e74705SXin Li }
8472*67e74705SXin Li 
RebuildExprInCurrentInstantiation(Expr * E)8473*67e74705SXin Li ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8474*67e74705SXin Li   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8475*67e74705SXin Li                                           DeclarationName());
8476*67e74705SXin Li   return Rebuilder.TransformExpr(E);
8477*67e74705SXin Li }
8478*67e74705SXin Li 
RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec & SS)8479*67e74705SXin Li bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8480*67e74705SXin Li   if (SS.isInvalid())
8481*67e74705SXin Li     return true;
8482*67e74705SXin Li 
8483*67e74705SXin Li   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8484*67e74705SXin Li   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8485*67e74705SXin Li                                           DeclarationName());
8486*67e74705SXin Li   NestedNameSpecifierLoc Rebuilt
8487*67e74705SXin Li     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8488*67e74705SXin Li   if (!Rebuilt)
8489*67e74705SXin Li     return true;
8490*67e74705SXin Li 
8491*67e74705SXin Li   SS.Adopt(Rebuilt);
8492*67e74705SXin Li   return false;
8493*67e74705SXin Li }
8494*67e74705SXin Li 
8495*67e74705SXin Li /// \brief Rebuild the template parameters now that we know we're in a current
8496*67e74705SXin Li /// instantiation.
RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList * Params)8497*67e74705SXin Li bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8498*67e74705SXin Li                                                TemplateParameterList *Params) {
8499*67e74705SXin Li   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8500*67e74705SXin Li     Decl *Param = Params->getParam(I);
8501*67e74705SXin Li 
8502*67e74705SXin Li     // There is nothing to rebuild in a type parameter.
8503*67e74705SXin Li     if (isa<TemplateTypeParmDecl>(Param))
8504*67e74705SXin Li       continue;
8505*67e74705SXin Li 
8506*67e74705SXin Li     // Rebuild the template parameter list of a template template parameter.
8507*67e74705SXin Li     if (TemplateTemplateParmDecl *TTP
8508*67e74705SXin Li         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8509*67e74705SXin Li       if (RebuildTemplateParamsInCurrentInstantiation(
8510*67e74705SXin Li             TTP->getTemplateParameters()))
8511*67e74705SXin Li         return true;
8512*67e74705SXin Li 
8513*67e74705SXin Li       continue;
8514*67e74705SXin Li     }
8515*67e74705SXin Li 
8516*67e74705SXin Li     // Rebuild the type of a non-type template parameter.
8517*67e74705SXin Li     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8518*67e74705SXin Li     TypeSourceInfo *NewTSI
8519*67e74705SXin Li       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8520*67e74705SXin Li                                           NTTP->getLocation(),
8521*67e74705SXin Li                                           NTTP->getDeclName());
8522*67e74705SXin Li     if (!NewTSI)
8523*67e74705SXin Li       return true;
8524*67e74705SXin Li 
8525*67e74705SXin Li     if (NewTSI != NTTP->getTypeSourceInfo()) {
8526*67e74705SXin Li       NTTP->setTypeSourceInfo(NewTSI);
8527*67e74705SXin Li       NTTP->setType(NewTSI->getType());
8528*67e74705SXin Li     }
8529*67e74705SXin Li   }
8530*67e74705SXin Li 
8531*67e74705SXin Li   return false;
8532*67e74705SXin Li }
8533*67e74705SXin Li 
8534*67e74705SXin Li /// \brief Produces a formatted string that describes the binding of
8535*67e74705SXin Li /// template parameters to template arguments.
8536*67e74705SXin Li std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgumentList & Args)8537*67e74705SXin Li Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8538*67e74705SXin Li                                       const TemplateArgumentList &Args) {
8539*67e74705SXin Li   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8540*67e74705SXin Li }
8541*67e74705SXin Li 
8542*67e74705SXin Li std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgument * Args,unsigned NumArgs)8543*67e74705SXin Li Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8544*67e74705SXin Li                                       const TemplateArgument *Args,
8545*67e74705SXin Li                                       unsigned NumArgs) {
8546*67e74705SXin Li   SmallString<128> Str;
8547*67e74705SXin Li   llvm::raw_svector_ostream Out(Str);
8548*67e74705SXin Li 
8549*67e74705SXin Li   if (!Params || Params->size() == 0 || NumArgs == 0)
8550*67e74705SXin Li     return std::string();
8551*67e74705SXin Li 
8552*67e74705SXin Li   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8553*67e74705SXin Li     if (I >= NumArgs)
8554*67e74705SXin Li       break;
8555*67e74705SXin Li 
8556*67e74705SXin Li     if (I == 0)
8557*67e74705SXin Li       Out << "[with ";
8558*67e74705SXin Li     else
8559*67e74705SXin Li       Out << ", ";
8560*67e74705SXin Li 
8561*67e74705SXin Li     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8562*67e74705SXin Li       Out << Id->getName();
8563*67e74705SXin Li     } else {
8564*67e74705SXin Li       Out << '$' << I;
8565*67e74705SXin Li     }
8566*67e74705SXin Li 
8567*67e74705SXin Li     Out << " = ";
8568*67e74705SXin Li     Args[I].print(getPrintingPolicy(), Out);
8569*67e74705SXin Li   }
8570*67e74705SXin Li 
8571*67e74705SXin Li   Out << ']';
8572*67e74705SXin Li   return Out.str();
8573*67e74705SXin Li }
8574*67e74705SXin Li 
MarkAsLateParsedTemplate(FunctionDecl * FD,Decl * FnD,CachedTokens & Toks)8575*67e74705SXin Li void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8576*67e74705SXin Li                                     CachedTokens &Toks) {
8577*67e74705SXin Li   if (!FD)
8578*67e74705SXin Li     return;
8579*67e74705SXin Li 
8580*67e74705SXin Li   LateParsedTemplate *LPT = new LateParsedTemplate;
8581*67e74705SXin Li 
8582*67e74705SXin Li   // Take tokens to avoid allocations
8583*67e74705SXin Li   LPT->Toks.swap(Toks);
8584*67e74705SXin Li   LPT->D = FnD;
8585*67e74705SXin Li   LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8586*67e74705SXin Li 
8587*67e74705SXin Li   FD->setLateTemplateParsed(true);
8588*67e74705SXin Li }
8589*67e74705SXin Li 
UnmarkAsLateParsedTemplate(FunctionDecl * FD)8590*67e74705SXin Li void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8591*67e74705SXin Li   if (!FD)
8592*67e74705SXin Li     return;
8593*67e74705SXin Li   FD->setLateTemplateParsed(false);
8594*67e74705SXin Li }
8595*67e74705SXin Li 
IsInsideALocalClassWithinATemplateFunction()8596*67e74705SXin Li bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8597*67e74705SXin Li   DeclContext *DC = CurContext;
8598*67e74705SXin Li 
8599*67e74705SXin Li   while (DC) {
8600*67e74705SXin Li     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8601*67e74705SXin Li       const FunctionDecl *FD = RD->isLocalClass();
8602*67e74705SXin Li       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8603*67e74705SXin Li     } else if (DC->isTranslationUnit() || DC->isNamespace())
8604*67e74705SXin Li       return false;
8605*67e74705SXin Li 
8606*67e74705SXin Li     DC = DC->getParent();
8607*67e74705SXin Li   }
8608*67e74705SXin Li   return false;
8609*67e74705SXin Li }
8610*67e74705SXin Li 
8611*67e74705SXin Li /// \brief Walk the path from which a declaration was instantiated, and check
8612*67e74705SXin Li /// that every explicit specialization along that path is visible. This enforces
8613*67e74705SXin Li /// C++ [temp.expl.spec]/6:
8614*67e74705SXin Li ///
8615*67e74705SXin Li ///   If a template, a member template or a member of a class template is
8616*67e74705SXin Li ///   explicitly specialized then that specialization shall be declared before
8617*67e74705SXin Li ///   the first use of that specialization that would cause an implicit
8618*67e74705SXin Li ///   instantiation to take place, in every translation unit in which such a
8619*67e74705SXin Li ///   use occurs; no diagnostic is required.
8620*67e74705SXin Li ///
8621*67e74705SXin Li /// and also C++ [temp.class.spec]/1:
8622*67e74705SXin Li ///
8623*67e74705SXin Li ///   A partial specialization shall be declared before the first use of a
8624*67e74705SXin Li ///   class template specialization that would make use of the partial
8625*67e74705SXin Li ///   specialization as the result of an implicit or explicit instantiation
8626*67e74705SXin Li ///   in every translation unit in which such a use occurs; no diagnostic is
8627*67e74705SXin Li ///   required.
8628*67e74705SXin Li class ExplicitSpecializationVisibilityChecker {
8629*67e74705SXin Li   Sema &S;
8630*67e74705SXin Li   SourceLocation Loc;
8631*67e74705SXin Li   llvm::SmallVector<Module *, 8> Modules;
8632*67e74705SXin Li 
8633*67e74705SXin Li public:
ExplicitSpecializationVisibilityChecker(Sema & S,SourceLocation Loc)8634*67e74705SXin Li   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8635*67e74705SXin Li       : S(S), Loc(Loc) {}
8636*67e74705SXin Li 
check(NamedDecl * ND)8637*67e74705SXin Li   void check(NamedDecl *ND) {
8638*67e74705SXin Li     if (auto *FD = dyn_cast<FunctionDecl>(ND))
8639*67e74705SXin Li       return checkImpl(FD);
8640*67e74705SXin Li     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8641*67e74705SXin Li       return checkImpl(RD);
8642*67e74705SXin Li     if (auto *VD = dyn_cast<VarDecl>(ND))
8643*67e74705SXin Li       return checkImpl(VD);
8644*67e74705SXin Li     if (auto *ED = dyn_cast<EnumDecl>(ND))
8645*67e74705SXin Li       return checkImpl(ED);
8646*67e74705SXin Li   }
8647*67e74705SXin Li 
8648*67e74705SXin Li private:
diagnose(NamedDecl * D,bool IsPartialSpec)8649*67e74705SXin Li   void diagnose(NamedDecl *D, bool IsPartialSpec) {
8650*67e74705SXin Li     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8651*67e74705SXin Li                               : Sema::MissingImportKind::ExplicitSpecialization;
8652*67e74705SXin Li     const bool Recover = true;
8653*67e74705SXin Li 
8654*67e74705SXin Li     // If we got a custom set of modules (because only a subset of the
8655*67e74705SXin Li     // declarations are interesting), use them, otherwise let
8656*67e74705SXin Li     // diagnoseMissingImport intelligently pick some.
8657*67e74705SXin Li     if (Modules.empty())
8658*67e74705SXin Li       S.diagnoseMissingImport(Loc, D, Kind, Recover);
8659*67e74705SXin Li     else
8660*67e74705SXin Li       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8661*67e74705SXin Li   }
8662*67e74705SXin Li 
8663*67e74705SXin Li   // Check a specific declaration. There are three problematic cases:
8664*67e74705SXin Li   //
8665*67e74705SXin Li   //  1) The declaration is an explicit specialization of a template
8666*67e74705SXin Li   //     specialization.
8667*67e74705SXin Li   //  2) The declaration is an explicit specialization of a member of an
8668*67e74705SXin Li   //     templated class.
8669*67e74705SXin Li   //  3) The declaration is an instantiation of a template, and that template
8670*67e74705SXin Li   //     is an explicit specialization of a member of a templated class.
8671*67e74705SXin Li   //
8672*67e74705SXin Li   // We don't need to go any deeper than that, as the instantiation of the
8673*67e74705SXin Li   // surrounding class / etc is not triggered by whatever triggered this
8674*67e74705SXin Li   // instantiation, and thus should be checked elsewhere.
8675*67e74705SXin Li   template<typename SpecDecl>
checkImpl(SpecDecl * Spec)8676*67e74705SXin Li   void checkImpl(SpecDecl *Spec) {
8677*67e74705SXin Li     bool IsHiddenExplicitSpecialization = false;
8678*67e74705SXin Li     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8679*67e74705SXin Li       IsHiddenExplicitSpecialization =
8680*67e74705SXin Li           Spec->getMemberSpecializationInfo()
8681*67e74705SXin Li               ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8682*67e74705SXin Li               : !S.hasVisibleDeclaration(Spec);
8683*67e74705SXin Li     } else {
8684*67e74705SXin Li       checkInstantiated(Spec);
8685*67e74705SXin Li     }
8686*67e74705SXin Li 
8687*67e74705SXin Li     if (IsHiddenExplicitSpecialization)
8688*67e74705SXin Li       diagnose(Spec->getMostRecentDecl(), false);
8689*67e74705SXin Li   }
8690*67e74705SXin Li 
checkInstantiated(FunctionDecl * FD)8691*67e74705SXin Li   void checkInstantiated(FunctionDecl *FD) {
8692*67e74705SXin Li     if (auto *TD = FD->getPrimaryTemplate())
8693*67e74705SXin Li       checkTemplate(TD);
8694*67e74705SXin Li   }
8695*67e74705SXin Li 
checkInstantiated(CXXRecordDecl * RD)8696*67e74705SXin Li   void checkInstantiated(CXXRecordDecl *RD) {
8697*67e74705SXin Li     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8698*67e74705SXin Li     if (!SD)
8699*67e74705SXin Li       return;
8700*67e74705SXin Li 
8701*67e74705SXin Li     auto From = SD->getSpecializedTemplateOrPartial();
8702*67e74705SXin Li     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8703*67e74705SXin Li       checkTemplate(TD);
8704*67e74705SXin Li     else if (auto *TD =
8705*67e74705SXin Li                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8706*67e74705SXin Li       if (!S.hasVisibleDeclaration(TD))
8707*67e74705SXin Li         diagnose(TD, true);
8708*67e74705SXin Li       checkTemplate(TD);
8709*67e74705SXin Li     }
8710*67e74705SXin Li   }
8711*67e74705SXin Li 
checkInstantiated(VarDecl * RD)8712*67e74705SXin Li   void checkInstantiated(VarDecl *RD) {
8713*67e74705SXin Li     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8714*67e74705SXin Li     if (!SD)
8715*67e74705SXin Li       return;
8716*67e74705SXin Li 
8717*67e74705SXin Li     auto From = SD->getSpecializedTemplateOrPartial();
8718*67e74705SXin Li     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8719*67e74705SXin Li       checkTemplate(TD);
8720*67e74705SXin Li     else if (auto *TD =
8721*67e74705SXin Li                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8722*67e74705SXin Li       if (!S.hasVisibleDeclaration(TD))
8723*67e74705SXin Li         diagnose(TD, true);
8724*67e74705SXin Li       checkTemplate(TD);
8725*67e74705SXin Li     }
8726*67e74705SXin Li   }
8727*67e74705SXin Li 
checkInstantiated(EnumDecl * FD)8728*67e74705SXin Li   void checkInstantiated(EnumDecl *FD) {}
8729*67e74705SXin Li 
8730*67e74705SXin Li   template<typename TemplDecl>
checkTemplate(TemplDecl * TD)8731*67e74705SXin Li   void checkTemplate(TemplDecl *TD) {
8732*67e74705SXin Li     if (TD->isMemberSpecialization()) {
8733*67e74705SXin Li       if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8734*67e74705SXin Li         diagnose(TD->getMostRecentDecl(), false);
8735*67e74705SXin Li     }
8736*67e74705SXin Li   }
8737*67e74705SXin Li };
8738*67e74705SXin Li 
checkSpecializationVisibility(SourceLocation Loc,NamedDecl * Spec)8739*67e74705SXin Li void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8740*67e74705SXin Li   if (!getLangOpts().Modules)
8741*67e74705SXin Li     return;
8742*67e74705SXin Li 
8743*67e74705SXin Li   ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8744*67e74705SXin Li }
8745*67e74705SXin Li 
8746*67e74705SXin Li /// \brief Check whether a template partial specialization that we've discovered
8747*67e74705SXin Li /// is hidden, and produce suitable diagnostics if so.
checkPartialSpecializationVisibility(SourceLocation Loc,NamedDecl * Spec)8748*67e74705SXin Li void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8749*67e74705SXin Li                                                 NamedDecl *Spec) {
8750*67e74705SXin Li   llvm::SmallVector<Module *, 8> Modules;
8751*67e74705SXin Li   if (!hasVisibleDeclaration(Spec, &Modules))
8752*67e74705SXin Li     diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8753*67e74705SXin Li                           MissingImportKind::PartialSpecialization,
8754*67e74705SXin Li                           /*Recover*/true);
8755*67e74705SXin Li }
8756