Bug Summary

File:tools/clang/lib/Sema/SemaTemplate.cpp
Warning:line 1845, column 33
Access to field 'TypeAsWritten' results in a dereference of a null pointer (loaded from field 'ExplicitInfo')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp

1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ templates.
10//===----------------------------------------------------------------------===//
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/RecursiveASTVisitor.h"
20#include "clang/AST/TypeVisitor.h"
21#include "clang/Basic/Builtins.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
32#include "llvm/ADT/SmallBitVector.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/StringExtras.h"
35
36#include <iterator>
37using namespace clang;
38using namespace sema;
39
40// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
48namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.")(static_cast <bool> (!FD && "Cannot collect constraints from function declaration yet."
) ? void (0) : __assert_fail ("!FD && \"Cannot collect constraints from function declaration yet.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 64, __extension__ __PRETTY_FUNCTION__))
;
65 return Params->getRequiresClause();
66}
67
68/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
71static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
72 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
74 NamedDecl *D = Orig->getUnderlyingDecl();
75
76 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
78 return nullptr;
79
80 return Orig;
81 }
82
83 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
96 Record = cast<CXXRecordDecl>(Record->getDeclContext());
97 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
104
105 return nullptr;
106 }
107
108 return nullptr;
109}
110
111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
112 bool AllowFunctionTemplates) {
113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
119 AllowFunctionTemplates);
120 if (!Repl)
121 filter.erase();
122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
125 // A lookup that finds an injected-class-name (10.2) can result in an
126 // ambiguity in certain cases (for example, if it is found in more than
127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
131 // ambiguous.
132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
133 if (!ClassTemplates.insert(ClassTmpl).second) {
134 filter.erase();
135 continue;
136 }
137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
144 }
145 }
146 filter.done();
147}
148
149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
153 return true;
154
155 return false;
156}
157
158TemplateNameKind Sema::isTemplateName(Scope *S,
159 CXXScopeSpec &SS,
160 bool hasTemplateKeyword,
161 UnqualifiedId &Name,
162 ParsedType ObjectTypePtr,
163 bool EnteringContext,
164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
166 assert(getLangOpts().CPlusPlus && "No template names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No template names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 166, __extension__ __PRETTY_FUNCTION__))
;
167
168 DeclarationName TName;
169 MemberOfUnknownSpecialization = false;
170
171 switch (Name.getKind()) {
172 case UnqualifiedIdKind::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
175
176 case UnqualifiedIdKind::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
181 case UnqualifiedIdKind::IK_LiteralOperatorId:
182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
184
185 default:
186 return TNK_Non_template;
187 }
188
189 QualType ObjectType = ObjectTypePtr.get();
190
191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
197 R.suppressDiagnostics();
198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
201 return TNK_Non_template;
202 }
203
204 TemplateName Template;
205 TemplateNameKind TemplateKind;
206
207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
216 } else {
217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
223 } else {
224 Template = TemplateName(TD);
225 }
226
227 if (isa<FunctionTemplateDecl>(TD)) {
228 TemplateKind = TNK_Function_template;
229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __extension__ __PRETTY_FUNCTION__))
234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __extension__ __PRETTY_FUNCTION__))
235 isa<BuiltinTemplateDecl>(TD))(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __extension__ __PRETTY_FUNCTION__))
;
236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
238 }
239 }
240
241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
243}
244
245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
284 // FIXME: Typo correction?
285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
288
289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
294 << FixItHint::CreateInsertion(IILoc, "template ");
295 SuggestedTemplate
296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
301void Sema::LookupTemplateName(LookupResult &Found,
302 Scope *S, CXXScopeSpec &SS,
303 QualType ObjectType,
304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
306 // Determine where to perform name lookup
307 MemberOfUnknownSpecialization = false;
308 DeclContext *LookupCtx = nullptr;
309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist")(static_cast <bool> (!SS.isSet() && "ObjectType and scope specifier cannot coexist"
) ? void (0) : __assert_fail ("!SS.isSet() && \"ObjectType and scope specifier cannot coexist\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 313, __extension__ __PRETTY_FUNCTION__))
;
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
316 assert((isDependent || !ObjectType->isIncompleteType() ||(static_cast <bool> ((isDependent || !ObjectType->isIncompleteType
() || ObjectType->castAs<TagType>()->isBeingDefined
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&(static_cast <bool> ((isDependent || !ObjectType->isIncompleteType
() || ObjectType->castAs<TagType>()->isBeingDefined
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
318 "Caller should have completed object type")(static_cast <bool> ((isDependent || !ObjectType->isIncompleteType
() || ObjectType->castAs<TagType>()->isBeingDefined
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
;
319
320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
330
331 // The declaration context must be complete.
332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
337 bool AllowFunctionTemplatesInLookup = true;
338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
356 AllowFunctionTemplatesInLookup = false;
357 }
358 } else if (isDependent && (!S || ObjectType.isNull())) {
359 // We cannot look into a dependent object type or nested nme
360 // specifier.
361 MemberOfUnknownSpecialization = true;
362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
366
367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
369 }
370
371 if (Found.empty() && !isDependent) {
372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
374 Found.clear();
375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
384 Found.setLookupName(Corrected.getCorrection());
385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
387 FilterAcceptableTemplateNames(Found);
388 if (!Found.empty()) {
389 if (LookupCtx) {
390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
392 Name.getAsString() == CorrectedStr;
393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
396 } else {
397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
398 }
399 }
400 } else {
401 Found.setLookupName(Name);
402 }
403 }
404
405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
409 return;
410 }
411
412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
413 !getLangOpts().CPlusPlus11) {
414 // C++03 [basic.lookup.classref]p1:
415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
419 // Note: C++11 does not perform this second lookup.
420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
424
425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
433 FoundOuter.clear();
434 } else if (!Found.isSuppressingDiagnostics()) {
435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
441 Diag(Found.getNameLoc(),
442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
458void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
459 SourceLocation Less,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
462 return;
463
464 DeclarationNameInfo NameInfo;
465 CXXScopeSpec SS;
466 LookupNameKind LookupKind;
467
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
470
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
478 } else {
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
484 }
485
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
493 };
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
498 }
499 };
500
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
507 if (ND)
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
511 if (LookupCtx) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
518 << SS.getRange(), false);
519 } else {
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
522 << Name, false);
523 }
524 if (Found)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
527 return;
528 }
529 }
530
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
533 if (Found)
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535}
536
537/// ActOnDependentIdExpression - Handle a dependent id-expression that
538/// was just parsed. This is only possible with an explicit scope
539/// specifier naming a dependent type.
540ExprResult
541Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
542 SourceLocation TemplateKWLoc,
543 const DeclarationNameInfo &NameInfo,
544 bool isAddressOfOperand,
545 const TemplateArgumentListInfo *TemplateArgs) {
546 DeclContext *DC = getFunctionLevelDeclContext();
547
548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
551 // (...)
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
554 //
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561
562 // Check if the nested name specifier is an enum type.
563 bool IsEnum = false;
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
570
571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
573 NamedDecl *FirstQualifierInScope = nullptr;
574
575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
579 }
580
581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
582}
583
584ExprResult
585Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
586 SourceLocation TemplateKWLoc,
587 const DeclarationNameInfo &NameInfo,
588 const TemplateArgumentListInfo *TemplateArgs) {
589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591 TemplateArgs);
592}
593
594
595/// Determine whether we would be unable to instantiate this template (because
596/// it either has no definition, or is in the process of being instantiated).
597bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||(static_cast <bool> (isa<TagDecl>(Instantiation) ||
isa<FunctionDecl>(Instantiation) || isa<VarDecl>
(Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 605, __extension__ __PRETTY_FUNCTION__))
605 isa<VarDecl>(Instantiation))(static_cast <bool> (isa<TagDecl>(Instantiation) ||
isa<FunctionDecl>(Instantiation) || isa<VarDecl>
(Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 605, __extension__ __PRETTY_FUNCTION__))
;
606
607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
610
611 if (PatternDef && !IsEntityBeingDefined) {
612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
617 if (Complain)
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
620 return !Recover;
621 }
622 return false;
623 }
624
625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626 return true;
627
628 llvm::Optional<unsigned> Note;
629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
632 if (PatternDef) {
633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
636 << InstantiationTy;
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
647 } else {
648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")(static_cast <bool> (isa<TagDecl>(Instantiation) &&
"Must be a TagDecl!") ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 648, __extension__ __PRETTY_FUNCTION__))
;
649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
651 << InstantiationTy;
652 Note = diag::note_member_declared_at;
653 }
654 } else {
655 if (isa<FunctionDecl>(Instantiation)) {
656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
658 << Pattern;
659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
663 << InstantiationTy;
664 Note = diag::note_template_decl_here;
665 } else {
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")(static_cast <bool> (isa<VarDecl>(Instantiation) &&
"Must be a VarDecl!") ? void (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 666, __extension__ __PRETTY_FUNCTION__))
;
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
670 << Instantiation;
671 Instantiation->setInvalidDecl();
672 } else
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
678 }
679 }
680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
682
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
689 return true;
690}
691
692/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693/// that the template parameter 'PrevDecl' is being shadowed by a new
694/// declaration at location Loc. Returns true to indicate that this is
695/// an error, and false otherwise.
696void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter")(static_cast <bool> (PrevDecl->isTemplateParameter()
&& "Not a template parameter") ? void (0) : __assert_fail
("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 697, __extension__ __PRETTY_FUNCTION__))
;
698
699 // Microsoft Visual C++ permits template parameters to be shadowed.
700 if (getLangOpts().MicrosoftExt)
701 return;
702
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
706 Diag(Loc, diag::err_template_param_shadow)
707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
709}
710
711/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712/// the parameter D to reference the templated declaration and return a pointer
713/// to the template declaration. Otherwise, do nothing to D and return null.
714TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
717 return Temp;
718 }
719 return nullptr;
720}
721
722ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
724 assert(Kind == Template &&(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here"
) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 725, __extension__ __PRETTY_FUNCTION__))
725 "Only template template arguments can be pack expansions here")(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here"
) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 725, __extension__ __PRETTY_FUNCTION__))
;
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack
() && "Template template argument pack expansion without packs"
) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 727, __extension__ __PRETTY_FUNCTION__))
727 "Template template argument pack expansion without packs")(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack
() && "Template template argument pack expansion without packs"
) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 727, __extension__ __PRETTY_FUNCTION__))
;
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
730 return Result;
731}
732
733static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
735
736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
738 TypeSourceInfo *DI;
739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
740 if (!DI)
741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742 return TemplateArgumentLoc(TemplateArgument(T), DI);
743 }
744
745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
748 }
749
750 case ParsedTemplateArgument::Template: {
751 TemplateName Template = Arg.getAsTemplate().get();
752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
754 TArg = TemplateArgument(Template, Optional<unsigned int>());
755 else
756 TArg = Template;
757 return TemplateArgumentLoc(TArg,
758 Arg.getScopeSpec().getWithLocInContext(
759 SemaRef.Context),
760 Arg.getLocation(),
761 Arg.getEllipsisLoc());
762 }
763 }
764
765 llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 765)
;
766}
767
768/// \brief Translates template arguments as provided by the parser
769/// into template arguments used by semantic analysis.
770void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773 TemplateArgs.addArgument(translateTemplateArgument(*this,
774 TemplateArgsIn[I]));
775}
776
777static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
778 SourceLocation Loc,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784}
785
786/// ActOnTypeParameter - Called when a C++ template type parameter
787/// (e.g., "typename T") has been parsed. Typename specifies whether
788/// the keyword "typename" was used to declare the type parameter
789/// (otherwise, "class" was used), and KeyLoc is the location of the
790/// "class" or "typename" keyword. ParamName is the name of the
791/// parameter (NULL indicates an unnamed template parameter) and
792/// ParamNameLoc is the location of the parameter name (if any).
793/// If the type parameter has a default argument, it will be added
794/// later via ActOnTypeParameterDefault.
795NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
802 ParsedType DefaultArg) {
803 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Template type parameter not in template parameter scope!") ?
void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 804, __extension__ __PRETTY_FUNCTION__))
804 "Template type parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Template type parameter not in template parameter scope!") ?
void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 804, __extension__ __PRETTY_FUNCTION__))
;
805
806 SourceLocation Loc = ParamNameLoc;
807 if (!ParamName)
808 Loc = KeyLoc;
809
810 bool IsParameterPack = EllipsisLoc.isValid();
811 TemplateTypeParmDecl *Param
812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
813 KeyLoc, Loc, Depth, Position, ParamName,
814 Typename, IsParameterPack);
815 Param->setAccess(AS_public);
816
817 if (ParamName) {
818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
819
820 // Add the template parameter into the current scope.
821 S->AddDecl(Param);
822 IdResolver.AddDecl(Param);
823 }
824
825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
828 if (DefaultArg && IsParameterPack) {
829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830 DefaultArg = nullptr;
831 }
832
833 // Handle the default argument, if provided.
834 if (DefaultArg) {
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
837
838 assert(DefaultTInfo && "expected source information for type")(static_cast <bool> (DefaultTInfo && "expected source information for type"
) ? void (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 838, __extension__ __PRETTY_FUNCTION__))
;
839
840 // Check for unexpanded parameter packs.
841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842 UPPC_DefaultArgument))
843 return Param;
844
845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
848 return Param;
849 }
850
851 Param->setDefaultArgument(DefaultTInfo);
852 }
853
854 return Param;
855}
856
857/// \brief Check that the type of a non-type template parameter is
858/// well-formed.
859///
860/// \returns the (possibly-promoted) parameter type if valid;
861/// otherwise, produces a diagnostic and returns a NULL type.
862QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
871 }
872
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
874}
875
876QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
878 // We don't allow variably-modified types as the type of non-type template
879 // parameters.
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
882 << T;
883 return QualType();
884 }
885
886 // C++ [temp.param]p4:
887 //
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
890 //
891 // -- integral or enumeration type,
892 if (T->isIntegralOrEnumerationType() ||
893 // -- pointer to object or pointer to function,
894 T->isPointerType() ||
895 // -- reference to object or reference to function,
896 T->isReferenceType() ||
897 // -- pointer to member,
898 T->isMemberPointerType() ||
899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
909 }
910
911 // C++ [temp.param]p8:
912 //
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
918
919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
920 << T;
921
922 return QualType();
923}
924
925NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
926 unsigned Depth,
927 unsigned Position,
928 SourceLocation EqualLoc,
929 Expr *Default) {
930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
931
932 // Check that we have valid decl-specifiers specified.
933 auto CheckValidDeclSpecifiers = [this, &D] {
934 // C++ [temp.param]
935 // p1
936 // template-parameter:
937 // ...
938 // parameter-declaration
939 // p2
940 // ... A storage class shall not be specified in a template-parameter
941 // declaration.
942 // [dcl.typedef]p1:
943 // The typedef specifier [...] shall not be used in the decl-specifier-seq
944 // of a parameter-declaration
945 const DeclSpec &DS = D.getDeclSpec();
946 auto EmitDiag = [this](SourceLocation Loc) {
947 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
948 << FixItHint::CreateRemoval(Loc);
949 };
950 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
951 EmitDiag(DS.getStorageClassSpecLoc());
952
953 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
954 EmitDiag(DS.getThreadStorageClassSpecLoc());
955
956 // [dcl.inline]p1:
957 // The inline specifier can be applied only to the declaration or
958 // definition of a variable or function.
959
960 if (DS.isInlineSpecified())
961 EmitDiag(DS.getInlineSpecLoc());
962
963 // [dcl.constexpr]p1:
964 // The constexpr specifier shall be applied only to the definition of a
965 // variable or variable template or the declaration of a function or
966 // function template.
967
968 if (DS.isConstexprSpecified())
969 EmitDiag(DS.getConstexprSpecLoc());
970
971 // [dcl.fct.spec]p1:
972 // Function-specifiers can be used only in function declarations.
973
974 if (DS.isVirtualSpecified())
975 EmitDiag(DS.getVirtualSpecLoc());
976
977 if (DS.isExplicitSpecified())
978 EmitDiag(DS.getExplicitSpecLoc());
979
980 if (DS.isNoreturnSpecified())
981 EmitDiag(DS.getNoreturnSpecLoc());
982 };
983
984 CheckValidDeclSpecifiers();
985
986 if (TInfo->getType()->isUndeducedType()) {
987 Diag(D.getIdentifierLoc(),
988 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
989 << QualType(TInfo->getType()->getContainedAutoType(), 0);
990 }
991
992 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Non-type template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 993, __extension__ __PRETTY_FUNCTION__))
993 "Non-type template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Non-type template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 993, __extension__ __PRETTY_FUNCTION__))
;
994 bool Invalid = false;
995
996 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
997 if (T.isNull()) {
998 T = Context.IntTy; // Recover with an 'int' type.
999 Invalid = true;
1000 }
1001
1002 IdentifierInfo *ParamName = D.getIdentifier();
1003 bool IsParameterPack = D.hasEllipsis();
1004 NonTypeTemplateParmDecl *Param
1005 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1006 D.getLocStart(),
1007 D.getIdentifierLoc(),
1008 Depth, Position, ParamName, T,
1009 IsParameterPack, TInfo);
1010 Param->setAccess(AS_public);
1011
1012 if (Invalid)
1013 Param->setInvalidDecl();
1014
1015 if (ParamName) {
1016 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1017 ParamName);
1018
1019 // Add the template parameter into the current scope.
1020 S->AddDecl(Param);
1021 IdResolver.AddDecl(Param);
1022 }
1023
1024 // C++0x [temp.param]p9:
1025 // A default template-argument may be specified for any kind of
1026 // template-parameter that is not a template parameter pack.
1027 if (Default && IsParameterPack) {
1028 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029 Default = nullptr;
1030 }
1031
1032 // Check the well-formedness of the default template argument, if provided.
1033 if (Default) {
1034 // Check for unexpanded parameter packs.
1035 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1036 return Param;
1037
1038 TemplateArgument Converted;
1039 ExprResult DefaultRes =
1040 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1041 if (DefaultRes.isInvalid()) {
1042 Param->setInvalidDecl();
1043 return Param;
1044 }
1045 Default = DefaultRes.get();
1046
1047 Param->setDefaultArgument(Default);
1048 }
1049
1050 return Param;
1051}
1052
1053/// ActOnTemplateTemplateParameter - Called when a C++ template template
1054/// parameter (e.g. T in template <template \<typename> class T> class array)
1055/// has been parsed. S is the current scope.
1056NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1057 SourceLocation TmpLoc,
1058 TemplateParameterList *Params,
1059 SourceLocation EllipsisLoc,
1060 IdentifierInfo *Name,
1061 SourceLocation NameLoc,
1062 unsigned Depth,
1063 unsigned Position,
1064 SourceLocation EqualLoc,
1065 ParsedTemplateArgument Default) {
1066 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Template template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1067, __extension__ __PRETTY_FUNCTION__))
1067 "Template template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Template template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1067, __extension__ __PRETTY_FUNCTION__))
;
1068
1069 // Construct the parameter object.
1070 bool IsParameterPack = EllipsisLoc.isValid();
1071 TemplateTemplateParmDecl *Param =
1072 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1073 NameLoc.isInvalid()? TmpLoc : NameLoc,
1074 Depth, Position, IsParameterPack,
1075 Name, Params);
1076 Param->setAccess(AS_public);
1077
1078 // If the template template parameter has a name, then link the identifier
1079 // into the scope and lookup mechanisms.
1080 if (Name) {
1081 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1082
1083 S->AddDecl(Param);
1084 IdResolver.AddDecl(Param);
1085 }
1086
1087 if (Params->size() == 0) {
1088 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1089 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1090 Param->setInvalidDecl();
1091 }
1092
1093 // C++0x [temp.param]p9:
1094 // A default template-argument may be specified for any kind of
1095 // template-parameter that is not a template parameter pack.
1096 if (IsParameterPack && !Default.isInvalid()) {
1097 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1098 Default = ParsedTemplateArgument();
1099 }
1100
1101 if (!Default.isInvalid()) {
1102 // Check only that we have a template template argument. We don't want to
1103 // try to check well-formedness now, because our template template parameter
1104 // might have dependent types in its template parameters, which we wouldn't
1105 // be able to match now.
1106 //
1107 // If none of the template template parameter's template arguments mention
1108 // other template parameters, we could actually perform more checking here.
1109 // However, it isn't worth doing.
1110 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1111 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1112 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1113 << DefaultArg.getSourceRange();
1114 return Param;
1115 }
1116
1117 // Check for unexpanded parameter packs.
1118 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1119 DefaultArg.getArgument().getAsTemplate(),
1120 UPPC_DefaultArgument))
1121 return Param;
1122
1123 Param->setDefaultArgument(Context, DefaultArg);
1124 }
1125
1126 return Param;
1127}
1128
1129/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1130/// constrained by RequiresClause, that contains the template parameters in
1131/// Params.
1132TemplateParameterList *
1133Sema::ActOnTemplateParameterList(unsigned Depth,
1134 SourceLocation ExportLoc,
1135 SourceLocation TemplateLoc,
1136 SourceLocation LAngleLoc,
1137 ArrayRef<NamedDecl *> Params,
1138 SourceLocation RAngleLoc,
1139 Expr *RequiresClause) {
1140 if (ExportLoc.isValid())
1141 Diag(ExportLoc, diag::warn_template_export_unsupported);
1142
1143 return TemplateParameterList::Create(
1144 Context, TemplateLoc, LAngleLoc,
1145 llvm::makeArrayRef(Params.data(), Params.size()),
1146 RAngleLoc, RequiresClause);
1147}
1148
1149static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1150 if (SS.isSet())
1151 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1152}
1153
1154DeclResult
1155Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1156 SourceLocation KWLoc, CXXScopeSpec &SS,
1157 IdentifierInfo *Name, SourceLocation NameLoc,
1158 AttributeList *Attr,
1159 TemplateParameterList *TemplateParams,
1160 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1161 SourceLocation FriendLoc,
1162 unsigned NumOuterTemplateParamLists,
1163 TemplateParameterList** OuterTemplateParamLists,
1164 SkipBodyInfo *SkipBody) {
1165 assert(TemplateParams && TemplateParams->size() > 0 &&(static_cast <bool> (TemplateParams && TemplateParams
->size() > 0 && "No template parameters") ? void
(0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1166, __extension__ __PRETTY_FUNCTION__))
1166 "No template parameters")(static_cast <bool> (TemplateParams && TemplateParams
->size() > 0 && "No template parameters") ? void
(0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1166, __extension__ __PRETTY_FUNCTION__))
;
1167 assert(TUK != TUK_Reference && "Can only declare or define class templates")(static_cast <bool> (TUK != TUK_Reference && "Can only declare or define class templates"
) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1167, __extension__ __PRETTY_FUNCTION__))
;
1168 bool Invalid = false;
1169
1170 // Check that we can declare a template here.
1171 if (CheckTemplateDeclScope(S, TemplateParams))
1172 return true;
1173
1174 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1175 assert(Kind != TTK_Enum && "can't build template of enumerated type")(static_cast <bool> (Kind != TTK_Enum && "can't build template of enumerated type"
) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1175, __extension__ __PRETTY_FUNCTION__))
;
1176
1177 // There is no such thing as an unnamed class template.
1178 if (!Name) {
1179 Diag(KWLoc, diag::err_template_unnamed_class);
1180 return true;
1181 }
1182
1183 // Find any previous declaration with this name. For a friend with no
1184 // scope explicitly specified, we only look for tag declarations (per
1185 // C++11 [basic.lookup.elab]p2).
1186 DeclContext *SemanticContext;
1187 LookupResult Previous(*this, Name, NameLoc,
1188 (SS.isEmpty() && TUK == TUK_Friend)
1189 ? LookupTagName : LookupOrdinaryName,
1190 forRedeclarationInCurContext());
1191 if (SS.isNotEmpty() && !SS.isInvalid()) {
1192 SemanticContext = computeDeclContext(SS, true);
1193 if (!SemanticContext) {
1194 // FIXME: Horrible, horrible hack! We can't currently represent this
1195 // in the AST, and historically we have just ignored such friend
1196 // class templates, so don't complain here.
1197 Diag(NameLoc, TUK == TUK_Friend
1198 ? diag::warn_template_qualified_friend_ignored
1199 : diag::err_template_qualified_declarator_no_match)
1200 << SS.getScopeRep() << SS.getRange();
1201 return TUK != TUK_Friend;
1202 }
1203
1204 if (RequireCompleteDeclContext(SS, SemanticContext))
1205 return true;
1206
1207 // If we're adding a template to a dependent context, we may need to
1208 // rebuilding some of the types used within the template parameter list,
1209 // now that we know what the current instantiation is.
1210 if (SemanticContext->isDependentContext()) {
1211 ContextRAII SavedContext(*this, SemanticContext);
1212 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1213 Invalid = true;
1214 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1215 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1216
1217 LookupQualifiedName(Previous, SemanticContext);
1218 } else {
1219 SemanticContext = CurContext;
1220
1221 // C++14 [class.mem]p14:
1222 // If T is the name of a class, then each of the following shall have a
1223 // name different from T:
1224 // -- every member template of class T
1225 if (TUK != TUK_Friend &&
1226 DiagnoseClassNameShadow(SemanticContext,
1227 DeclarationNameInfo(Name, NameLoc)))
1228 return true;
1229
1230 LookupName(Previous, S);
1231 }
1232
1233 if (Previous.isAmbiguous())
1234 return true;
1235
1236 NamedDecl *PrevDecl = nullptr;
1237 if (Previous.begin() != Previous.end())
1238 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1239
1240 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1241 // Maybe we will complain about the shadowed template parameter.
1242 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1243 // Just pretend that we didn't see the previous declaration.
1244 PrevDecl = nullptr;
1245 }
1246
1247 // If there is a previous declaration with the same name, check
1248 // whether this is a valid redeclaration.
1249 ClassTemplateDecl *PrevClassTemplate =
1250 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1251
1252 // We may have found the injected-class-name of a class template,
1253 // class template partial specialization, or class template specialization.
1254 // In these cases, grab the template that is being defined or specialized.
1255 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1256 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1257 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1258 PrevClassTemplate
1259 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1260 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1261 PrevClassTemplate
1262 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1263 ->getSpecializedTemplate();
1264 }
1265 }
1266
1267 if (TUK == TUK_Friend) {
1268 // C++ [namespace.memdef]p3:
1269 // [...] When looking for a prior declaration of a class or a function
1270 // declared as a friend, and when the name of the friend class or
1271 // function is neither a qualified name nor a template-id, scopes outside
1272 // the innermost enclosing namespace scope are not considered.
1273 if (!SS.isSet()) {
1274 DeclContext *OutermostContext = CurContext;
1275 while (!OutermostContext->isFileContext())
1276 OutermostContext = OutermostContext->getLookupParent();
1277
1278 if (PrevDecl &&
1279 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1280 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1281 SemanticContext = PrevDecl->getDeclContext();
1282 } else {
1283 // Declarations in outer scopes don't matter. However, the outermost
1284 // context we computed is the semantic context for our new
1285 // declaration.
1286 PrevDecl = PrevClassTemplate = nullptr;
1287 SemanticContext = OutermostContext;
1288
1289 // Check that the chosen semantic context doesn't already contain a
1290 // declaration of this name as a non-tag type.
1291 Previous.clear(LookupOrdinaryName);
1292 DeclContext *LookupContext = SemanticContext;
1293 while (LookupContext->isTransparentContext())
1294 LookupContext = LookupContext->getLookupParent();
1295 LookupQualifiedName(Previous, LookupContext);
1296
1297 if (Previous.isAmbiguous())
1298 return true;
1299
1300 if (Previous.begin() != Previous.end())
1301 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1302 }
1303 }
1304 } else if (PrevDecl &&
1305 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1306 S, SS.isValid()))
1307 PrevDecl = PrevClassTemplate = nullptr;
1308
1309 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1310 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1311 if (SS.isEmpty() &&
1312 !(PrevClassTemplate &&
1313 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1314 SemanticContext->getRedeclContext()))) {
1315 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1316 Diag(Shadow->getTargetDecl()->getLocation(),
1317 diag::note_using_decl_target);
1318 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1319 // Recover by ignoring the old declaration.
1320 PrevDecl = PrevClassTemplate = nullptr;
1321 }
1322 }
1323
1324 // TODO Memory management; associated constraints are not always stored.
1325 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1326
1327 if (PrevClassTemplate) {
1328 // Ensure that the template parameter lists are compatible. Skip this check
1329 // for a friend in a dependent context: the template parameter list itself
1330 // could be dependent.
1331 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1332 !TemplateParameterListsAreEqual(TemplateParams,
1333 PrevClassTemplate->getTemplateParameters(),
1334 /*Complain=*/true,
1335 TPL_TemplateMatch))
1336 return true;
1337
1338 // Check for matching associated constraints on redeclarations.
1339 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1340 const bool RedeclACMismatch = [&] {
1341 if (!(CurAC || PrevAC))
1342 return false; // Nothing to check; no mismatch.
1343 if (CurAC && PrevAC) {
1344 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1345 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1346 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1347 if (CurACInfo == PrevACInfo)
1348 return false; // All good; no mismatch.
1349 }
1350 return true;
1351 }();
1352
1353 if (RedeclACMismatch) {
1354 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1355 diag::err_template_different_associated_constraints);
1356 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1357 diag::note_template_prev_declaration) << /*declaration*/0;
1358 return true;
1359 }
1360
1361 // C++ [temp.class]p4:
1362 // In a redeclaration, partial specialization, explicit
1363 // specialization or explicit instantiation of a class template,
1364 // the class-key shall agree in kind with the original class
1365 // template declaration (7.1.5.3).
1366 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1367 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1368 TUK == TUK_Definition, KWLoc, Name)) {
1369 Diag(KWLoc, diag::err_use_with_wrong_tag)
1370 << Name
1371 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1372 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1373 Kind = PrevRecordDecl->getTagKind();
1374 }
1375
1376 // Check for redefinition of this class template.
1377 if (TUK == TUK_Definition) {
1378 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1379 // If we have a prior definition that is not visible, treat this as
1380 // simply making that previous definition visible.
1381 NamedDecl *Hidden = nullptr;
1382 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1383 SkipBody->ShouldSkip = true;
1384 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1385 assert(Tmpl && "original definition of a class template is not a "(static_cast <bool> (Tmpl && "original definition of a class template is not a "
"class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1386, __extension__ __PRETTY_FUNCTION__))
1386 "class template?")(static_cast <bool> (Tmpl && "original definition of a class template is not a "
"class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1386, __extension__ __PRETTY_FUNCTION__))
;
1387 makeMergedDefinitionVisible(Hidden);
1388 makeMergedDefinitionVisible(Tmpl);
1389 return Def;
1390 }
1391
1392 Diag(NameLoc, diag::err_redefinition) << Name;
1393 Diag(Def->getLocation(), diag::note_previous_definition);
1394 // FIXME: Would it make sense to try to "forget" the previous
1395 // definition, as part of error recovery?
1396 return true;
1397 }
1398 }
1399 } else if (PrevDecl) {
1400 // C++ [temp]p5:
1401 // A class template shall not have the same name as any other
1402 // template, class, function, object, enumeration, enumerator,
1403 // namespace, or type in the same scope (3.3), except as specified
1404 // in (14.5.4).
1405 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1406 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1407 return true;
1408 }
1409
1410 // Check the template parameter list of this declaration, possibly
1411 // merging in the template parameter list from the previous class
1412 // template declaration. Skip this check for a friend in a dependent
1413 // context, because the template parameter list might be dependent.
1414 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1415 CheckTemplateParameterList(
1416 TemplateParams,
1417 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1418 : nullptr,
1419 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1420 SemanticContext->isDependentContext())
1421 ? TPC_ClassTemplateMember
1422 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1423 : TPC_ClassTemplate))
1424 Invalid = true;
1425
1426 if (SS.isSet()) {
1427 // If the name of the template was qualified, we must be defining the
1428 // template out-of-line.
1429 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1430 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1431 : diag::err_member_decl_does_not_match)
1432 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1433 Invalid = true;
1434 }
1435 }
1436
1437 // If this is a templated friend in a dependent context we should not put it
1438 // on the redecl chain. In some cases, the templated friend can be the most
1439 // recent declaration tricking the template instantiator to make substitutions
1440 // there.
1441 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1442 bool ShouldAddRedecl
1443 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1444
1445 CXXRecordDecl *NewClass =
1446 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1447 PrevClassTemplate && ShouldAddRedecl ?
1448 PrevClassTemplate->getTemplatedDecl() : nullptr,
1449 /*DelayTypeCreation=*/true);
1450 SetNestedNameSpecifier(NewClass, SS);
1451 if (NumOuterTemplateParamLists > 0)
1452 NewClass->setTemplateParameterListsInfo(
1453 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1454 NumOuterTemplateParamLists));
1455
1456 // Add alignment attributes if necessary; these attributes are checked when
1457 // the ASTContext lays out the structure.
1458 if (TUK == TUK_Definition) {
1459 AddAlignmentAttributesForRecord(NewClass);
1460 AddMsStructLayoutForRecord(NewClass);
1461 }
1462
1463 // Attach the associated constraints when the declaration will not be part of
1464 // a decl chain.
1465 Expr *const ACtoAttach =
1466 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1467
1468 ClassTemplateDecl *NewTemplate
1469 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1470 DeclarationName(Name), TemplateParams,
1471 NewClass, ACtoAttach);
1472
1473 if (ShouldAddRedecl)
1474 NewTemplate->setPreviousDecl(PrevClassTemplate);
1475
1476 NewClass->setDescribedClassTemplate(NewTemplate);
1477
1478 if (ModulePrivateLoc.isValid())
1479 NewTemplate->setModulePrivate();
1480
1481 // Build the type for the class template declaration now.
1482 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1483 T = Context.getInjectedClassNameType(NewClass, T);
1484 assert(T->isDependentType() && "Class template type is not dependent?")(static_cast <bool> (T->isDependentType() &&
"Class template type is not dependent?") ? void (0) : __assert_fail
("T->isDependentType() && \"Class template type is not dependent?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1484, __extension__ __PRETTY_FUNCTION__))
;
1485 (void)T;
1486
1487 // If we are providing an explicit specialization of a member that is a
1488 // class template, make a note of that.
1489 if (PrevClassTemplate &&
1490 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1491 PrevClassTemplate->setMemberSpecialization();
1492
1493 // Set the access specifier.
1494 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1495 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1496
1497 // Set the lexical context of these templates
1498 NewClass->setLexicalDeclContext(CurContext);
1499 NewTemplate->setLexicalDeclContext(CurContext);
1500
1501 if (TUK == TUK_Definition)
1502 NewClass->startDefinition();
1503
1504 if (Attr)
1505 ProcessDeclAttributeList(S, NewClass, Attr);
1506
1507 if (PrevClassTemplate)
1508 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1509
1510 AddPushedVisibilityAttribute(NewClass);
1511
1512 if (TUK != TUK_Friend) {
1513 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1514 Scope *Outer = S;
1515 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1516 Outer = Outer->getParent();
1517 PushOnScopeChains(NewTemplate, Outer);
1518 } else {
1519 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1520 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1521 NewClass->setAccess(PrevClassTemplate->getAccess());
1522 }
1523
1524 NewTemplate->setObjectOfFriendDecl();
1525
1526 // Friend templates are visible in fairly strange ways.
1527 if (!CurContext->isDependentContext()) {
1528 DeclContext *DC = SemanticContext->getRedeclContext();
1529 DC->makeDeclVisibleInContext(NewTemplate);
1530 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1531 PushOnScopeChains(NewTemplate, EnclosingScope,
1532 /* AddToContext = */ false);
1533 }
1534
1535 FriendDecl *Friend = FriendDecl::Create(
1536 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1537 Friend->setAccess(AS_public);
1538 CurContext->addDecl(Friend);
1539 }
1540
1541 if (PrevClassTemplate)
1542 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1543
1544 if (Invalid) {
1545 NewTemplate->setInvalidDecl();
1546 NewClass->setInvalidDecl();
1547 }
1548
1549 ActOnDocumentableDecl(NewTemplate);
1550
1551 return NewTemplate;
1552}
1553
1554namespace {
1555/// Transform to convert portions of a constructor declaration into the
1556/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1557struct ConvertConstructorToDeductionGuideTransform {
1558 ConvertConstructorToDeductionGuideTransform(Sema &S,
1559 ClassTemplateDecl *Template)
1560 : SemaRef(S), Template(Template) {}
1561
1562 Sema &SemaRef;
1563 ClassTemplateDecl *Template;
1564
1565 DeclContext *DC = Template->getDeclContext();
1566 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1567 DeclarationName DeductionGuideName =
1568 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1569
1570 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1571
1572 // Index adjustment to apply to convert depth-1 template parameters into
1573 // depth-0 template parameters.
1574 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1575
1576 /// Transform a constructor declaration into a deduction guide.
1577 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1578 CXXConstructorDecl *CD) {
1579 SmallVector<TemplateArgument, 16> SubstArgs;
1580
1581 LocalInstantiationScope Scope(SemaRef);
1582
1583 // C++ [over.match.class.deduct]p1:
1584 // -- For each constructor of the class template designated by the
1585 // template-name, a function template with the following properties:
1586
1587 // -- The template parameters are the template parameters of the class
1588 // template followed by the template parameters (including default
1589 // template arguments) of the constructor, if any.
1590 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1591 if (FTD) {
1592 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1593 SmallVector<NamedDecl *, 16> AllParams;
1594 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1595 AllParams.insert(AllParams.begin(),
1596 TemplateParams->begin(), TemplateParams->end());
1597 SubstArgs.reserve(InnerParams->size());
1598
1599 // Later template parameters could refer to earlier ones, so build up
1600 // a list of substituted template arguments as we go.
1601 for (NamedDecl *Param : *InnerParams) {
1602 MultiLevelTemplateArgumentList Args;
1603 Args.addOuterTemplateArguments(SubstArgs);
1604 Args.addOuterRetainedLevel();
1605 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1606 if (!NewParam)
1607 return nullptr;
1608 AllParams.push_back(NewParam);
1609 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1610 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1611 }
1612 TemplateParams = TemplateParameterList::Create(
1613 SemaRef.Context, InnerParams->getTemplateLoc(),
1614 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1615 /*FIXME: RequiresClause*/ nullptr);
1616 }
1617
1618 // If we built a new template-parameter-list, track that we need to
1619 // substitute references to the old parameters into references to the
1620 // new ones.
1621 MultiLevelTemplateArgumentList Args;
1622 if (FTD) {
1623 Args.addOuterTemplateArguments(SubstArgs);
1624 Args.addOuterRetainedLevel();
1625 }
1626
1627 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1628 .getAsAdjusted<FunctionProtoTypeLoc>();
1629 assert(FPTL && "no prototype for constructor declaration")(static_cast <bool> (FPTL && "no prototype for constructor declaration"
) ? void (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1629, __extension__ __PRETTY_FUNCTION__))
;
1630
1631 // Transform the type of the function, adjusting the return type and
1632 // replacing references to the old parameters with references to the
1633 // new ones.
1634 TypeLocBuilder TLB;
1635 SmallVector<ParmVarDecl*, 8> Params;
1636 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1637 if (NewType.isNull())
1638 return nullptr;
1639 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1640
1641 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1642 CD->getLocStart(), CD->getLocation(),
1643 CD->getLocEnd());
1644 }
1645
1646 /// Build a deduction guide with the specified parameter types.
1647 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1648 SourceLocation Loc = Template->getLocation();
1649
1650 // Build the requested type.
1651 FunctionProtoType::ExtProtoInfo EPI;
1652 EPI.HasTrailingReturn = true;
1653 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1654 DeductionGuideName, EPI);
1655 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1656
1657 FunctionProtoTypeLoc FPTL =
1658 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1659
1660 // Build the parameters, needed during deduction / substitution.
1661 SmallVector<ParmVarDecl*, 4> Params;
1662 for (auto T : ParamTypes) {
1663 ParmVarDecl *NewParam = ParmVarDecl::Create(
1664 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1665 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1666 NewParam->setScopeInfo(0, Params.size());
1667 FPTL.setParam(Params.size(), NewParam);
1668 Params.push_back(NewParam);
1669 }
1670
1671 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1672 Loc, Loc, Loc);
1673 }
1674
1675private:
1676 /// Transform a constructor template parameter into a deduction guide template
1677 /// parameter, rebuilding any internal references to earlier parameters and
1678 /// renumbering as we go.
1679 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1680 MultiLevelTemplateArgumentList &Args) {
1681 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1682 // TemplateTypeParmDecl's index cannot be changed after creation, so
1683 // substitute it directly.
1684 auto *NewTTP = TemplateTypeParmDecl::Create(
1685 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1686 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1687 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1688 TTP->isParameterPack());
1689 if (TTP->hasDefaultArgument()) {
1690 TypeSourceInfo *InstantiatedDefaultArg =
1691 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1692 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1693 if (InstantiatedDefaultArg)
1694 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1695 }
1696 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1697 NewTTP);
1698 return NewTTP;
1699 }
1700
1701 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1702 return transformTemplateParameterImpl(TTP, Args);
1703
1704 return transformTemplateParameterImpl(
1705 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1706 }
1707 template<typename TemplateParmDecl>
1708 TemplateParmDecl *
1709 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1710 MultiLevelTemplateArgumentList &Args) {
1711 // Ask the template instantiator to do the heavy lifting for us, then adjust
1712 // the index of the parameter once it's done.
1713 auto *NewParam =
1714 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1715 assert(NewParam->getDepth() == 0 && "unexpected template param depth")(static_cast <bool> (NewParam->getDepth() == 0 &&
"unexpected template param depth") ? void (0) : __assert_fail
("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1715, __extension__ __PRETTY_FUNCTION__))
;
1716 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1717 return NewParam;
1718 }
1719
1720 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1721 FunctionProtoTypeLoc TL,
1722 SmallVectorImpl<ParmVarDecl*> &Params,
1723 MultiLevelTemplateArgumentList &Args) {
1724 SmallVector<QualType, 4> ParamTypes;
1725 const FunctionProtoType *T = TL.getTypePtr();
1726
1727 // -- The types of the function parameters are those of the constructor.
1728 for (auto *OldParam : TL.getParams()) {
1729 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1730 if (!NewParam)
1731 return QualType();
1732 ParamTypes.push_back(NewParam->getType());
1733 Params.push_back(NewParam);
1734 }
1735
1736 // -- The return type is the class template specialization designated by
1737 // the template-name and template arguments corresponding to the
1738 // template parameters obtained from the class template.
1739 //
1740 // We use the injected-class-name type of the primary template instead.
1741 // This has the convenient property that it is different from any type that
1742 // the user can write in a deduction-guide (because they cannot enter the
1743 // context of the template), so implicit deduction guides can never collide
1744 // with explicit ones.
1745 QualType ReturnType = DeducedType;
1746 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1747
1748 // Resolving a wording defect, we also inherit the variadicness of the
1749 // constructor.
1750 FunctionProtoType::ExtProtoInfo EPI;
1751 EPI.Variadic = T->isVariadic();
1752 EPI.HasTrailingReturn = true;
1753
1754 QualType Result = SemaRef.BuildFunctionType(
1755 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1756 if (Result.isNull())
1757 return QualType();
1758
1759 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1760 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1761 NewTL.setLParenLoc(TL.getLParenLoc());
1762 NewTL.setRParenLoc(TL.getRParenLoc());
1763 NewTL.setExceptionSpecRange(SourceRange());
1764 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1765 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1766 NewTL.setParam(I, Params[I]);
1767
1768 return Result;
1769 }
1770
1771 ParmVarDecl *
1772 transformFunctionTypeParam(ParmVarDecl *OldParam,
1773 MultiLevelTemplateArgumentList &Args) {
1774 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1775 TypeSourceInfo *NewDI;
1776 if (!Args.getNumLevels())
1777 NewDI = OldDI;
1778 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1779 // Expand out the one and only element in each inner pack.
1780 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1781 NewDI =
1782 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1783 OldParam->getLocation(), OldParam->getDeclName());
1784 if (!NewDI) return nullptr;
1785 NewDI =
1786 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1787 PackTL.getTypePtr()->getNumExpansions());
1788 } else
1789 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1790 OldParam->getDeclName());
1791 if (!NewDI)
1792 return nullptr;
1793
1794 // Canonicalize the type. This (for instance) replaces references to
1795 // typedef members of the current instantiations with the definitions of
1796 // those typedefs, avoiding triggering instantiation of the deduced type
1797 // during deduction.
1798 // FIXME: It would be preferable to retain type sugar and source
1799 // information here (and handle this in substitution instead).
1800 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1801 SemaRef.Context.getCanonicalType(NewDI->getType()),
1802 OldParam->getLocation());
1803
1804 // Resolving a wording defect, we also inherit default arguments from the
1805 // constructor.
1806 ExprResult NewDefArg;
1807 if (OldParam->hasDefaultArg()) {
1808 NewDefArg = Args.getNumLevels()
1809 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1810 : OldParam->getDefaultArg();
1811 if (NewDefArg.isInvalid())
1812 return nullptr;
1813 }
1814
1815 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1816 OldParam->getInnerLocStart(),
1817 OldParam->getLocation(),
1818 OldParam->getIdentifier(),
1819 NewDI->getType(),
1820 NewDI,
1821 OldParam->getStorageClass(),
1822 NewDefArg.get());
1823 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1824 OldParam->getFunctionScopeIndex());
1825 return NewParam;
1826 }
1827
1828 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1829 bool Explicit, TypeSourceInfo *TInfo,
1830 SourceLocation LocStart, SourceLocation Loc,
1831 SourceLocation LocEnd) {
1832 DeclarationNameInfo Name(DeductionGuideName, Loc);
1833 ArrayRef<ParmVarDecl *> Params =
1834 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1835
1836 // Build the implicit deduction guide template.
1837 auto *Guide =
1838 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1839 Name, TInfo->getType(), TInfo, LocEnd);
1840 Guide->setImplicit();
1841 Guide->setParams(Params);
1842
1843 for (auto *Param : Params)
1844 Param->setDeclContext(Guide);
1845
1846 auto *GuideTemplate = FunctionTemplateDecl::Create(
1847 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1848 GuideTemplate->setImplicit();
1849 Guide->setDescribedFunctionTemplate(GuideTemplate);
1850
1851 if (isa<CXXRecordDecl>(DC)) {
1852 Guide->setAccess(AS_public);
1853 GuideTemplate->setAccess(AS_public);
1854 }
1855
1856 DC->addDecl(GuideTemplate);
1857 return GuideTemplate;
1858 }
1859};
1860}
1861
1862void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1863 SourceLocation Loc) {
1864 DeclContext *DC = Template->getDeclContext();
1865 if (DC->isDependentContext())
1866 return;
1867
1868 ConvertConstructorToDeductionGuideTransform Transform(
1869 *this, cast<ClassTemplateDecl>(Template));
1870 if (!isCompleteType(Loc, Transform.DeducedType))
1871 return;
1872
1873 // Check whether we've already declared deduction guides for this template.
1874 // FIXME: Consider storing a flag on the template to indicate this.
1875 auto Existing = DC->lookup(Transform.DeductionGuideName);
1876 for (auto *D : Existing)
1877 if (D->isImplicit())
1878 return;
1879
1880 // In case we were expanding a pack when we attempted to declare deduction
1881 // guides, turn off pack expansion for everything we're about to do.
1882 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1883 // Create a template instantiation record to track the "instantiation" of
1884 // constructors into deduction guides.
1885 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1886 // this substitution process actually fail?
1887 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1888
1889 // Convert declared constructors into deduction guide templates.
1890 // FIXME: Skip constructors for which deduction must necessarily fail (those
1891 // for which some class template parameter without a default argument never
1892 // appears in a deduced context).
1893 bool AddedAny = false;
1894 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1895 D = D->getUnderlyingDecl();
1896 if (D->isInvalidDecl() || D->isImplicit())
1897 continue;
1898 D = cast<NamedDecl>(D->getCanonicalDecl());
1899
1900 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1901 auto *CD =
1902 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1903 // Class-scope explicit specializations (MS extension) do not result in
1904 // deduction guides.
1905 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1906 continue;
1907
1908 Transform.transformConstructor(FTD, CD);
1909 AddedAny = true;
1910 }
1911
1912 // C++17 [over.match.class.deduct]
1913 // -- If C is not defined or does not declare any constructors, an
1914 // additional function template derived as above from a hypothetical
1915 // constructor C().
1916 if (!AddedAny)
1917 Transform.buildSimpleDeductionGuide(None);
1918
1919 // -- An additional function template derived as above from a hypothetical
1920 // constructor C(C), called the copy deduction candidate.
1921 cast<CXXDeductionGuideDecl>(
1922 cast<FunctionTemplateDecl>(
1923 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1924 ->getTemplatedDecl())
1925 ->setIsCopyDeductionCandidate();
1926}
1927
1928/// \brief Diagnose the presence of a default template argument on a
1929/// template parameter, which is ill-formed in certain contexts.
1930///
1931/// \returns true if the default template argument should be dropped.
1932static bool DiagnoseDefaultTemplateArgument(Sema &S,
1933 Sema::TemplateParamListContext TPC,
1934 SourceLocation ParamLoc,
1935 SourceRange DefArgRange) {
1936 switch (TPC) {
1937 case Sema::TPC_ClassTemplate:
1938 case Sema::TPC_VarTemplate:
1939 case Sema::TPC_TypeAliasTemplate:
1940 return false;
1941
1942 case Sema::TPC_FunctionTemplate:
1943 case Sema::TPC_FriendFunctionTemplateDefinition:
1944 // C++ [temp.param]p9:
1945 // A default template-argument shall not be specified in a
1946 // function template declaration or a function template
1947 // definition [...]
1948 // If a friend function template declaration specifies a default
1949 // template-argument, that declaration shall be a definition and shall be
1950 // the only declaration of the function template in the translation unit.
1951 // (C++98/03 doesn't have this wording; see DR226).
1952 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1953 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1954 : diag::ext_template_parameter_default_in_function_template)
1955 << DefArgRange;
1956 return false;
1957
1958 case Sema::TPC_ClassTemplateMember:
1959 // C++0x [temp.param]p9:
1960 // A default template-argument shall not be specified in the
1961 // template-parameter-lists of the definition of a member of a
1962 // class template that appears outside of the member's class.
1963 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1964 << DefArgRange;
1965 return true;
1966
1967 case Sema::TPC_FriendClassTemplate:
1968 case Sema::TPC_FriendFunctionTemplate:
1969 // C++ [temp.param]p9:
1970 // A default template-argument shall not be specified in a
1971 // friend template declaration.
1972 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1973 << DefArgRange;
1974 return true;
1975
1976 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1977 // for friend function templates if there is only a single
1978 // declaration (and it is a definition). Strange!
1979 }
1980
1981 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1981)
;
1982}
1983
1984/// \brief Check for unexpanded parameter packs within the template parameters
1985/// of a template template parameter, recursively.
1986static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1987 TemplateTemplateParmDecl *TTP) {
1988 // A template template parameter which is a parameter pack is also a pack
1989 // expansion.
1990 if (TTP->isParameterPack())
1991 return false;
1992
1993 TemplateParameterList *Params = TTP->getTemplateParameters();
1994 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1995 NamedDecl *P = Params->getParam(I);
1996 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1997 if (!NTTP->isParameterPack() &&
1998 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1999 NTTP->getTypeSourceInfo(),
2000 Sema::UPPC_NonTypeTemplateParameterType))
2001 return true;
2002
2003 continue;
2004 }
2005
2006 if (TemplateTemplateParmDecl *InnerTTP
2007 = dyn_cast<TemplateTemplateParmDecl>(P))
2008 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2009 return true;
2010 }
2011
2012 return false;
2013}
2014
2015/// \brief Checks the validity of a template parameter list, possibly
2016/// considering the template parameter list from a previous
2017/// declaration.
2018///
2019/// If an "old" template parameter list is provided, it must be
2020/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2021/// template parameter list.
2022///
2023/// \param NewParams Template parameter list for a new template
2024/// declaration. This template parameter list will be updated with any
2025/// default arguments that are carried through from the previous
2026/// template parameter list.
2027///
2028/// \param OldParams If provided, template parameter list from a
2029/// previous declaration of the same template. Default template
2030/// arguments will be merged from the old template parameter list to
2031/// the new template parameter list.
2032///
2033/// \param TPC Describes the context in which we are checking the given
2034/// template parameter list.
2035///
2036/// \returns true if an error occurred, false otherwise.
2037bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2038 TemplateParameterList *OldParams,
2039 TemplateParamListContext TPC) {
2040 bool Invalid = false;
2041
2042 // C++ [temp.param]p10:
2043 // The set of default template-arguments available for use with a
2044 // template declaration or definition is obtained by merging the
2045 // default arguments from the definition (if in scope) and all
2046 // declarations in scope in the same way default function
2047 // arguments are (8.3.6).
2048 bool SawDefaultArgument = false;
2049 SourceLocation PreviousDefaultArgLoc;
2050
2051 // Dummy initialization to avoid warnings.
2052 TemplateParameterList::iterator OldParam = NewParams->end();
2053 if (OldParams)
2054 OldParam = OldParams->begin();
2055
2056 bool RemoveDefaultArguments = false;
2057 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2058 NewParamEnd = NewParams->end();
2059 NewParam != NewParamEnd; ++NewParam) {
2060 // Variables used to diagnose redundant default arguments
2061 bool RedundantDefaultArg = false;
2062 SourceLocation OldDefaultLoc;
2063 SourceLocation NewDefaultLoc;
2064
2065 // Variable used to diagnose missing default arguments
2066 bool MissingDefaultArg = false;
2067
2068 // Variable used to diagnose non-final parameter packs
2069 bool SawParameterPack = false;
2070
2071 if (TemplateTypeParmDecl *NewTypeParm
2072 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2073 // Check the presence of a default argument here.
2074 if (NewTypeParm->hasDefaultArgument() &&
2075 DiagnoseDefaultTemplateArgument(*this, TPC,
2076 NewTypeParm->getLocation(),
2077 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2078 .getSourceRange()))
2079 NewTypeParm->removeDefaultArgument();
2080
2081 // Merge default arguments for template type parameters.
2082 TemplateTypeParmDecl *OldTypeParm
2083 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2084 if (NewTypeParm->isParameterPack()) {
2085 assert(!NewTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2086, __extension__ __PRETTY_FUNCTION__))
2086 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2086, __extension__ __PRETTY_FUNCTION__))
;
2087 SawParameterPack = true;
2088 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2089 NewTypeParm->hasDefaultArgument()) {
2090 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2091 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2092 SawDefaultArgument = true;
2093 RedundantDefaultArg = true;
2094 PreviousDefaultArgLoc = NewDefaultLoc;
2095 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2096 // Merge the default argument from the old declaration to the
2097 // new declaration.
2098 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2099 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2100 } else if (NewTypeParm->hasDefaultArgument()) {
2101 SawDefaultArgument = true;
2102 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2103 } else if (SawDefaultArgument)
2104 MissingDefaultArg = true;
2105 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2106 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2107 // Check for unexpanded parameter packs.
2108 if (!NewNonTypeParm->isParameterPack() &&
2109 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2110 NewNonTypeParm->getTypeSourceInfo(),
2111 UPPC_NonTypeTemplateParameterType)) {
2112 Invalid = true;
2113 continue;
2114 }
2115
2116 // Check the presence of a default argument here.
2117 if (NewNonTypeParm->hasDefaultArgument() &&
2118 DiagnoseDefaultTemplateArgument(*this, TPC,
2119 NewNonTypeParm->getLocation(),
2120 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2121 NewNonTypeParm->removeDefaultArgument();
2122 }
2123
2124 // Merge default arguments for non-type template parameters
2125 NonTypeTemplateParmDecl *OldNonTypeParm
2126 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2127 if (NewNonTypeParm->isParameterPack()) {
2128 assert(!NewNonTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2129, __extension__ __PRETTY_FUNCTION__))
2129 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2129, __extension__ __PRETTY_FUNCTION__))
;
2130 if (!NewNonTypeParm->isPackExpansion())
2131 SawParameterPack = true;
2132 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2133 NewNonTypeParm->hasDefaultArgument()) {
2134 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2135 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2136 SawDefaultArgument = true;
2137 RedundantDefaultArg = true;
2138 PreviousDefaultArgLoc = NewDefaultLoc;
2139 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2140 // Merge the default argument from the old declaration to the
2141 // new declaration.
2142 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2143 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2144 } else if (NewNonTypeParm->hasDefaultArgument()) {
2145 SawDefaultArgument = true;
2146 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2147 } else if (SawDefaultArgument)
2148 MissingDefaultArg = true;
2149 } else {
2150 TemplateTemplateParmDecl *NewTemplateParm
2151 = cast<TemplateTemplateParmDecl>(*NewParam);
2152
2153 // Check for unexpanded parameter packs, recursively.
2154 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2155 Invalid = true;
2156 continue;
2157 }
2158
2159 // Check the presence of a default argument here.
2160 if (NewTemplateParm->hasDefaultArgument() &&
2161 DiagnoseDefaultTemplateArgument(*this, TPC,
2162 NewTemplateParm->getLocation(),
2163 NewTemplateParm->getDefaultArgument().getSourceRange()))
2164 NewTemplateParm->removeDefaultArgument();
2165
2166 // Merge default arguments for template template parameters
2167 TemplateTemplateParmDecl *OldTemplateParm
2168 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2169 if (NewTemplateParm->isParameterPack()) {
2170 assert(!NewTemplateParm->hasDefaultArgument() &&(static_cast <bool> (!NewTemplateParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2171, __extension__ __PRETTY_FUNCTION__))
2171 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTemplateParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2171, __extension__ __PRETTY_FUNCTION__))
;
2172 if (!NewTemplateParm->isPackExpansion())
2173 SawParameterPack = true;
2174 } else if (OldTemplateParm &&
2175 hasVisibleDefaultArgument(OldTemplateParm) &&
2176 NewTemplateParm->hasDefaultArgument()) {
2177 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2178 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2179 SawDefaultArgument = true;
2180 RedundantDefaultArg = true;
2181 PreviousDefaultArgLoc = NewDefaultLoc;
2182 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2183 // Merge the default argument from the old declaration to the
2184 // new declaration.
2185 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2186 PreviousDefaultArgLoc
2187 = OldTemplateParm->getDefaultArgument().getLocation();
2188 } else if (NewTemplateParm->hasDefaultArgument()) {
2189 SawDefaultArgument = true;
2190 PreviousDefaultArgLoc
2191 = NewTemplateParm->getDefaultArgument().getLocation();
2192 } else if (SawDefaultArgument)
2193 MissingDefaultArg = true;
2194 }
2195
2196 // C++11 [temp.param]p11:
2197 // If a template parameter of a primary class template or alias template
2198 // is a template parameter pack, it shall be the last template parameter.
2199 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2200 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2201 TPC == TPC_TypeAliasTemplate)) {
2202 Diag((*NewParam)->getLocation(),
2203 diag::err_template_param_pack_must_be_last_template_parameter);
2204 Invalid = true;
2205 }
2206
2207 if (RedundantDefaultArg) {
2208 // C++ [temp.param]p12:
2209 // A template-parameter shall not be given default arguments
2210 // by two different declarations in the same scope.
2211 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2212 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2213 Invalid = true;
2214 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2215 // C++ [temp.param]p11:
2216 // If a template-parameter of a class template has a default
2217 // template-argument, each subsequent template-parameter shall either
2218 // have a default template-argument supplied or be a template parameter
2219 // pack.
2220 Diag((*NewParam)->getLocation(),
2221 diag::err_template_param_default_arg_missing);
2222 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2223 Invalid = true;
2224 RemoveDefaultArguments = true;
2225 }
2226
2227 // If we have an old template parameter list that we're merging
2228 // in, move on to the next parameter.
2229 if (OldParams)
2230 ++OldParam;
2231 }
2232
2233 // We were missing some default arguments at the end of the list, so remove
2234 // all of the default arguments.
2235 if (RemoveDefaultArguments) {
2236 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2237 NewParamEnd = NewParams->end();
2238 NewParam != NewParamEnd; ++NewParam) {
2239 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2240 TTP->removeDefaultArgument();
2241 else if (NonTypeTemplateParmDecl *NTTP
2242 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2243 NTTP->removeDefaultArgument();
2244 else
2245 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2246 }
2247 }
2248
2249 return Invalid;
2250}
2251
2252namespace {
2253
2254/// A class which looks for a use of a certain level of template
2255/// parameter.
2256struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2257 typedef RecursiveASTVisitor<DependencyChecker> super;
2258
2259 unsigned Depth;
2260
2261 // Whether we're looking for a use of a template parameter that makes the
2262 // overall construct type-dependent / a dependent type. This is strictly
2263 // best-effort for now; we may fail to match at all for a dependent type
2264 // in some cases if this is set.
2265 bool IgnoreNonTypeDependent;
2266
2267 bool Match;
2268 SourceLocation MatchLoc;
2269
2270 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2271 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2272 Match(false) {}
2273
2274 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2275 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2276 NamedDecl *ND = Params->getParam(0);
2277 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2278 Depth = PD->getDepth();
2279 } else if (NonTypeTemplateParmDecl *PD =
2280 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2281 Depth = PD->getDepth();
2282 } else {
2283 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2284 }
2285 }
2286
2287 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2288 if (ParmDepth >= Depth) {
2289 Match = true;
2290 MatchLoc = Loc;
2291 return true;
2292 }
2293 return false;
2294 }
2295
2296 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2297 // Prune out non-type-dependent expressions if requested. This can
2298 // sometimes result in us failing to find a template parameter reference
2299 // (if a value-dependent expression creates a dependent type), but this
2300 // mode is best-effort only.
2301 if (auto *E = dyn_cast_or_null<Expr>(S))
2302 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2303 return true;
2304 return super::TraverseStmt(S, Q);
2305 }
2306
2307 bool TraverseTypeLoc(TypeLoc TL) {
2308 if (IgnoreNonTypeDependent && !TL.isNull() &&
2309 !TL.getType()->isDependentType())
2310 return true;
2311 return super::TraverseTypeLoc(TL);
2312 }
2313
2314 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2315 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2316 }
2317
2318 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2319 // For a best-effort search, keep looking until we find a location.
2320 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2321 }
2322
2323 bool TraverseTemplateName(TemplateName N) {
2324 if (TemplateTemplateParmDecl *PD =
2325 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2326 if (Matches(PD->getDepth()))
2327 return false;
2328 return super::TraverseTemplateName(N);
2329 }
2330
2331 bool VisitDeclRefExpr(DeclRefExpr *E) {
2332 if (NonTypeTemplateParmDecl *PD =
2333 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2334 if (Matches(PD->getDepth(), E->getExprLoc()))
2335 return false;
2336 return super::VisitDeclRefExpr(E);
2337 }
2338
2339 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2340 return TraverseType(T->getReplacementType());
2341 }
2342
2343 bool
2344 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2345 return TraverseTemplateArgument(T->getArgumentPack());
2346 }
2347
2348 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2349 return TraverseType(T->getInjectedSpecializationType());
2350 }
2351};
2352} // end anonymous namespace
2353
2354/// Determines whether a given type depends on the given parameter
2355/// list.
2356static bool
2357DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2358 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2359 Checker.TraverseType(T);
2360 return Checker.Match;
2361}
2362
2363// Find the source range corresponding to the named type in the given
2364// nested-name-specifier, if any.
2365static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2366 QualType T,
2367 const CXXScopeSpec &SS) {
2368 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2369 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2370 if (const Type *CurType = NNS->getAsType()) {
2371 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2372 return NNSLoc.getTypeLoc().getSourceRange();
2373 } else
2374 break;
2375
2376 NNSLoc = NNSLoc.getPrefix();
2377 }
2378
2379 return SourceRange();
2380}
2381
2382/// \brief Match the given template parameter lists to the given scope
2383/// specifier, returning the template parameter list that applies to the
2384/// name.
2385///
2386/// \param DeclStartLoc the start of the declaration that has a scope
2387/// specifier or a template parameter list.
2388///
2389/// \param DeclLoc The location of the declaration itself.
2390///
2391/// \param SS the scope specifier that will be matched to the given template
2392/// parameter lists. This scope specifier precedes a qualified name that is
2393/// being declared.
2394///
2395/// \param TemplateId The template-id following the scope specifier, if there
2396/// is one. Used to check for a missing 'template<>'.
2397///
2398/// \param ParamLists the template parameter lists, from the outermost to the
2399/// innermost template parameter lists.
2400///
2401/// \param IsFriend Whether to apply the slightly different rules for
2402/// matching template parameters to scope specifiers in friend
2403/// declarations.
2404///
2405/// \param IsMemberSpecialization will be set true if the scope specifier
2406/// denotes a fully-specialized type, and therefore this is a declaration of
2407/// a member specialization.
2408///
2409/// \returns the template parameter list, if any, that corresponds to the
2410/// name that is preceded by the scope specifier @p SS. This template
2411/// parameter list may have template parameters (if we're declaring a
2412/// template) or may have no template parameters (if we're declaring a
2413/// template specialization), or may be NULL (if what we're declaring isn't
2414/// itself a template).
2415TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2416 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2417 TemplateIdAnnotation *TemplateId,
2418 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2419 bool &IsMemberSpecialization, bool &Invalid) {
2420 IsMemberSpecialization = false;
2421 Invalid = false;
2422
2423 // The sequence of nested types to which we will match up the template
2424 // parameter lists. We first build this list by starting with the type named
2425 // by the nested-name-specifier and walking out until we run out of types.
2426 SmallVector<QualType, 4> NestedTypes;
2427 QualType T;
2428 if (SS.getScopeRep()) {
2429 if (CXXRecordDecl *Record
2430 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2431 T = Context.getTypeDeclType(Record);
2432 else
2433 T = QualType(SS.getScopeRep()->getAsType(), 0);
2434 }
2435
2436 // If we found an explicit specialization that prevents us from needing
2437 // 'template<>' headers, this will be set to the location of that
2438 // explicit specialization.
2439 SourceLocation ExplicitSpecLoc;
2440
2441 while (!T.isNull()) {
2442 NestedTypes.push_back(T);
2443
2444 // Retrieve the parent of a record type.
2445 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2446 // If this type is an explicit specialization, we're done.
2447 if (ClassTemplateSpecializationDecl *Spec
2448 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2449 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2450 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2451 ExplicitSpecLoc = Spec->getLocation();
2452 break;
2453 }
2454 } else if (Record->getTemplateSpecializationKind()
2455 == TSK_ExplicitSpecialization) {
2456 ExplicitSpecLoc = Record->getLocation();
2457 break;
2458 }
2459
2460 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2461 T = Context.getTypeDeclType(Parent);
2462 else
2463 T = QualType();
2464 continue;
2465 }
2466
2467 if (const TemplateSpecializationType *TST
2468 = T->getAs<TemplateSpecializationType>()) {
2469 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2470 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2471 T = Context.getTypeDeclType(Parent);
2472 else
2473 T = QualType();
2474 continue;
2475 }
2476 }
2477
2478 // Look one step prior in a dependent template specialization type.
2479 if (const DependentTemplateSpecializationType *DependentTST
2480 = T->getAs<DependentTemplateSpecializationType>()) {
2481 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2482 T = QualType(NNS->getAsType(), 0);
2483 else
2484 T = QualType();
2485 continue;
2486 }
2487
2488 // Look one step prior in a dependent name type.
2489 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2490 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2491 T = QualType(NNS->getAsType(), 0);
2492 else
2493 T = QualType();
2494 continue;
2495 }
2496
2497 // Retrieve the parent of an enumeration type.
2498 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2499 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2500 // check here.
2501 EnumDecl *Enum = EnumT->getDecl();
2502
2503 // Get to the parent type.
2504 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2505 T = Context.getTypeDeclType(Parent);
2506 else
2507 T = QualType();
2508 continue;
2509 }
2510
2511 T = QualType();
2512 }
2513 // Reverse the nested types list, since we want to traverse from the outermost
2514 // to the innermost while checking template-parameter-lists.
2515 std::reverse(NestedTypes.begin(), NestedTypes.end());
2516
2517 // C++0x [temp.expl.spec]p17:
2518 // A member or a member template may be nested within many
2519 // enclosing class templates. In an explicit specialization for
2520 // such a member, the member declaration shall be preceded by a
2521 // template<> for each enclosing class template that is
2522 // explicitly specialized.
2523 bool SawNonEmptyTemplateParameterList = false;
2524
2525 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2526 if (SawNonEmptyTemplateParameterList) {
2527 Diag(DeclLoc, diag::err_specialize_member_of_template)
2528 << !Recovery << Range;
2529 Invalid = true;
2530 IsMemberSpecialization = false;
2531 return true;
2532 }
2533
2534 return false;
2535 };
2536
2537 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2538 // Check that we can have an explicit specialization here.
2539 if (CheckExplicitSpecialization(Range, true))
2540 return true;
2541
2542 // We don't have a template header, but we should.
2543 SourceLocation ExpectedTemplateLoc;
2544 if (!ParamLists.empty())
2545 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2546 else
2547 ExpectedTemplateLoc = DeclStartLoc;
2548
2549 Diag(DeclLoc, diag::err_template_spec_needs_header)
2550 << Range
2551 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2552 return false;
2553 };
2554
2555 unsigned ParamIdx = 0;
2556 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2557 ++TypeIdx) {
2558 T = NestedTypes[TypeIdx];
2559
2560 // Whether we expect a 'template<>' header.
2561 bool NeedEmptyTemplateHeader = false;
2562
2563 // Whether we expect a template header with parameters.
2564 bool NeedNonemptyTemplateHeader = false;
2565
2566 // For a dependent type, the set of template parameters that we
2567 // expect to see.
2568 TemplateParameterList *ExpectedTemplateParams = nullptr;
2569
2570 // C++0x [temp.expl.spec]p15:
2571 // A member or a member template may be nested within many enclosing
2572 // class templates. In an explicit specialization for such a member, the
2573 // member declaration shall be preceded by a template<> for each
2574 // enclosing class template that is explicitly specialized.
2575 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2576 if (ClassTemplatePartialSpecializationDecl *Partial
2577 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2578 ExpectedTemplateParams = Partial->getTemplateParameters();
2579 NeedNonemptyTemplateHeader = true;
2580 } else if (Record->isDependentType()) {
2581 if (Record->getDescribedClassTemplate()) {
2582 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2583 ->getTemplateParameters();
2584 NeedNonemptyTemplateHeader = true;
2585 }
2586 } else if (ClassTemplateSpecializationDecl *Spec
2587 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2588 // C++0x [temp.expl.spec]p4:
2589 // Members of an explicitly specialized class template are defined
2590 // in the same manner as members of normal classes, and not using
2591 // the template<> syntax.
2592 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2593 NeedEmptyTemplateHeader = true;
2594 else
2595 continue;
2596 } else if (Record->getTemplateSpecializationKind()) {
2597 if (Record->getTemplateSpecializationKind()
2598 != TSK_ExplicitSpecialization &&
2599 TypeIdx == NumTypes - 1)
2600 IsMemberSpecialization = true;
2601
2602 continue;
2603 }
2604 } else if (const TemplateSpecializationType *TST
2605 = T->getAs<TemplateSpecializationType>()) {
2606 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2607 ExpectedTemplateParams = Template->getTemplateParameters();
2608 NeedNonemptyTemplateHeader = true;
2609 }
2610 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2611 // FIXME: We actually could/should check the template arguments here
2612 // against the corresponding template parameter list.
2613 NeedNonemptyTemplateHeader = false;
2614 }
2615
2616 // C++ [temp.expl.spec]p16:
2617 // In an explicit specialization declaration for a member of a class
2618 // template or a member template that ap- pears in namespace scope, the
2619 // member template and some of its enclosing class templates may remain
2620 // unspecialized, except that the declaration shall not explicitly
2621 // specialize a class member template if its en- closing class templates
2622 // are not explicitly specialized as well.
2623 if (ParamIdx < ParamLists.size()) {
2624 if (ParamLists[ParamIdx]->size() == 0) {
2625 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2626 false))
2627 return nullptr;
2628 } else
2629 SawNonEmptyTemplateParameterList = true;
2630 }
2631
2632 if (NeedEmptyTemplateHeader) {
2633 // If we're on the last of the types, and we need a 'template<>' header
2634 // here, then it's a member specialization.
2635 if (TypeIdx == NumTypes - 1)
2636 IsMemberSpecialization = true;
2637
2638 if (ParamIdx < ParamLists.size()) {
2639 if (ParamLists[ParamIdx]->size() > 0) {
2640 // The header has template parameters when it shouldn't. Complain.
2641 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2642 diag::err_template_param_list_matches_nontemplate)
2643 << T
2644 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2645 ParamLists[ParamIdx]->getRAngleLoc())
2646 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2647 Invalid = true;
2648 return nullptr;
2649 }
2650
2651 // Consume this template header.
2652 ++ParamIdx;
2653 continue;
2654 }
2655
2656 if (!IsFriend)
2657 if (DiagnoseMissingExplicitSpecialization(
2658 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2659 return nullptr;
2660
2661 continue;
2662 }
2663
2664 if (NeedNonemptyTemplateHeader) {
2665 // In friend declarations we can have template-ids which don't
2666 // depend on the corresponding template parameter lists. But
2667 // assume that empty parameter lists are supposed to match this
2668 // template-id.
2669 if (IsFriend && T->isDependentType()) {
2670 if (ParamIdx < ParamLists.size() &&
2671 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2672 ExpectedTemplateParams = nullptr;
2673 else
2674 continue;
2675 }
2676
2677 if (ParamIdx < ParamLists.size()) {
2678 // Check the template parameter list, if we can.
2679 if (ExpectedTemplateParams &&
2680 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2681 ExpectedTemplateParams,
2682 true, TPL_TemplateMatch))
2683 Invalid = true;
2684
2685 if (!Invalid &&
2686 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2687 TPC_ClassTemplateMember))
2688 Invalid = true;
2689
2690 ++ParamIdx;
2691 continue;
2692 }
2693
2694 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2695 << T
2696 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2697 Invalid = true;
2698 continue;
2699 }
2700 }
2701
2702 // If there were at least as many template-ids as there were template
2703 // parameter lists, then there are no template parameter lists remaining for
2704 // the declaration itself.
2705 if (ParamIdx >= ParamLists.size()) {
2706 if (TemplateId && !IsFriend) {
2707 // We don't have a template header for the declaration itself, but we
2708 // should.
2709 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2710 TemplateId->RAngleLoc));
2711
2712 // Fabricate an empty template parameter list for the invented header.
2713 return TemplateParameterList::Create(Context, SourceLocation(),
2714 SourceLocation(), None,
2715 SourceLocation(), nullptr);
2716 }
2717
2718 return nullptr;
2719 }
2720
2721 // If there were too many template parameter lists, complain about that now.
2722 if (ParamIdx < ParamLists.size() - 1) {
2723 bool HasAnyExplicitSpecHeader = false;
2724 bool AllExplicitSpecHeaders = true;
2725 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2726 if (ParamLists[I]->size() == 0)
2727 HasAnyExplicitSpecHeader = true;
2728 else
2729 AllExplicitSpecHeaders = false;
2730 }
2731
2732 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2733 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2734 : diag::err_template_spec_extra_headers)
2735 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2736 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2737
2738 // If there was a specialization somewhere, such that 'template<>' is
2739 // not required, and there were any 'template<>' headers, note where the
2740 // specialization occurred.
2741 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2742 Diag(ExplicitSpecLoc,
2743 diag::note_explicit_template_spec_does_not_need_header)
2744 << NestedTypes.back();
2745
2746 // We have a template parameter list with no corresponding scope, which
2747 // means that the resulting template declaration can't be instantiated
2748 // properly (we'll end up with dependent nodes when we shouldn't).
2749 if (!AllExplicitSpecHeaders)
2750 Invalid = true;
2751 }
2752
2753 // C++ [temp.expl.spec]p16:
2754 // In an explicit specialization declaration for a member of a class
2755 // template or a member template that ap- pears in namespace scope, the
2756 // member template and some of its enclosing class templates may remain
2757 // unspecialized, except that the declaration shall not explicitly
2758 // specialize a class member template if its en- closing class templates
2759 // are not explicitly specialized as well.
2760 if (ParamLists.back()->size() == 0 &&
2761 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2762 false))
2763 return nullptr;
2764
2765 // Return the last template parameter list, which corresponds to the
2766 // entity being declared.
2767 return ParamLists.back();
2768}
2769
2770void Sema::NoteAllFoundTemplates(TemplateName Name) {
2771 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2772 Diag(Template->getLocation(), diag::note_template_declared_here)
2773 << (isa<FunctionTemplateDecl>(Template)
2774 ? 0
2775 : isa<ClassTemplateDecl>(Template)
2776 ? 1
2777 : isa<VarTemplateDecl>(Template)
2778 ? 2
2779 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2780 << Template->getDeclName();
2781 return;
2782 }
2783
2784 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2785 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2786 IEnd = OST->end();
2787 I != IEnd; ++I)
2788 Diag((*I)->getLocation(), diag::note_template_declared_here)
2789 << 0 << (*I)->getDeclName();
2790
2791 return;
2792 }
2793}
2794
2795static QualType
2796checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2797 const SmallVectorImpl<TemplateArgument> &Converted,
2798 SourceLocation TemplateLoc,
2799 TemplateArgumentListInfo &TemplateArgs) {
2800 ASTContext &Context = SemaRef.getASTContext();
2801 switch (BTD->getBuiltinTemplateKind()) {
2802 case BTK__make_integer_seq: {
2803 // Specializations of __make_integer_seq<S, T, N> are treated like
2804 // S<T, 0, ..., N-1>.
2805
2806 // C++14 [inteseq.intseq]p1:
2807 // T shall be an integer type.
2808 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2809 SemaRef.Diag(TemplateArgs[1].getLocation(),
2810 diag::err_integer_sequence_integral_element_type);
2811 return QualType();
2812 }
2813
2814 // C++14 [inteseq.make]p1:
2815 // If N is negative the program is ill-formed.
2816 TemplateArgument NumArgsArg = Converted[2];
2817 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2818 if (NumArgs < 0) {
2819 SemaRef.Diag(TemplateArgs[2].getLocation(),
2820 diag::err_integer_sequence_negative_length);
2821 return QualType();
2822 }
2823
2824 QualType ArgTy = NumArgsArg.getIntegralType();
2825 TemplateArgumentListInfo SyntheticTemplateArgs;
2826 // The type argument gets reused as the first template argument in the
2827 // synthetic template argument list.
2828 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2829 // Expand N into 0 ... N-1.
2830 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2831 I < NumArgs; ++I) {
2832 TemplateArgument TA(Context, I, ArgTy);
2833 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2834 TA, ArgTy, TemplateArgs[2].getLocation()));
2835 }
2836 // The first template argument will be reused as the template decl that
2837 // our synthetic template arguments will be applied to.
2838 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2839 TemplateLoc, SyntheticTemplateArgs);
2840 }
2841
2842 case BTK__type_pack_element:
2843 // Specializations of
2844 // __type_pack_element<Index, T_1, ..., T_N>
2845 // are treated like T_Index.
2846 assert(Converted.size() == 2 &&(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2847, __extension__ __PRETTY_FUNCTION__))
2847 "__type_pack_element should be given an index and a parameter pack")(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2847, __extension__ __PRETTY_FUNCTION__))
;
2848
2849 // If the Index is out of bounds, the program is ill-formed.
2850 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2851 llvm::APSInt Index = IndexArg.getAsIntegral();
2852 assert(Index >= 0 && "the index used with __type_pack_element should be of "(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? void (0) : __assert_fail
("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2853, __extension__ __PRETTY_FUNCTION__))
2853 "type std::size_t, and hence be non-negative")(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? void (0) : __assert_fail
("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2853, __extension__ __PRETTY_FUNCTION__))
;
2854 if (Index >= Ts.pack_size()) {
2855 SemaRef.Diag(TemplateArgs[0].getLocation(),
2856 diag::err_type_pack_element_out_of_bounds);
2857 return QualType();
2858 }
2859
2860 // We simply return the type at index `Index`.
2861 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2862 return Nth->getAsType();
2863 }
2864 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2864)
;
2865}
2866
2867/// Determine whether this alias template is "enable_if_t".
2868static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2869 return AliasTemplate->getName().equals("enable_if_t");
2870}
2871
2872/// Collect all of the separable terms in the given condition, which
2873/// might be a conjunction.
2874///
2875/// FIXME: The right answer is to convert the logical expression into
2876/// disjunctive normal form, so we can find the first failed term
2877/// within each possible clause.
2878static void collectConjunctionTerms(Expr *Clause,
2879 SmallVectorImpl<Expr *> &Terms) {
2880 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2881 if (BinOp->getOpcode() == BO_LAnd) {
2882 collectConjunctionTerms(BinOp->getLHS(), Terms);
2883 collectConjunctionTerms(BinOp->getRHS(), Terms);
2884 }
2885
2886 return;
2887 }
2888
2889 Terms.push_back(Clause);
2890}
2891
2892// The ranges-v3 library uses an odd pattern of a top-level "||" with
2893// a left-hand side that is value-dependent but never true. Identify
2894// the idiom and ignore that term.
2895static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
2896 // Top-level '||'.
2897 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2898 if (!BinOp) return Cond;
2899
2900 if (BinOp->getOpcode() != BO_LOr) return Cond;
2901
2902 // With an inner '==' that has a literal on the right-hand side.
2903 Expr *LHS = BinOp->getLHS();
2904 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2905 if (!InnerBinOp) return Cond;
2906
2907 if (InnerBinOp->getOpcode() != BO_EQ ||
2908 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2909 return Cond;
2910
2911 // If the inner binary operation came from a macro expansion named
2912 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2913 // of the '||', which is the real, user-provided condition.
2914 SourceLocation Loc = InnerBinOp->getExprLoc();
2915 if (!Loc.isMacroID()) return Cond;
2916
2917 StringRef MacroName = PP.getImmediateMacroName(Loc);
2918 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2919 return BinOp->getRHS();
2920
2921 return Cond;
2922}
2923
2924std::pair<Expr *, std::string>
2925Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2926 Cond = lookThroughRangesV3Condition(PP, Cond);
2927
2928 // Separate out all of the terms in a conjunction.
2929 SmallVector<Expr *, 4> Terms;
2930 collectConjunctionTerms(Cond, Terms);
2931
2932 // Determine which term failed.
2933 Expr *FailedCond = nullptr;
2934 for (Expr *Term : Terms) {
2935 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2936
2937 // Literals are uninteresting.
2938 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2939 isa<IntegerLiteral>(TermAsWritten))
2940 continue;
2941
2942 // The initialization of the parameter from the argument is
2943 // a constant-evaluated context.
2944 EnterExpressionEvaluationContext ConstantEvaluated(
2945 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2946
2947 bool Succeeded;
2948 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
2949 !Succeeded) {
2950 FailedCond = TermAsWritten;
2951 break;
2952 }
2953 }
2954
2955 if (!FailedCond) {
2956 if (!AllowTopLevelCond)
2957 return { nullptr, "" };
2958
2959 FailedCond = Cond->IgnoreParenImpCasts();
2960 }
2961
2962 std::string Description;
2963 {
2964 llvm::raw_string_ostream Out(Description);
2965 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
2966 }
2967 return { FailedCond, Description };
2968}
2969
2970QualType Sema::CheckTemplateIdType(TemplateName Name,
2971 SourceLocation TemplateLoc,
2972 TemplateArgumentListInfo &TemplateArgs) {
2973 DependentTemplateName *DTN
2974 = Name.getUnderlying().getAsDependentTemplateName();
2975 if (DTN && DTN->isIdentifier())
2976 // When building a template-id where the template-name is dependent,
2977 // assume the template is a type template. Either our assumption is
2978 // correct, or the code is ill-formed and will be diagnosed when the
2979 // dependent name is substituted.
2980 return Context.getDependentTemplateSpecializationType(ETK_None,
2981 DTN->getQualifier(),
2982 DTN->getIdentifier(),
2983 TemplateArgs);
2984
2985 TemplateDecl *Template = Name.getAsTemplateDecl();
2986 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2987 isa<VarTemplateDecl>(Template)) {
2988 // We might have a substituted template template parameter pack. If so,
2989 // build a template specialization type for it.
2990 if (Name.getAsSubstTemplateTemplateParmPack())
2991 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2992
2993 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2994 << Name;
2995 NoteAllFoundTemplates(Name);
2996 return QualType();
2997 }
2998
2999 // Check that the template argument list is well-formed for this
3000 // template.
3001 SmallVector<TemplateArgument, 4> Converted;
3002 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3003 false, Converted))
3004 return QualType();
3005
3006 QualType CanonType;
3007
3008 bool InstantiationDependent = false;
3009 if (TypeAliasTemplateDecl *AliasTemplate =
3010 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3011 // Find the canonical type for this type alias template specialization.
3012 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3013 if (Pattern->isInvalidDecl())
3014 return QualType();
3015
3016 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3017 Converted);
3018
3019 // Only substitute for the innermost template argument list.
3020 MultiLevelTemplateArgumentList TemplateArgLists;
3021 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3022 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3023 for (unsigned I = 0; I < Depth; ++I)
3024 TemplateArgLists.addOuterTemplateArguments(None);
3025
3026 LocalInstantiationScope Scope(*this);
3027 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3028 if (Inst.isInvalid())
3029 return QualType();
3030
3031 CanonType = SubstType(Pattern->getUnderlyingType(),
3032 TemplateArgLists, AliasTemplate->getLocation(),
3033 AliasTemplate->getDeclName());
3034 if (CanonType.isNull()) {
3035 // If this was enable_if and we failed to find the nested type
3036 // within enable_if in a SFINAE context, dig out the specific
3037 // enable_if condition that failed and present that instead.
3038 if (isEnableIfAliasTemplate(AliasTemplate)) {
3039 if (auto DeductionInfo = isSFINAEContext()) {
3040 if (*DeductionInfo &&
3041 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3042 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3043 diag::err_typename_nested_not_found_enable_if &&
3044 TemplateArgs[0].getArgument().getKind()
3045 == TemplateArgument::Expression) {
3046 Expr *FailedCond;
3047 std::string FailedDescription;
3048 std::tie(FailedCond, FailedDescription) =
3049 findFailedBooleanCondition(
3050 TemplateArgs[0].getSourceExpression(),
3051 /*AllowTopLevelCond=*/true);
3052
3053 // Remove the old SFINAE diagnostic.
3054 PartialDiagnosticAt OldDiag =
3055 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3056 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3057
3058 // Add a new SFINAE diagnostic specifying which condition
3059 // failed.
3060 (*DeductionInfo)->addSFINAEDiagnostic(
3061 OldDiag.first,
3062 PDiag(diag::err_typename_nested_not_found_requirement)
3063 << FailedDescription
3064 << FailedCond->getSourceRange());
3065 }
3066 }
3067 }
3068
3069 return QualType();
3070 }
3071 } else if (Name.isDependent() ||
3072 TemplateSpecializationType::anyDependentTemplateArguments(
3073 TemplateArgs, InstantiationDependent)) {
3074 // This class template specialization is a dependent
3075 // type. Therefore, its canonical type is another class template
3076 // specialization type that contains all of the converted
3077 // arguments in canonical form. This ensures that, e.g., A<T> and
3078 // A<T, T> have identical types when A is declared as:
3079 //
3080 // template<typename T, typename U = T> struct A;
3081 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3082
3083 // This might work out to be a current instantiation, in which
3084 // case the canonical type needs to be the InjectedClassNameType.
3085 //
3086 // TODO: in theory this could be a simple hashtable lookup; most
3087 // changes to CurContext don't change the set of current
3088 // instantiations.
3089 if (isa<ClassTemplateDecl>(Template)) {
3090 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3091 // If we get out to a namespace, we're done.
3092 if (Ctx->isFileContext()) break;
3093
3094 // If this isn't a record, keep looking.
3095 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3096 if (!Record) continue;
3097
3098 // Look for one of the two cases with InjectedClassNameTypes
3099 // and check whether it's the same template.
3100 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3101 !Record->getDescribedClassTemplate())
3102 continue;
3103
3104 // Fetch the injected class name type and check whether its
3105 // injected type is equal to the type we just built.
3106 QualType ICNT = Context.getTypeDeclType(Record);
3107 QualType Injected = cast<InjectedClassNameType>(ICNT)
3108 ->getInjectedSpecializationType();
3109
3110 if (CanonType != Injected->getCanonicalTypeInternal())
3111 continue;
3112
3113 // If so, the canonical type of this TST is the injected
3114 // class name type of the record we just found.
3115 assert(ICNT.isCanonical())(static_cast <bool> (ICNT.isCanonical()) ? void (0) : __assert_fail
("ICNT.isCanonical()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3115, __extension__ __PRETTY_FUNCTION__))
;
3116 CanonType = ICNT;
3117 break;
3118 }
3119 }
3120 } else if (ClassTemplateDecl *ClassTemplate
3121 = dyn_cast<ClassTemplateDecl>(Template)) {
3122 // Find the class template specialization declaration that
3123 // corresponds to these arguments.
3124 void *InsertPos = nullptr;
3125 ClassTemplateSpecializationDecl *Decl
3126 = ClassTemplate->findSpecialization(Converted, InsertPos);
3127 if (!Decl) {
3128 // This is the first time we have referenced this class template
3129 // specialization. Create the canonical declaration and add it to
3130 // the set of specializations.
3131 Decl = ClassTemplateSpecializationDecl::Create(Context,
3132 ClassTemplate->getTemplatedDecl()->getTagKind(),
3133 ClassTemplate->getDeclContext(),
3134 ClassTemplate->getTemplatedDecl()->getLocStart(),
3135 ClassTemplate->getLocation(),
3136 ClassTemplate,
3137 Converted, nullptr);
3138 ClassTemplate->AddSpecialization(Decl, InsertPos);
3139 if (ClassTemplate->isOutOfLine())
3140 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3141 }
3142
3143 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3144 MultiLevelTemplateArgumentList TemplateArgLists;
3145 TemplateArgLists.addOuterTemplateArguments(Converted);
3146 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3147 Decl);
3148 }
3149
3150 // Diagnose uses of this specialization.
3151 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3152
3153 CanonType = Context.getTypeDeclType(Decl);
3154 assert(isa<RecordType>(CanonType) &&(static_cast <bool> (isa<RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType") ?
void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3155, __extension__ __PRETTY_FUNCTION__))
3155 "type of non-dependent specialization is not a RecordType")(static_cast <bool> (isa<RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType") ?
void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3155, __extension__ __PRETTY_FUNCTION__))
;
3156 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3157 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3158 TemplateArgs);
3159 }
3160
3161 // Build the fully-sugared type for this class template
3162 // specialization, which refers back to the class template
3163 // specialization we created or found.
3164 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3165}
3166
3167TypeResult
3168Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3169 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3170 SourceLocation TemplateIILoc,
3171 SourceLocation LAngleLoc,
3172 ASTTemplateArgsPtr TemplateArgsIn,
3173 SourceLocation RAngleLoc,
3174 bool IsCtorOrDtorName, bool IsClassName) {
3175 if (SS.isInvalid())
3176 return true;
3177
3178 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3179 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3180
3181 // C++ [temp.res]p3:
3182 // A qualified-id that refers to a type and in which the
3183 // nested-name-specifier depends on a template-parameter (14.6.2)
3184 // shall be prefixed by the keyword typename to indicate that the
3185 // qualified-id denotes a type, forming an
3186 // elaborated-type-specifier (7.1.5.3).
3187 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3188 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3189 << SS.getScopeRep() << TemplateII->getName();
3190 // Recover as if 'typename' were specified.
3191 // FIXME: This is not quite correct recovery as we don't transform SS
3192 // into the corresponding dependent form (and we don't diagnose missing
3193 // 'template' keywords within SS as a result).
3194 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3195 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3196 TemplateArgsIn, RAngleLoc);
3197 }
3198
3199 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3200 // it's not actually allowed to be used as a type in most cases. Because
3201 // we annotate it before we know whether it's valid, we have to check for
3202 // this case here.
3203 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3204 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3205 Diag(TemplateIILoc,
3206 TemplateKWLoc.isInvalid()
3207 ? diag::err_out_of_line_qualified_id_type_names_constructor
3208 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3209 << TemplateII << 0 /*injected-class-name used as template name*/
3210 << 1 /*if any keyword was present, it was 'template'*/;
3211 }
3212 }
3213
3214 TemplateName Template = TemplateD.get();
3215
3216 // Translate the parser's template argument list in our AST format.
3217 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3218 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3219
3220 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3221 QualType T
3222 = Context.getDependentTemplateSpecializationType(ETK_None,
3223 DTN->getQualifier(),
3224 DTN->getIdentifier(),
3225 TemplateArgs);
3226 // Build type-source information.
3227 TypeLocBuilder TLB;
3228 DependentTemplateSpecializationTypeLoc SpecTL
3229 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3230 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3231 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3232 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3233 SpecTL.setTemplateNameLoc(TemplateIILoc);
3234 SpecTL.setLAngleLoc(LAngleLoc);
3235 SpecTL.setRAngleLoc(RAngleLoc);
3236 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3237 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3238 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3239 }
3240
3241 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3242 if (Result.isNull())
3243 return true;
3244
3245 // Build type-source information.
3246 TypeLocBuilder TLB;
3247 TemplateSpecializationTypeLoc SpecTL
3248 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3249 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3250 SpecTL.setTemplateNameLoc(TemplateIILoc);
3251 SpecTL.setLAngleLoc(LAngleLoc);
3252 SpecTL.setRAngleLoc(RAngleLoc);
3253 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3254 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3255
3256 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3257 // constructor or destructor name (in such a case, the scope specifier
3258 // will be attached to the enclosing Decl or Expr node).
3259 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3260 // Create an elaborated-type-specifier containing the nested-name-specifier.
3261 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3262 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3263 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3264 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3265 }
3266
3267 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3268}
3269
3270TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3271 TypeSpecifierType TagSpec,
3272 SourceLocation TagLoc,
3273 CXXScopeSpec &SS,
3274 SourceLocation TemplateKWLoc,
3275 TemplateTy TemplateD,
3276 SourceLocation TemplateLoc,
3277 SourceLocation LAngleLoc,
3278 ASTTemplateArgsPtr TemplateArgsIn,
3279 SourceLocation RAngleLoc) {
3280 TemplateName Template = TemplateD.get();
3281
3282 // Translate the parser's template argument list in our AST format.
3283 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3284 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3285
3286 // Determine the tag kind
3287 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3288 ElaboratedTypeKeyword Keyword
3289 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3290
3291 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3292 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3293 DTN->getQualifier(),
3294 DTN->getIdentifier(),
3295 TemplateArgs);
3296
3297 // Build type-source information.
3298 TypeLocBuilder TLB;
3299 DependentTemplateSpecializationTypeLoc SpecTL
3300 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3301 SpecTL.setElaboratedKeywordLoc(TagLoc);
3302 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3303 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3304 SpecTL.setTemplateNameLoc(TemplateLoc);
3305 SpecTL.setLAngleLoc(LAngleLoc);
3306 SpecTL.setRAngleLoc(RAngleLoc);
3307 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3308 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3309 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3310 }
3311
3312 if (TypeAliasTemplateDecl *TAT =
3313 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3314 // C++0x [dcl.type.elab]p2:
3315 // If the identifier resolves to a typedef-name or the simple-template-id
3316 // resolves to an alias template specialization, the
3317 // elaborated-type-specifier is ill-formed.
3318 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3319 << TAT << NTK_TypeAliasTemplate << TagKind;
3320 Diag(TAT->getLocation(), diag::note_declared_at);
3321 }
3322
3323 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3324 if (Result.isNull())
3325 return TypeResult(true);
3326
3327 // Check the tag kind
3328 if (const RecordType *RT = Result->getAs<RecordType>()) {
3329 RecordDecl *D = RT->getDecl();
3330
3331 IdentifierInfo *Id = D->getIdentifier();
3332 assert(Id && "templated class must have an identifier")(static_cast <bool> (Id && "templated class must have an identifier"
) ? void (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3332, __extension__ __PRETTY_FUNCTION__))
;
3333
3334 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3335 TagLoc, Id)) {
3336 Diag(TagLoc, diag::err_use_with_wrong_tag)
3337 << Result
3338 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3339 Diag(D->getLocation(), diag::note_previous_use);
3340 }
3341 }
3342
3343 // Provide source-location information for the template specialization.
3344 TypeLocBuilder TLB;
3345 TemplateSpecializationTypeLoc SpecTL
3346 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3347 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3348 SpecTL.setTemplateNameLoc(TemplateLoc);
3349 SpecTL.setLAngleLoc(LAngleLoc);
3350 SpecTL.setRAngleLoc(RAngleLoc);
3351 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3352 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3353
3354 // Construct an elaborated type containing the nested-name-specifier (if any)
3355 // and tag keyword.
3356 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3357 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3358 ElabTL.setElaboratedKeywordLoc(TagLoc);
3359 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3360 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3361}
3362
3363static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3364 NamedDecl *PrevDecl,
3365 SourceLocation Loc,
3366 bool IsPartialSpecialization);
3367
3368static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3369
3370static bool isTemplateArgumentTemplateParameter(
3371 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3372 switch (Arg.getKind()) {
3373 case TemplateArgument::Null:
3374 case TemplateArgument::NullPtr:
3375 case TemplateArgument::Integral:
3376 case TemplateArgument::Declaration:
3377 case TemplateArgument::Pack:
3378 case TemplateArgument::TemplateExpansion:
3379 return false;
3380
3381 case TemplateArgument::Type: {
3382 QualType Type = Arg.getAsType();
3383 const TemplateTypeParmType *TPT =
3384 Arg.getAsType()->getAs<TemplateTypeParmType>();
3385 return TPT && !Type.hasQualifiers() &&
3386 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3387 }
3388
3389 case TemplateArgument::Expression: {
3390 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3391 if (!DRE || !DRE->getDecl())
3392 return false;
3393 const NonTypeTemplateParmDecl *NTTP =
3394 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3395 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3396 }
3397
3398 case TemplateArgument::Template:
3399 const TemplateTemplateParmDecl *TTP =
3400 dyn_cast_or_null<TemplateTemplateParmDecl>(
3401 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3402 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3403 }
3404 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3404)
;
3405}
3406
3407static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3408 ArrayRef<TemplateArgument> Args) {
3409 if (Params->size() != Args.size())
3410 return false;
3411
3412 unsigned Depth = Params->getDepth();
3413
3414 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3415 TemplateArgument Arg = Args[I];
3416
3417 // If the parameter is a pack expansion, the argument must be a pack
3418 // whose only element is a pack expansion.
3419 if (Params->getParam(I)->isParameterPack()) {
3420 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3421 !Arg.pack_begin()->isPackExpansion())
3422 return false;
3423 Arg = Arg.pack_begin()->getPackExpansionPattern();
3424 }
3425
3426 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3427 return false;
3428 }
3429
3430 return true;
3431}
3432
3433/// Convert the parser's template argument list representation into our form.
3434static TemplateArgumentListInfo
3435makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3436 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3437 TemplateId.RAngleLoc);
3438 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3439 TemplateId.NumArgs);
3440 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3441 return TemplateArgs;
3442}
3443
3444template<typename PartialSpecDecl>
3445static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3446 if (Partial->getDeclContext()->isDependentContext())
3447 return;
3448
3449 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3450 // for non-substitution-failure issues?
3451 TemplateDeductionInfo Info(Partial->getLocation());
3452 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3453 return;
3454
3455 auto *Template = Partial->getSpecializedTemplate();
3456 S.Diag(Partial->getLocation(),
3457 diag::ext_partial_spec_not_more_specialized_than_primary)
3458 << isa<VarTemplateDecl>(Template);
3459
3460 if (Info.hasSFINAEDiagnostic()) {
3461 PartialDiagnosticAt Diag = {SourceLocation(),
3462 PartialDiagnostic::NullDiagnostic()};
3463 Info.takeSFINAEDiagnostic(Diag);
3464 SmallString<128> SFINAEArgString;
3465 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3466 S.Diag(Diag.first,
3467 diag::note_partial_spec_not_more_specialized_than_primary)
3468 << SFINAEArgString;
3469 }
3470
3471 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3472}
3473
3474static void
3475noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3476 const llvm::SmallBitVector &DeducibleParams) {
3477 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3478 if (!DeducibleParams[I]) {
3479 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3480 if (Param->getDeclName())
3481 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3482 << Param->getDeclName();
3483 else
3484 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3485 << "(anonymous)";
3486 }
3487 }
3488}
3489
3490
3491template<typename PartialSpecDecl>
3492static void checkTemplatePartialSpecialization(Sema &S,
3493 PartialSpecDecl *Partial) {
3494 // C++1z [temp.class.spec]p8: (DR1495)
3495 // - The specialization shall be more specialized than the primary
3496 // template (14.5.5.2).
3497 checkMoreSpecializedThanPrimary(S, Partial);
3498
3499 // C++ [temp.class.spec]p8: (DR1315)
3500 // - Each template-parameter shall appear at least once in the
3501 // template-id outside a non-deduced context.
3502 // C++1z [temp.class.spec.match]p3 (P0127R2)
3503 // If the template arguments of a partial specialization cannot be
3504 // deduced because of the structure of its template-parameter-list
3505 // and the template-id, the program is ill-formed.
3506 auto *TemplateParams = Partial->getTemplateParameters();
3507 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3508 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3509 TemplateParams->getDepth(), DeducibleParams);
3510
3511 if (!DeducibleParams.all()) {
3512 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3513 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3514 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3515 << (NumNonDeducible > 1)
3516 << SourceRange(Partial->getLocation(),
3517 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3518 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3519 }
3520}
3521
3522void Sema::CheckTemplatePartialSpecialization(
3523 ClassTemplatePartialSpecializationDecl *Partial) {
3524 checkTemplatePartialSpecialization(*this, Partial);
3525}
3526
3527void Sema::CheckTemplatePartialSpecialization(
3528 VarTemplatePartialSpecializationDecl *Partial) {
3529 checkTemplatePartialSpecialization(*this, Partial);
3530}
3531
3532void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3533 // C++1z [temp.param]p11:
3534 // A template parameter of a deduction guide template that does not have a
3535 // default-argument shall be deducible from the parameter-type-list of the
3536 // deduction guide template.
3537 auto *TemplateParams = TD->getTemplateParameters();
3538 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3539 MarkDeducedTemplateParameters(TD, DeducibleParams);
3540 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3541 // A parameter pack is deducible (to an empty pack).
3542 auto *Param = TemplateParams->getParam(I);
3543 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3544 DeducibleParams[I] = true;
3545 }
3546
3547 if (!DeducibleParams.all()) {
3548 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3549 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3550 << (NumNonDeducible > 1);
3551 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3552 }
3553}
3554
3555DeclResult Sema::ActOnVarTemplateSpecialization(
3556 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3557 TemplateParameterList *TemplateParams, StorageClass SC,
3558 bool IsPartialSpecialization) {
3559 // D must be variable template id.
3560 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind
::IK_TemplateId && "Variable template specialization is declared with a template it."
) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3561, __extension__ __PRETTY_FUNCTION__))
3561 "Variable template specialization is declared with a template it.")(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind
::IK_TemplateId && "Variable template specialization is declared with a template it."
) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3561, __extension__ __PRETTY_FUNCTION__))
;
3562
3563 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3564 TemplateArgumentListInfo TemplateArgs =
3565 makeTemplateArgumentListInfo(*this, *TemplateId);
3566 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3567 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3568 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3569
3570 TemplateName Name = TemplateId->Template.get();
3571
3572 // The template-id must name a variable template.
3573 VarTemplateDecl *VarTemplate =
3574 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3575 if (!VarTemplate) {
3576 NamedDecl *FnTemplate;
3577 if (auto *OTS = Name.getAsOverloadedTemplate())
3578 FnTemplate = *OTS->begin();
3579 else
3580 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3581 if (FnTemplate)
3582 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3583 << FnTemplate->getDeclName();
3584 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3585 << IsPartialSpecialization;
3586 }
3587
3588 // Check for unexpanded parameter packs in any of the template arguments.
3589 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3590 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3591 UPPC_PartialSpecialization))
3592 return true;
3593
3594 // Check that the template argument list is well-formed for this
3595 // template.
3596 SmallVector<TemplateArgument, 4> Converted;
3597 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3598 false, Converted))
3599 return true;
3600
3601 // Find the variable template (partial) specialization declaration that
3602 // corresponds to these arguments.
3603 if (IsPartialSpecialization) {
3604 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3605 TemplateArgs.size(), Converted))
3606 return true;
3607
3608 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3609 // also do them during instantiation.
3610 bool InstantiationDependent;
3611 if (!Name.isDependent() &&
3612 !TemplateSpecializationType::anyDependentTemplateArguments(
3613 TemplateArgs.arguments(),
3614 InstantiationDependent)) {
3615 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3616 << VarTemplate->getDeclName();
3617 IsPartialSpecialization = false;
3618 }
3619
3620 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3621 Converted)) {
3622 // C++ [temp.class.spec]p9b3:
3623 //
3624 // -- The argument list of the specialization shall not be identical
3625 // to the implicit argument list of the primary template.
3626 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3627 << /*variable template*/ 1
3628 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3629 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3630 // FIXME: Recover from this by treating the declaration as a redeclaration
3631 // of the primary template.
3632 return true;
3633 }
3634 }
3635
3636 void *InsertPos = nullptr;
3637 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3638
3639 if (IsPartialSpecialization)
3640 // FIXME: Template parameter list matters too
3641 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3642 else
3643 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3644
3645 VarTemplateSpecializationDecl *Specialization = nullptr;
3646
3647 // Check whether we can declare a variable template specialization in
3648 // the current scope.
3649 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3650 TemplateNameLoc,
3651 IsPartialSpecialization))
3652 return true;
3653
3654 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3655 // Since the only prior variable template specialization with these
3656 // arguments was referenced but not declared, reuse that
3657 // declaration node as our own, updating its source location and
3658 // the list of outer template parameters to reflect our new declaration.
3659 Specialization = PrevDecl;
3660 Specialization->setLocation(TemplateNameLoc);
3661 PrevDecl = nullptr;
3662 } else if (IsPartialSpecialization) {
3663 // Create a new class template partial specialization declaration node.
3664 VarTemplatePartialSpecializationDecl *PrevPartial =
3665 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3666 VarTemplatePartialSpecializationDecl *Partial =
3667 VarTemplatePartialSpecializationDecl::Create(
3668 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3669 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3670 Converted, TemplateArgs);
3671
3672 if (!PrevPartial)
3673 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3674 Specialization = Partial;
3675
3676 // If we are providing an explicit specialization of a member variable
3677 // template specialization, make a note of that.
3678 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3679 PrevPartial->setMemberSpecialization();
3680
3681 CheckTemplatePartialSpecialization(Partial);
3682 } else {
3683 // Create a new class template specialization declaration node for
3684 // this explicit specialization or friend declaration.
3685 Specialization = VarTemplateSpecializationDecl::Create(
3686 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3687 VarTemplate, DI->getType(), DI, SC, Converted);
3688 Specialization->setTemplateArgsInfo(TemplateArgs);
3689
3690 if (!PrevDecl)
3691 VarTemplate->AddSpecialization(Specialization, InsertPos);
3692 }
3693
3694 // C++ [temp.expl.spec]p6:
3695 // If a template, a member template or the member of a class template is
3696 // explicitly specialized then that specialization shall be declared
3697 // before the first use of that specialization that would cause an implicit
3698 // instantiation to take place, in every translation unit in which such a
3699 // use occurs; no diagnostic is required.
3700 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3701 bool Okay = false;
3702 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3703 // Is there any previous explicit specialization declaration?
3704 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3705 Okay = true;
3706 break;
3707 }
3708 }
3709
3710 if (!Okay) {
3711 SourceRange Range(TemplateNameLoc, RAngleLoc);
3712 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3713 << Name << Range;
3714
3715 Diag(PrevDecl->getPointOfInstantiation(),
3716 diag::note_instantiation_required_here)
3717 << (PrevDecl->getTemplateSpecializationKind() !=
3718 TSK_ImplicitInstantiation);
3719 return true;
3720 }
3721 }
3722
3723 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3724 Specialization->setLexicalDeclContext(CurContext);
3725
3726 // Add the specialization into its lexical context, so that it can
3727 // be seen when iterating through the list of declarations in that
3728 // context. However, specializations are not found by name lookup.
3729 CurContext->addDecl(Specialization);
3730
3731 // Note that this is an explicit specialization.
3732 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3733
3734 if (PrevDecl) {
3735 // Check that this isn't a redefinition of this specialization,
3736 // merging with previous declarations.
3737 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3738 forRedeclarationInCurContext());
3739 PrevSpec.addDecl(PrevDecl);
3740 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3741 } else if (Specialization->isStaticDataMember() &&
3742 Specialization->isOutOfLine()) {
3743 Specialization->setAccess(VarTemplate->getAccess());
3744 }
3745
3746 // Link instantiations of static data members back to the template from
3747 // which they were instantiated.
3748 if (Specialization->isStaticDataMember())
3749 Specialization->setInstantiationOfStaticDataMember(
3750 VarTemplate->getTemplatedDecl(),
3751 Specialization->getSpecializationKind());
3752
3753 return Specialization;
3754}
3755
3756namespace {
3757/// \brief A partial specialization whose template arguments have matched
3758/// a given template-id.
3759struct PartialSpecMatchResult {
3760 VarTemplatePartialSpecializationDecl *Partial;
3761 TemplateArgumentList *Args;
3762};
3763} // end anonymous namespace
3764
3765DeclResult
3766Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3767 SourceLocation TemplateNameLoc,
3768 const TemplateArgumentListInfo &TemplateArgs) {
3769 assert(Template && "A variable template id without template?")(static_cast <bool> (Template && "A variable template id without template?"
) ? void (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3769, __extension__ __PRETTY_FUNCTION__))
;
3770
3771 // Check that the template argument list is well-formed for this template.
3772 SmallVector<TemplateArgument, 4> Converted;
3773 if (CheckTemplateArgumentList(
3774 Template, TemplateNameLoc,
3775 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3776 Converted))
3777 return true;
3778
3779 // Find the variable template specialization declaration that
3780 // corresponds to these arguments.
3781 void *InsertPos = nullptr;
3782 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3783 Converted, InsertPos)) {
3784 checkSpecializationVisibility(TemplateNameLoc, Spec);
3785 // If we already have a variable template specialization, return it.
3786 return Spec;
3787 }
3788
3789 // This is the first time we have referenced this variable template
3790 // specialization. Create the canonical declaration and add it to
3791 // the set of specializations, based on the closest partial specialization
3792 // that it represents. That is,
3793 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3794 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3795 Converted);
3796 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3797 bool AmbiguousPartialSpec = false;
3798 typedef PartialSpecMatchResult MatchResult;
3799 SmallVector<MatchResult, 4> Matched;
3800 SourceLocation PointOfInstantiation = TemplateNameLoc;
3801 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3802 /*ForTakingAddress=*/false);
3803
3804 // 1. Attempt to find the closest partial specialization that this
3805 // specializes, if any.
3806 // If any of the template arguments is dependent, then this is probably
3807 // a placeholder for an incomplete declarative context; which must be
3808 // complete by instantiation time. Thus, do not search through the partial
3809 // specializations yet.
3810 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3811 // Perhaps better after unification of DeduceTemplateArguments() and
3812 // getMoreSpecializedPartialSpecialization().
3813 bool InstantiationDependent = false;
3814 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3815 TemplateArgs, InstantiationDependent)) {
3816
3817 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3818 Template->getPartialSpecializations(PartialSpecs);
3819
3820 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3821 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3822 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3823
3824 if (TemplateDeductionResult Result =
3825 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3826 // Store the failed-deduction information for use in diagnostics, later.
3827 // TODO: Actually use the failed-deduction info?
3828 FailedCandidates.addCandidate().set(
3829 DeclAccessPair::make(Template, AS_public), Partial,
3830 MakeDeductionFailureInfo(Context, Result, Info));
3831 (void)Result;
3832 } else {
3833 Matched.push_back(PartialSpecMatchResult());
3834 Matched.back().Partial = Partial;
3835 Matched.back().Args = Info.take();
3836 }
3837 }
3838
3839 if (Matched.size() >= 1) {
3840 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3841 if (Matched.size() == 1) {
3842 // -- If exactly one matching specialization is found, the
3843 // instantiation is generated from that specialization.
3844 // We don't need to do anything for this.
3845 } else {
3846 // -- If more than one matching specialization is found, the
3847 // partial order rules (14.5.4.2) are used to determine
3848 // whether one of the specializations is more specialized
3849 // than the others. If none of the specializations is more
3850 // specialized than all of the other matching
3851 // specializations, then the use of the variable template is
3852 // ambiguous and the program is ill-formed.
3853 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3854 PEnd = Matched.end();
3855 P != PEnd; ++P) {
3856 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3857 PointOfInstantiation) ==
3858 P->Partial)
3859 Best = P;
3860 }
3861
3862 // Determine if the best partial specialization is more specialized than
3863 // the others.
3864 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3865 PEnd = Matched.end();
3866 P != PEnd; ++P) {
3867 if (P != Best && getMoreSpecializedPartialSpecialization(
3868 P->Partial, Best->Partial,
3869 PointOfInstantiation) != Best->Partial) {
3870 AmbiguousPartialSpec = true;
3871 break;
3872 }
3873 }
3874 }
3875
3876 // Instantiate using the best variable template partial specialization.
3877 InstantiationPattern = Best->Partial;
3878 InstantiationArgs = Best->Args;
3879 } else {
3880 // -- If no match is found, the instantiation is generated
3881 // from the primary template.
3882 // InstantiationPattern = Template->getTemplatedDecl();
3883 }
3884 }
3885
3886 // 2. Create the canonical declaration.
3887 // Note that we do not instantiate a definition until we see an odr-use
3888 // in DoMarkVarDeclReferenced().
3889 // FIXME: LateAttrs et al.?
3890 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3891 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3892 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3893 if (!Decl)
3894 return true;
3895
3896 if (AmbiguousPartialSpec) {
3897 // Partial ordering did not produce a clear winner. Complain.
3898 Decl->setInvalidDecl();
3899 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3900 << Decl;
3901
3902 // Print the matching partial specializations.
3903 for (MatchResult P : Matched)
3904 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3905 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3906 *P.Args);
3907 return true;
3908 }
3909
3910 if (VarTemplatePartialSpecializationDecl *D =
3911 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3912 Decl->setInstantiationOf(D, InstantiationArgs);
3913
3914 checkSpecializationVisibility(TemplateNameLoc, Decl);
3915
3916 assert(Decl && "No variable template specialization?")(static_cast <bool> (Decl && "No variable template specialization?"
) ? void (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3916, __extension__ __PRETTY_FUNCTION__))
;
3917 return Decl;
3918}
3919
3920ExprResult
3921Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3922 const DeclarationNameInfo &NameInfo,
3923 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3924 const TemplateArgumentListInfo *TemplateArgs) {
3925
3926 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3927 *TemplateArgs);
3928 if (Decl.isInvalid())
3929 return ExprError();
3930
3931 VarDecl *Var = cast<VarDecl>(Decl.get());
3932 if (!Var->getTemplateSpecializationKind())
3933 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3934 NameInfo.getLoc());
3935
3936 // Build an ordinary singleton decl ref.
3937 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3938 /*FoundD=*/nullptr, TemplateArgs);
3939}
3940
3941ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3942 SourceLocation TemplateKWLoc,
3943 LookupResult &R,
3944 bool RequiresADL,
3945 const TemplateArgumentListInfo *TemplateArgs) {
3946 // FIXME: Can we do any checking at this point? I guess we could check the
3947 // template arguments that we have against the template name, if the template
3948 // name refers to a single template. That's not a terribly common case,
3949 // though.
3950 // foo<int> could identify a single function unambiguously
3951 // This approach does NOT work, since f<int>(1);
3952 // gets resolved prior to resorting to overload resolution
3953 // i.e., template<class T> void f(double);
3954 // vs template<class T, class U> void f(U);
3955
3956 // These should be filtered out by our callers.
3957 assert(!R.empty() && "empty lookup results when building templateid")(static_cast <bool> (!R.empty() && "empty lookup results when building templateid"
) ? void (0) : __assert_fail ("!R.empty() && \"empty lookup results when building templateid\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3957, __extension__ __PRETTY_FUNCTION__))
;
3958 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")(static_cast <bool> (!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3958, __extension__ __PRETTY_FUNCTION__))
;
3959
3960 // In C++1y, check variable template ids.
3961 bool InstantiationDependent;
3962 if (R.getAsSingle<VarTemplateDecl>() &&
3963 !TemplateSpecializationType::anyDependentTemplateArguments(
3964 *TemplateArgs, InstantiationDependent)) {
3965 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3966 R.getAsSingle<VarTemplateDecl>(),
3967 TemplateKWLoc, TemplateArgs);
3968 }
3969
3970 // We don't want lookup warnings at this point.
3971 R.suppressDiagnostics();
3972
3973 UnresolvedLookupExpr *ULE
3974 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3975 SS.getWithLocInContext(Context),
3976 TemplateKWLoc,
3977 R.getLookupNameInfo(),
3978 RequiresADL, TemplateArgs,
3979 R.begin(), R.end());
3980
3981 return ULE;
3982}
3983
3984// We actually only call this from template instantiation.
3985ExprResult
3986Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3987 SourceLocation TemplateKWLoc,
3988 const DeclarationNameInfo &NameInfo,
3989 const TemplateArgumentListInfo *TemplateArgs) {
3990
3991 assert(TemplateArgs || TemplateKWLoc.isValid())(static_cast <bool> (TemplateArgs || TemplateKWLoc.isValid
()) ? void (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3991, __extension__ __PRETTY_FUNCTION__))
;
3992 DeclContext *DC;
3993 if (!(DC = computeDeclContext(SS, false)) ||
3994 DC->isDependentContext() ||
3995 RequireCompleteDeclContext(SS, DC))
3996 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3997
3998 bool MemberOfUnknownSpecialization;
3999 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4000 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
4001 MemberOfUnknownSpecialization);
4002
4003 if (R.isAmbiguous())
4004 return ExprError();
4005
4006 if (R.empty()) {
4007 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
4008 << NameInfo.getName() << SS.getRange();
4009 return ExprError();
4010 }
4011
4012 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4013 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4014 << SS.getScopeRep()
4015 << NameInfo.getName().getAsString() << SS.getRange();
4016 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4017 return ExprError();
4018 }
4019
4020 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4021}
4022
4023/// \brief Form a dependent template name.
4024///
4025/// This action forms a dependent template name given the template
4026/// name and its (presumably dependent) scope specifier. For
4027/// example, given "MetaFun::template apply", the scope specifier \p
4028/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4029/// of the "template" keyword, and "apply" is the \p Name.
4030TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4031 CXXScopeSpec &SS,
4032 SourceLocation TemplateKWLoc,
4033 UnqualifiedId &Name,
4034 ParsedType ObjectType,
4035 bool EnteringContext,
4036 TemplateTy &Result,
4037 bool AllowInjectedClassName) {
4038 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4039 Diag(TemplateKWLoc,
4040 getLangOpts().CPlusPlus11 ?
4041 diag::warn_cxx98_compat_template_outside_of_template :
4042 diag::ext_template_outside_of_template)
4043 << FixItHint::CreateRemoval(TemplateKWLoc);
4044
4045 DeclContext *LookupCtx = nullptr;
4046 if (SS.isSet())
4047 LookupCtx = computeDeclContext(SS, EnteringContext);
4048 if (!LookupCtx && ObjectType)
4049 LookupCtx = computeDeclContext(ObjectType.get());
4050 if (LookupCtx) {
4051 // C++0x [temp.names]p5:
4052 // If a name prefixed by the keyword template is not the name of
4053 // a template, the program is ill-formed. [Note: the keyword
4054 // template may not be applied to non-template members of class
4055 // templates. -end note ] [ Note: as is the case with the
4056 // typename prefix, the template prefix is allowed in cases
4057 // where it is not strictly necessary; i.e., when the
4058 // nested-name-specifier or the expression on the left of the ->
4059 // or . is not dependent on a template-parameter, or the use
4060 // does not appear in the scope of a template. -end note]
4061 //
4062 // Note: C++03 was more strict here, because it banned the use of
4063 // the "template" keyword prior to a template-name that was not a
4064 // dependent name. C++ DR468 relaxed this requirement (the
4065 // "template" keyword is now permitted). We follow the C++0x
4066 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4067 bool MemberOfUnknownSpecialization;
4068 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4069 ObjectType, EnteringContext, Result,
4070 MemberOfUnknownSpecialization);
4071 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4072 isa<CXXRecordDecl>(LookupCtx) &&
4073 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4074 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4075 // This is a dependent template. Handle it below.
4076 } else if (TNK == TNK_Non_template) {
4077 Diag(Name.getLocStart(),
4078 diag::err_template_kw_refers_to_non_template)
4079 << GetNameFromUnqualifiedId(Name).getName()
4080 << Name.getSourceRange()
4081 << TemplateKWLoc;
4082 return TNK_Non_template;
4083 } else {
4084 // We found something; return it.
4085 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4086 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4087 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4088 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4089 // C++14 [class.qual]p2:
4090 // In a lookup in which function names are not ignored and the
4091 // nested-name-specifier nominates a class C, if the name specified
4092 // [...] is the injected-class-name of C, [...] the name is instead
4093 // considered to name the constructor
4094 //
4095 // We don't get here if naming the constructor would be valid, so we
4096 // just reject immediately and recover by treating the
4097 // injected-class-name as naming the template.
4098 Diag(Name.getLocStart(),
4099 diag::ext_out_of_line_qualified_id_type_names_constructor)
4100 << Name.Identifier << 0 /*injected-class-name used as template name*/
4101 << 1 /*'template' keyword was used*/;
4102 }
4103 return TNK;
4104 }
4105 }
4106
4107 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4108
4109 switch (Name.getKind()) {
4110 case UnqualifiedIdKind::IK_Identifier:
4111 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4112 Name.Identifier));
4113 return TNK_Dependent_template_name;
4114
4115 case UnqualifiedIdKind::IK_OperatorFunctionId:
4116 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4117 Name.OperatorFunctionId.Operator));
4118 return TNK_Function_template;
4119
4120 case UnqualifiedIdKind::IK_LiteralOperatorId:
4121 llvm_unreachable("literal operator id cannot have a dependent scope")::llvm::llvm_unreachable_internal("literal operator id cannot have a dependent scope"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4121)
;
4122
4123 default:
4124 break;
4125 }
4126
4127 Diag(Name.getLocStart(),
4128 diag::err_template_kw_refers_to_non_template)
4129 << GetNameFromUnqualifiedId(Name).getName()
4130 << Name.getSourceRange()
4131 << TemplateKWLoc;
4132 return TNK_Non_template;
4133}
4134
4135bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4136 TemplateArgumentLoc &AL,
4137 SmallVectorImpl<TemplateArgument> &Converted) {
4138 const TemplateArgument &Arg = AL.getArgument();
4139 QualType ArgType;
4140 TypeSourceInfo *TSI = nullptr;
4141
4142 // Check template type parameter.
4143 switch(Arg.getKind()) {
4144 case TemplateArgument::Type:
4145 // C++ [temp.arg.type]p1:
4146 // A template-argument for a template-parameter which is a
4147 // type shall be a type-id.
4148 ArgType = Arg.getAsType();
4149 TSI = AL.getTypeSourceInfo();
4150 break;
4151 case TemplateArgument::Template: {
4152 // We have a template type parameter but the template argument
4153 // is a template without any arguments.
4154 SourceRange SR = AL.getSourceRange();
4155 TemplateName Name = Arg.getAsTemplate();
4156 Diag(SR.getBegin(), diag::err_template_missing_args)
4157 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4158 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4159 Diag(Decl->getLocation(), diag::note_template_decl_here);
4160
4161 return true;
4162 }
4163 case TemplateArgument::Expression: {
4164 // We have a template type parameter but the template argument is an
4165 // expression; see if maybe it is missing the "typename" keyword.
4166 CXXScopeSpec SS;
4167 DeclarationNameInfo NameInfo;
4168
4169 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4170 SS.Adopt(ArgExpr->getQualifierLoc());
4171 NameInfo = ArgExpr->getNameInfo();
4172 } else if (DependentScopeDeclRefExpr *ArgExpr =
4173 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4174 SS.Adopt(ArgExpr->getQualifierLoc());
4175 NameInfo = ArgExpr->getNameInfo();
4176 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4177 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4178 if (ArgExpr->isImplicitAccess()) {
4179 SS.Adopt(ArgExpr->getQualifierLoc());
4180 NameInfo = ArgExpr->getMemberNameInfo();
4181 }
4182 }
4183
4184 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4185 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4186 LookupParsedName(Result, CurScope, &SS);
4187
4188 if (Result.getAsSingle<TypeDecl>() ||
4189 Result.getResultKind() ==
4190 LookupResult::NotFoundInCurrentInstantiation) {
4191 // Suggest that the user add 'typename' before the NNS.
4192 SourceLocation Loc = AL.getSourceRange().getBegin();
4193 Diag(Loc, getLangOpts().MSVCCompat
4194 ? diag::ext_ms_template_type_arg_missing_typename
4195 : diag::err_template_arg_must_be_type_suggest)
4196 << FixItHint::CreateInsertion(Loc, "typename ");
4197 Diag(Param->getLocation(), diag::note_template_param_here);
4198
4199 // Recover by synthesizing a type using the location information that we
4200 // already have.
4201 ArgType =
4202 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4203 TypeLocBuilder TLB;
4204 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4205 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4206 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4207 TL.setNameLoc(NameInfo.getLoc());
4208 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4209
4210 // Overwrite our input TemplateArgumentLoc so that we can recover
4211 // properly.
4212 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4213 TemplateArgumentLocInfo(TSI));
4214
4215 break;
4216 }
4217 }
4218 // fallthrough
4219 LLVM_FALLTHROUGH[[clang::fallthrough]];
4220 }
4221 default: {
4222 // We have a template type parameter but the template argument
4223 // is not a type.
4224 SourceRange SR = AL.getSourceRange();
4225 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4226 Diag(Param->getLocation(), diag::note_template_param_here);
4227
4228 return true;
4229 }
4230 }
4231
4232 if (CheckTemplateArgument(Param, TSI))
4233 return true;
4234
4235 // Add the converted template type argument.
4236 ArgType = Context.getCanonicalType(ArgType);
4237
4238 // Objective-C ARC:
4239 // If an explicitly-specified template argument type is a lifetime type
4240 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4241 if (getLangOpts().ObjCAutoRefCount &&
4242 ArgType->isObjCLifetimeType() &&
4243 !ArgType.getObjCLifetime()) {
4244 Qualifiers Qs;
4245 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4246 ArgType = Context.getQualifiedType(ArgType, Qs);
4247 }
4248
4249 Converted.push_back(TemplateArgument(ArgType));
4250 return false;
4251}
4252
4253/// \brief Substitute template arguments into the default template argument for
4254/// the given template type parameter.
4255///
4256/// \param SemaRef the semantic analysis object for which we are performing
4257/// the substitution.
4258///
4259/// \param Template the template that we are synthesizing template arguments
4260/// for.
4261///
4262/// \param TemplateLoc the location of the template name that started the
4263/// template-id we are checking.
4264///
4265/// \param RAngleLoc the location of the right angle bracket ('>') that
4266/// terminates the template-id.
4267///
4268/// \param Param the template template parameter whose default we are
4269/// substituting into.
4270///
4271/// \param Converted the list of template arguments provided for template
4272/// parameters that precede \p Param in the template parameter list.
4273/// \returns the substituted template argument, or NULL if an error occurred.
4274static TypeSourceInfo *
4275SubstDefaultTemplateArgument(Sema &SemaRef,
4276 TemplateDecl *Template,
4277 SourceLocation TemplateLoc,
4278 SourceLocation RAngleLoc,
4279 TemplateTypeParmDecl *Param,
4280 SmallVectorImpl<TemplateArgument> &Converted) {
4281 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4282
4283 // If the argument type is dependent, instantiate it now based
4284 // on the previously-computed template arguments.
4285 if (ArgType->getType()->isDependentType()) {
4286 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4287 Param, Template, Converted,
4288 SourceRange(TemplateLoc, RAngleLoc));
4289 if (Inst.isInvalid())
4290 return nullptr;
4291
4292 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4293
4294 // Only substitute for the innermost template argument list.
4295 MultiLevelTemplateArgumentList TemplateArgLists;
4296 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4297 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4298 TemplateArgLists.addOuterTemplateArguments(None);
4299
4300 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4301 ArgType =
4302 SemaRef.SubstType(ArgType, TemplateArgLists,
4303 Param->getDefaultArgumentLoc(), Param->getDeclName());
4304 }
4305
4306 return ArgType;
4307}
4308
4309/// \brief Substitute template arguments into the default template argument for
4310/// the given non-type template parameter.
4311///
4312/// \param SemaRef the semantic analysis object for which we are performing
4313/// the substitution.
4314///
4315/// \param Template the template that we are synthesizing template arguments
4316/// for.
4317///
4318/// \param TemplateLoc the location of the template name that started the
4319/// template-id we are checking.
4320///
4321/// \param RAngleLoc the location of the right angle bracket ('>') that
4322/// terminates the template-id.
4323///
4324/// \param Param the non-type template parameter whose default we are
4325/// substituting into.
4326///
4327/// \param Converted the list of template arguments provided for template
4328/// parameters that precede \p Param in the template parameter list.
4329///
4330/// \returns the substituted template argument, or NULL if an error occurred.
4331static ExprResult
4332SubstDefaultTemplateArgument(Sema &SemaRef,
4333 TemplateDecl *Template,
4334 SourceLocation TemplateLoc,
4335 SourceLocation RAngleLoc,
4336 NonTypeTemplateParmDecl *Param,
4337 SmallVectorImpl<TemplateArgument> &Converted) {
4338 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4339 Param, Template, Converted,
4340 SourceRange(TemplateLoc, RAngleLoc));
4341 if (Inst.isInvalid())
4342 return ExprError();
4343
4344 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4345
4346 // Only substitute for the innermost template argument list.
4347 MultiLevelTemplateArgumentList TemplateArgLists;
4348 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4349 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4350 TemplateArgLists.addOuterTemplateArguments(None);
4351
4352 EnterExpressionEvaluationContext ConstantEvaluated(
4353 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4354 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4355}
4356
4357/// \brief Substitute template arguments into the default template argument for
4358/// the given template template parameter.
4359///
4360/// \param SemaRef the semantic analysis object for which we are performing
4361/// the substitution.
4362///
4363/// \param Template the template that we are synthesizing template arguments
4364/// for.
4365///
4366/// \param TemplateLoc the location of the template name that started the
4367/// template-id we are checking.
4368///
4369/// \param RAngleLoc the location of the right angle bracket ('>') that
4370/// terminates the template-id.
4371///
4372/// \param Param the template template parameter whose default we are
4373/// substituting into.
4374///
4375/// \param Converted the list of template arguments provided for template
4376/// parameters that precede \p Param in the template parameter list.
4377///
4378/// \param QualifierLoc Will be set to the nested-name-specifier (with
4379/// source-location information) that precedes the template name.
4380///
4381/// \returns the substituted template argument, or NULL if an error occurred.
4382static TemplateName
4383SubstDefaultTemplateArgument(Sema &SemaRef,
4384 TemplateDecl *Template,
4385 SourceLocation TemplateLoc,
4386 SourceLocation RAngleLoc,
4387 TemplateTemplateParmDecl *Param,
4388 SmallVectorImpl<TemplateArgument> &Converted,
4389 NestedNameSpecifierLoc &QualifierLoc) {
4390 Sema::InstantiatingTemplate Inst(
4391 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4392 SourceRange(TemplateLoc, RAngleLoc));
4393 if (Inst.isInvalid())
4394 return TemplateName();
4395
4396 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4397
4398 // Only substitute for the innermost template argument list.
4399 MultiLevelTemplateArgumentList TemplateArgLists;
4400 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4401 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4402 TemplateArgLists.addOuterTemplateArguments(None);
4403
4404 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4405 // Substitute into the nested-name-specifier first,
4406 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4407 if (QualifierLoc) {
4408 QualifierLoc =
4409 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4410 if (!QualifierLoc)
4411 return TemplateName();
4412 }
4413
4414 return SemaRef.SubstTemplateName(
4415 QualifierLoc,
4416 Param->getDefaultArgument().getArgument().getAsTemplate(),
4417 Param->getDefaultArgument().getTemplateNameLoc(),
4418 TemplateArgLists);
4419}
4420
4421/// \brief If the given template parameter has a default template
4422/// argument, substitute into that default template argument and
4423/// return the corresponding template argument.
4424TemplateArgumentLoc
4425Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4426 SourceLocation TemplateLoc,
4427 SourceLocation RAngleLoc,
4428 Decl *Param,
4429 SmallVectorImpl<TemplateArgument>
4430 &Converted,
4431 bool &HasDefaultArg) {
4432 HasDefaultArg = false;
4433
4434 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4435 if (!hasVisibleDefaultArgument(TypeParm))
4436 return TemplateArgumentLoc();
4437
4438 HasDefaultArg = true;
4439 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4440 TemplateLoc,
4441 RAngleLoc,
4442 TypeParm,
4443 Converted);
4444 if (DI)
4445 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4446
4447 return TemplateArgumentLoc();
4448 }
4449
4450 if (NonTypeTemplateParmDecl *NonTypeParm
4451 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4452 if (!hasVisibleDefaultArgument(NonTypeParm))
4453 return TemplateArgumentLoc();
4454
4455 HasDefaultArg = true;
4456 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4457 TemplateLoc,
4458 RAngleLoc,
4459 NonTypeParm,
4460 Converted);
4461 if (Arg.isInvalid())
4462 return TemplateArgumentLoc();
4463
4464 Expr *ArgE = Arg.getAs<Expr>();
4465 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4466 }
4467
4468 TemplateTemplateParmDecl *TempTempParm
4469 = cast<TemplateTemplateParmDecl>(Param);
4470 if (!hasVisibleDefaultArgument(TempTempParm))
4471 return TemplateArgumentLoc();
4472
4473 HasDefaultArg = true;
4474 NestedNameSpecifierLoc QualifierLoc;
4475 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4476 TemplateLoc,
4477 RAngleLoc,
4478 TempTempParm,
4479 Converted,
4480 QualifierLoc);
4481 if (TName.isNull())
4482 return TemplateArgumentLoc();
4483
4484 return TemplateArgumentLoc(TemplateArgument(TName),
4485 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4486 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4487}
4488
4489/// Convert a template-argument that we parsed as a type into a template, if
4490/// possible. C++ permits injected-class-names to perform dual service as
4491/// template template arguments and as template type arguments.
4492static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4493 // Extract and step over any surrounding nested-name-specifier.
4494 NestedNameSpecifierLoc QualLoc;
4495 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4496 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4497 return TemplateArgumentLoc();
4498
4499 QualLoc = ETLoc.getQualifierLoc();
4500 TLoc = ETLoc.getNamedTypeLoc();
4501 }
4502
4503 // If this type was written as an injected-class-name, it can be used as a
4504 // template template argument.
4505 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4506 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4507 QualLoc, InjLoc.getNameLoc());
4508
4509 // If this type was written as an injected-class-name, it may have been
4510 // converted to a RecordType during instantiation. If the RecordType is
4511 // *not* wrapped in a TemplateSpecializationType and denotes a class
4512 // template specialization, it must have come from an injected-class-name.
4513 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4514 if (auto *CTSD =
4515 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4516 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4517 QualLoc, RecLoc.getNameLoc());
4518
4519 return TemplateArgumentLoc();
4520}
4521
4522/// \brief Check that the given template argument corresponds to the given
4523/// template parameter.
4524///
4525/// \param Param The template parameter against which the argument will be
4526/// checked.
4527///
4528/// \param Arg The template argument, which may be updated due to conversions.
4529///
4530/// \param Template The template in which the template argument resides.
4531///
4532/// \param TemplateLoc The location of the template name for the template
4533/// whose argument list we're matching.
4534///
4535/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4536/// the template argument list.
4537///
4538/// \param ArgumentPackIndex The index into the argument pack where this
4539/// argument will be placed. Only valid if the parameter is a parameter pack.
4540///
4541/// \param Converted The checked, converted argument will be added to the
4542/// end of this small vector.
4543///
4544/// \param CTAK Describes how we arrived at this particular template argument:
4545/// explicitly written, deduced, etc.
4546///
4547/// \returns true on error, false otherwise.
4548bool Sema::CheckTemplateArgument(NamedDecl *Param,
4549 TemplateArgumentLoc &Arg,
4550 NamedDecl *Template,
4551 SourceLocation TemplateLoc,
4552 SourceLocation RAngleLoc,
4553 unsigned ArgumentPackIndex,
4554 SmallVectorImpl<TemplateArgument> &Converted,
4555 CheckTemplateArgumentKind CTAK) {
4556 // Check template type parameters.
4557 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4558 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4559
4560 // Check non-type template parameters.
4561 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4562 // Do substitution on the type of the non-type template parameter
4563 // with the template arguments we've seen thus far. But if the
4564 // template has a dependent context then we cannot substitute yet.
4565 QualType NTTPType = NTTP->getType();
4566 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4567 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4568
4569 if (NTTPType->isDependentType() &&
4570 !isa<TemplateTemplateParmDecl>(Template) &&
4571 !Template->getDeclContext()->isDependentContext()) {
4572 // Do substitution on the type of the non-type template parameter.
4573 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4574 NTTP, Converted,
4575 SourceRange(TemplateLoc, RAngleLoc));
4576 if (Inst.isInvalid())
4577 return true;
4578
4579 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4580 Converted);
4581 NTTPType = SubstType(NTTPType,
4582 MultiLevelTemplateArgumentList(TemplateArgs),
4583 NTTP->getLocation(),
4584 NTTP->getDeclName());
4585 // If that worked, check the non-type template parameter type
4586 // for validity.
4587 if (!NTTPType.isNull())
4588 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4589 NTTP->getLocation());
4590 if (NTTPType.isNull())
4591 return true;
4592 }
4593
4594 switch (Arg.getArgument().getKind()) {
4595 case TemplateArgument::Null:
4596 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4596)
;
4597
4598 case TemplateArgument::Expression: {
4599 TemplateArgument Result;
4600 ExprResult Res =
4601 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4602 Result, CTAK);
4603 if (Res.isInvalid())
4604 return true;
4605
4606 // If the resulting expression is new, then use it in place of the
4607 // old expression in the template argument.
4608 if (Res.get() != Arg.getArgument().getAsExpr()) {
4609 TemplateArgument TA(Res.get());
4610 Arg = TemplateArgumentLoc(TA, Res.get());
4611 }
4612
4613 Converted.push_back(Result);
4614 break;
4615 }
4616
4617 case TemplateArgument::Declaration:
4618 case TemplateArgument::Integral:
4619 case TemplateArgument::NullPtr:
4620 // We've already checked this template argument, so just copy
4621 // it to the list of converted arguments.
4622 Converted.push_back(Arg.getArgument());
4623 break;
4624
4625 case TemplateArgument::Template:
4626 case TemplateArgument::TemplateExpansion:
4627 // We were given a template template argument. It may not be ill-formed;
4628 // see below.
4629 if (DependentTemplateName *DTN
4630 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4631 .getAsDependentTemplateName()) {
4632 // We have a template argument such as \c T::template X, which we
4633 // parsed as a template template argument. However, since we now
4634 // know that we need a non-type template argument, convert this
4635 // template name into an expression.
4636
4637 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4638 Arg.getTemplateNameLoc());
4639
4640 CXXScopeSpec SS;
4641 SS.Adopt(Arg.getTemplateQualifierLoc());
4642 // FIXME: the template-template arg was a DependentTemplateName,
4643 // so it was provided with a template keyword. However, its source
4644 // location is not stored in the template argument structure.
4645 SourceLocation TemplateKWLoc;
4646 ExprResult E = DependentScopeDeclRefExpr::Create(
4647 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4648 nullptr);
4649
4650 // If we parsed the template argument as a pack expansion, create a
4651 // pack expansion expression.
4652 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4653 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4654 if (E.isInvalid())
4655 return true;
4656 }
4657
4658 TemplateArgument Result;
4659 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4660 if (E.isInvalid())
4661 return true;
4662
4663 Converted.push_back(Result);
4664 break;
4665 }
4666
4667 // We have a template argument that actually does refer to a class
4668 // template, alias template, or template template parameter, and
4669 // therefore cannot be a non-type template argument.
4670 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4671 << Arg.getSourceRange();
4672
4673 Diag(Param->getLocation(), diag::note_template_param_here);
4674 return true;
4675
4676 case TemplateArgument::Type: {
4677 // We have a non-type template parameter but the template
4678 // argument is a type.
4679
4680 // C++ [temp.arg]p2:
4681 // In a template-argument, an ambiguity between a type-id and
4682 // an expression is resolved to a type-id, regardless of the
4683 // form of the corresponding template-parameter.
4684 //
4685 // We warn specifically about this case, since it can be rather
4686 // confusing for users.
4687 QualType T = Arg.getArgument().getAsType();
4688 SourceRange SR = Arg.getSourceRange();
4689 if (T->isFunctionType())
4690 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4691 else
4692 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4693 Diag(Param->getLocation(), diag::note_template_param_here);
4694 return true;
4695 }
4696
4697 case TemplateArgument::Pack:
4698 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4698)
;
4699 }
4700
4701 return false;
4702 }
4703
4704
4705 // Check template template parameters.
4706 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4707
4708 // Substitute into the template parameter list of the template
4709 // template parameter, since previously-supplied template arguments
4710 // may appear within the template template parameter.
4711 {
4712 // Set up a template instantiation context.
4713 LocalInstantiationScope Scope(*this);
4714 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4715 TempParm, Converted,
4716 SourceRange(TemplateLoc, RAngleLoc));
4717 if (Inst.isInvalid())
4718 return true;
4719
4720 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4721 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4722 SubstDecl(TempParm, CurContext,
4723 MultiLevelTemplateArgumentList(TemplateArgs)));
4724 if (!TempParm)
4725 return true;
4726 }
4727
4728 // C++1z [temp.local]p1: (DR1004)
4729 // When [the injected-class-name] is used [...] as a template-argument for
4730 // a template template-parameter [...] it refers to the class template
4731 // itself.
4732 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4733 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4734 Arg.getTypeSourceInfo()->getTypeLoc());
4735 if (!ConvertedArg.getArgument().isNull())
4736 Arg = ConvertedArg;
4737 }
4738
4739 switch (Arg.getArgument().getKind()) {
4740 case TemplateArgument::Null:
4741 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4741)
;
4742
4743 case TemplateArgument::Template:
4744 case TemplateArgument::TemplateExpansion:
4745 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4746 return true;
4747
4748 Converted.push_back(Arg.getArgument());
4749 break;
4750
4751 case TemplateArgument::Expression:
4752 case TemplateArgument::Type:
4753 // We have a template template parameter but the template
4754 // argument does not refer to a template.
4755 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4756 << getLangOpts().CPlusPlus11;
4757 return true;
4758
4759 case TemplateArgument::Declaration:
4760 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4760)
;
4761 case TemplateArgument::Integral:
4762 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4762)
;
4763 case TemplateArgument::NullPtr:
4764 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4764)
;
4765
4766 case TemplateArgument::Pack:
4767 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4767)
;
4768 }
4769
4770 return false;
4771}
4772
4773/// \brief Diagnose an arity mismatch in the
4774static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4775 SourceLocation TemplateLoc,
4776 TemplateArgumentListInfo &TemplateArgs) {
4777 TemplateParameterList *Params = Template->getTemplateParameters();
4778 unsigned NumParams = Params->size();
4779 unsigned NumArgs = TemplateArgs.size();
4780
4781 SourceRange Range;
4782 if (NumArgs > NumParams)
4783 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4784 TemplateArgs.getRAngleLoc());
4785 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4786 << (NumArgs > NumParams)
4787 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4788 << Template << Range;
4789 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4790 << Params->getSourceRange();
4791 return true;
4792}
4793
4794/// \brief Check whether the template parameter is a pack expansion, and if so,
4795/// determine the number of parameters produced by that expansion. For instance:
4796///
4797/// \code
4798/// template<typename ...Ts> struct A {
4799/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4800/// };
4801/// \endcode
4802///
4803/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4804/// is not a pack expansion, so returns an empty Optional.
4805static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4806 if (NonTypeTemplateParmDecl *NTTP
4807 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4808 if (NTTP->isExpandedParameterPack())
4809 return NTTP->getNumExpansionTypes();
4810 }
4811
4812 if (TemplateTemplateParmDecl *TTP
4813 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4814 if (TTP->isExpandedParameterPack())
4815 return TTP->getNumExpansionTemplateParameters();
4816 }
4817
4818 return None;
4819}
4820
4821/// Diagnose a missing template argument.
4822template<typename TemplateParmDecl>
4823static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4824 TemplateDecl *TD,
4825 const TemplateParmDecl *D,
4826 TemplateArgumentListInfo &Args) {
4827 // Dig out the most recent declaration of the template parameter; there may be
4828 // declarations of the template that are more recent than TD.
4829 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4830 ->getTemplateParameters()
4831 ->getParam(D->getIndex()));
4832
4833 // If there's a default argument that's not visible, diagnose that we're
4834 // missing a module import.
4835 llvm::SmallVector<Module*, 8> Modules;
4836 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4837 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4838 D->getDefaultArgumentLoc(), Modules,
4839 Sema::MissingImportKind::DefaultArgument,
4840 /*Recover*/true);
4841 return true;
4842 }
4843
4844 // FIXME: If there's a more recent default argument that *is* visible,
4845 // diagnose that it was declared too late.
4846
4847 return diagnoseArityMismatch(S, TD, Loc, Args);
4848}
4849
4850/// \brief Check that the given template argument list is well-formed
4851/// for specializing the given template.
4852bool Sema::CheckTemplateArgumentList(
4853 TemplateDecl *Template, SourceLocation TemplateLoc,
4854 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4855 SmallVectorImpl<TemplateArgument> &Converted,
4856 bool UpdateArgsWithConversions) {
4857 // Make a copy of the template arguments for processing. Only make the
4858 // changes at the end when successful in matching the arguments to the
4859 // template.
4860 TemplateArgumentListInfo NewArgs = TemplateArgs;
4861
4862 // Make sure we get the template parameter list from the most
4863 // recentdeclaration, since that is the only one that has is guaranteed to
4864 // have all the default template argument information.
4865 TemplateParameterList *Params =
4866 cast<TemplateDecl>(Template->getMostRecentDecl())
4867 ->getTemplateParameters();
4868
4869 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4870
4871 // C++ [temp.arg]p1:
4872 // [...] The type and form of each template-argument specified in
4873 // a template-id shall match the type and form specified for the
4874 // corresponding parameter declared by the template in its
4875 // template-parameter-list.
4876 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4877 SmallVector<TemplateArgument, 2> ArgumentPack;
4878 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4879 LocalInstantiationScope InstScope(*this, true);
4880 for (TemplateParameterList::iterator Param = Params->begin(),
4881 ParamEnd = Params->end();
4882 Param != ParamEnd; /* increment in loop */) {
4883 // If we have an expanded parameter pack, make sure we don't have too
4884 // many arguments.
4885 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4886 if (*Expansions == ArgumentPack.size()) {
4887 // We're done with this parameter pack. Pack up its arguments and add
4888 // them to the list.
4889 Converted.push_back(
4890 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4891 ArgumentPack.clear();
4892
4893 // This argument is assigned to the next parameter.
4894 ++Param;
4895 continue;
4896 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4897 // Not enough arguments for this parameter pack.
4898 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4899 << false
4900 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4901 << Template;
4902 Diag(Template->getLocation(), diag::note_template_decl_here)
4903 << Params->getSourceRange();
4904 return true;
4905 }
4906 }
4907
4908 if (ArgIdx < NumArgs) {
4909 // Check the template argument we were given.
4910 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4911 TemplateLoc, RAngleLoc,
4912 ArgumentPack.size(), Converted))
4913 return true;
4914
4915 bool PackExpansionIntoNonPack =
4916 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4917 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4918 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4919 // Core issue 1430: we have a pack expansion as an argument to an
4920 // alias template, and it's not part of a parameter pack. This
4921 // can't be canonicalized, so reject it now.
4922 Diag(NewArgs[ArgIdx].getLocation(),
4923 diag::err_alias_template_expansion_into_fixed_list)
4924 << NewArgs[ArgIdx].getSourceRange();
4925 Diag((*Param)->getLocation(), diag::note_template_param_here);
4926 return true;
4927 }
4928
4929 // We're now done with this argument.
4930 ++ArgIdx;
4931
4932 if ((*Param)->isTemplateParameterPack()) {
4933 // The template parameter was a template parameter pack, so take the
4934 // deduced argument and place it on the argument pack. Note that we
4935 // stay on the same template parameter so that we can deduce more
4936 // arguments.
4937 ArgumentPack.push_back(Converted.pop_back_val());
4938 } else {
4939 // Move to the next template parameter.
4940 ++Param;
4941 }
4942
4943 // If we just saw a pack expansion into a non-pack, then directly convert
4944 // the remaining arguments, because we don't know what parameters they'll
4945 // match up with.
4946 if (PackExpansionIntoNonPack) {
4947 if (!ArgumentPack.empty()) {
4948 // If we were part way through filling in an expanded parameter pack,
4949 // fall back to just producing individual arguments.
4950 Converted.insert(Converted.end(),
4951 ArgumentPack.begin(), ArgumentPack.end());
4952 ArgumentPack.clear();
4953 }
4954
4955 while (ArgIdx < NumArgs) {
4956 Converted.push_back(NewArgs[ArgIdx].getArgument());
4957 ++ArgIdx;
4958 }
4959
4960 return false;
4961 }
4962
4963 continue;
4964 }
4965
4966 // If we're checking a partial template argument list, we're done.
4967 if (PartialTemplateArgs) {
4968 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4969 Converted.push_back(
4970 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4971
4972 return false;
4973 }
4974
4975 // If we have a template parameter pack with no more corresponding
4976 // arguments, just break out now and we'll fill in the argument pack below.
4977 if ((*Param)->isTemplateParameterPack()) {
4978 assert(!getExpandedPackSize(*Param) &&(static_cast <bool> (!getExpandedPackSize(*Param) &&
"Should have dealt with this already") ? void (0) : __assert_fail
("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4979, __extension__ __PRETTY_FUNCTION__))
4979 "Should have dealt with this already")(static_cast <bool> (!getExpandedPackSize(*Param) &&
"Should have dealt with this already") ? void (0) : __assert_fail
("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4979, __extension__ __PRETTY_FUNCTION__))
;
4980
4981 // A non-expanded parameter pack before the end of the parameter list
4982 // only occurs for an ill-formed template parameter list, unless we've
4983 // got a partial argument list for a function template, so just bail out.
4984 if (Param + 1 != ParamEnd)
4985 return true;
4986
4987 Converted.push_back(
4988 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4989 ArgumentPack.clear();
4990
4991 ++Param;
4992 continue;
4993 }
4994
4995 // Check whether we have a default argument.
4996 TemplateArgumentLoc Arg;
4997
4998 // Retrieve the default template argument from the template
4999 // parameter. For each kind of template parameter, we substitute the
5000 // template arguments provided thus far and any "outer" template arguments
5001 // (when the template parameter was part of a nested template) into
5002 // the default argument.
5003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5004 if (!hasVisibleDefaultArgument(TTP))
5005 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5006 NewArgs);
5007
5008 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5009 Template,
5010 TemplateLoc,
5011 RAngleLoc,
5012 TTP,
5013 Converted);
5014 if (!ArgType)
5015 return true;
5016
5017 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5018 ArgType);
5019 } else if (NonTypeTemplateParmDecl *NTTP
5020 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5021 if (!hasVisibleDefaultArgument(NTTP))
5022 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5023 NewArgs);
5024
5025 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5026 TemplateLoc,
5027 RAngleLoc,
5028 NTTP,
5029 Converted);
5030 if (E.isInvalid())
5031 return true;
5032
5033 Expr *Ex = E.getAs<Expr>();
5034 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5035 } else {
5036 TemplateTemplateParmDecl *TempParm
5037 = cast<TemplateTemplateParmDecl>(*Param);
5038
5039 if (!hasVisibleDefaultArgument(TempParm))
5040 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5041 NewArgs);
5042
5043 NestedNameSpecifierLoc QualifierLoc;
5044 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5045 TemplateLoc,
5046 RAngleLoc,
5047 TempParm,
5048 Converted,
5049 QualifierLoc);
5050 if (Name.isNull())
5051 return true;
5052
5053 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5054 TempParm->getDefaultArgument().getTemplateNameLoc());
5055 }
5056
5057 // Introduce an instantiation record that describes where we are using
5058 // the default template argument. We're not actually instantiating a
5059 // template here, we just create this object to put a note into the
5060 // context stack.
5061 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5062 SourceRange(TemplateLoc, RAngleLoc));
5063 if (Inst.isInvalid())
5064 return true;
5065
5066 // Check the default template argument.
5067 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5068 RAngleLoc, 0, Converted))
5069 return true;
5070
5071 // Core issue 150 (assumed resolution): if this is a template template
5072 // parameter, keep track of the default template arguments from the
5073 // template definition.
5074 if (isTemplateTemplateParameter)
5075 NewArgs.addArgument(Arg);
5076
5077 // Move to the next template parameter and argument.
5078 ++Param;
5079 ++ArgIdx;
5080 }
5081
5082 // If we're performing a partial argument substitution, allow any trailing
5083 // pack expansions; they might be empty. This can happen even if
5084 // PartialTemplateArgs is false (the list of arguments is complete but
5085 // still dependent).
5086 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5087 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5088 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5089 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5090 }
5091
5092 // If we have any leftover arguments, then there were too many arguments.
5093 // Complain and fail.
5094 if (ArgIdx < NumArgs)
5095 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5096
5097 // No problems found with the new argument list, propagate changes back
5098 // to caller.
5099 if (UpdateArgsWithConversions)
5100 TemplateArgs = std::move(NewArgs);
5101
5102 return false;
5103}
5104
5105namespace {
5106 class UnnamedLocalNoLinkageFinder
5107 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5108 {
5109 Sema &S;
5110 SourceRange SR;
5111
5112 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5113
5114 public:
5115 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5116
5117 bool Visit(QualType T) {
5118 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5119 }
5120
5121#define TYPE(Class, Parent) \
5122 bool Visit##Class##Type(const Class##Type *);
5123#define ABSTRACT_TYPE(Class, Parent) \
5124 bool Visit##Class##Type(const Class##Type *) { return false; }
5125#define NON_CANONICAL_TYPE(Class, Parent) \
5126 bool Visit##Class##Type(const Class##Type *) { return false; }
5127#include "clang/AST/TypeNodes.def"
5128
5129 bool VisitTagDecl(const TagDecl *Tag);
5130 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5131 };
5132} // end anonymous namespace
5133
5134bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5135 return false;
5136}
5137
5138bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5139 return Visit(T->getElementType());
5140}
5141
5142bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5143 return Visit(T->getPointeeType());
5144}
5145
5146bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5147 const BlockPointerType* T) {
5148 return Visit(T->getPointeeType());
5149}
5150
5151bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5152 const LValueReferenceType* T) {
5153 return Visit(T->getPointeeType());
5154}
5155
5156bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5157 const RValueReferenceType* T) {
5158 return Visit(T->getPointeeType());
5159}
5160
5161bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5162 const MemberPointerType* T) {
5163 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5164}
5165
5166bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5167 const ConstantArrayType* T) {
5168 return Visit(T->getElementType());
5169}
5170
5171bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5172 const IncompleteArrayType* T) {
5173 return Visit(T->getElementType());
5174}
5175
5176bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5177 const VariableArrayType* T) {
5178 return Visit(T->getElementType());
5179}
5180
5181bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5182 const DependentSizedArrayType* T) {
5183 return Visit(T->getElementType());
5184}
5185
5186bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5187 const DependentSizedExtVectorType* T) {
5188 return Visit(T->getElementType());
5189}
5190
5191bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5192 const DependentAddressSpaceType *T) {
5193 return Visit(T->getPointeeType());
5194}
5195
5196bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5197 return Visit(T->getElementType());
5198}
5199
5200bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5201 return Visit(T->getElementType());
5202}
5203
5204bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5205 const FunctionProtoType* T) {
5206 for (const auto &A : T->param_types()) {
5207 if (Visit(A))
5208 return true;
5209 }
5210
5211 return Visit(T->getReturnType());
5212}
5213
5214bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5215 const FunctionNoProtoType* T) {
5216 return Visit(T->getReturnType());
5217}
5218
5219bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5220 const UnresolvedUsingType*) {
5221 return false;
5222}
5223
5224bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5225 return false;
5226}
5227
5228bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5229 return Visit(T->getUnderlyingType());
5230}
5231
5232bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5233 return false;
5234}
5235
5236bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5237 const UnaryTransformType*) {
5238 return false;
5239}
5240
5241bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5242 return Visit(T->getDeducedType());
5243}
5244
5245bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5246 const DeducedTemplateSpecializationType *T) {
5247 return Visit(T->getDeducedType());
5248}
5249
5250bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5251 return VisitTagDecl(T->getDecl());
5252}
5253
5254bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5255 return VisitTagDecl(T->getDecl());
5256}
5257
5258bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5259 const TemplateTypeParmType*) {
5260 return false;
5261}
5262
5263bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5264 const SubstTemplateTypeParmPackType *) {
5265 return false;
5266}
5267
5268bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5269 const TemplateSpecializationType*) {
5270 return false;
5271}
5272
5273bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5274 const InjectedClassNameType* T) {
5275 return VisitTagDecl(T->getDecl());
5276}
5277
5278bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5279 const DependentNameType* T) {
5280 return VisitNestedNameSpecifier(T->getQualifier());
5281}
5282
5283bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5284 const DependentTemplateSpecializationType* T) {
5285 return VisitNestedNameSpecifier(T->getQualifier());
5286}
5287
5288bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5289 const PackExpansionType* T) {
5290 return Visit(T->getPattern());
5291}
5292
5293bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5294 return false;
5295}
5296
5297bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5298 const ObjCInterfaceType *) {
5299 return false;
5300}
5301
5302bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5303 const ObjCObjectPointerType *) {
5304 return false;
5305}
5306
5307bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5308 return Visit(T->getValueType());
5309}
5310
5311bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5312 return false;
5313}
5314
5315bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5316 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5317 S.Diag(SR.getBegin(),
5318 S.getLangOpts().CPlusPlus11 ?
5319 diag::warn_cxx98_compat_template_arg_local_type :
5320 diag::ext_template_arg_local_type)
5321 << S.Context.getTypeDeclType(Tag) << SR;
5322 return true;
5323 }
5324
5325 if (!Tag->hasNameForLinkage()) {
5326 S.Diag(SR.getBegin(),
5327 S.getLangOpts().CPlusPlus11 ?
5328 diag::warn_cxx98_compat_template_arg_unnamed_type :
5329 diag::ext_template_arg_unnamed_type) << SR;
5330 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5331 return true;
5332 }
5333
5334 return false;
5335}
5336
5337bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5338 NestedNameSpecifier *NNS) {
5339 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5340 return true;
5341
5342 switch (NNS->getKind()) {
5343 case NestedNameSpecifier::Identifier:
5344 case NestedNameSpecifier::Namespace:
5345 case NestedNameSpecifier::NamespaceAlias:
5346 case NestedNameSpecifier::Global:
5347 case NestedNameSpecifier::Super:
5348 return false;
5349
5350 case NestedNameSpecifier::TypeSpec:
5351 case NestedNameSpecifier::TypeSpecWithTemplate:
5352 return Visit(QualType(NNS->getAsType(), 0));
5353 }
5354 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5354)
;
5355}
5356
5357/// \brief Check a template argument against its corresponding
5358/// template type parameter.
5359///
5360/// This routine implements the semantics of C++ [temp.arg.type]. It
5361/// returns true if an error occurred, and false otherwise.
5362bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5363 TypeSourceInfo *ArgInfo) {
5364 assert(ArgInfo && "invalid TypeSourceInfo")(static_cast <bool> (ArgInfo && "invalid TypeSourceInfo"
) ? void (0) : __assert_fail ("ArgInfo && \"invalid TypeSourceInfo\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5364, __extension__ __PRETTY_FUNCTION__))
;
5365 QualType Arg = ArgInfo->getType();
5366 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5367
5368 if (Arg->isVariablyModifiedType()) {
5369 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5370 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5371 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5372 }
5373
5374 // C++03 [temp.arg.type]p2:
5375 // A local type, a type with no linkage, an unnamed type or a type
5376 // compounded from any of these types shall not be used as a
5377 // template-argument for a template type-parameter.
5378 //
5379 // C++11 allows these, and even in C++03 we allow them as an extension with
5380 // a warning.
5381 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5382 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5383 (void)Finder.Visit(Context.getCanonicalType(Arg));
5384 }
5385
5386 return false;
5387}
5388
5389enum NullPointerValueKind {
5390 NPV_NotNullPointer,
5391 NPV_NullPointer,
5392 NPV_Error
5393};
5394
5395/// \brief Determine whether the given template argument is a null pointer
5396/// value of the appropriate type.
5397static NullPointerValueKind
5398isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5399 QualType ParamType, Expr *Arg,
5400 Decl *Entity = nullptr) {
5401 if (Arg->isValueDependent() || Arg->isTypeDependent())
5402 return NPV_NotNullPointer;
5403
5404 // dllimport'd entities aren't constant but are available inside of template
5405 // arguments.
5406 if (Entity && Entity->hasAttr<DLLImportAttr>())
5407 return NPV_NotNullPointer;
5408
5409 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5410 llvm_unreachable(::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5411)
5411 "Incomplete parameter type in isNullPointerValueTemplateArgument!")::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5411)
;
5412
5413 if (!S.getLangOpts().CPlusPlus11)
5414 return NPV_NotNullPointer;
5415
5416 // Determine whether we have a constant expression.
5417 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5418 if (ArgRV.isInvalid())
5419 return NPV_Error;
5420 Arg = ArgRV.get();
5421
5422 Expr::EvalResult EvalResult;
5423 SmallVector<PartialDiagnosticAt, 8> Notes;
5424 EvalResult.Diag = &Notes;
5425 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5426 EvalResult.HasSideEffects) {
5427 SourceLocation DiagLoc = Arg->getExprLoc();
5428
5429 // If our only note is the usual "invalid subexpression" note, just point
5430 // the caret at its location rather than producing an essentially
5431 // redundant note.
5432 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5433 diag::note_invalid_subexpr_in_const_expr) {
5434 DiagLoc = Notes[0].first;
5435 Notes.clear();
5436 }
5437
5438 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5439 << Arg->getType() << Arg->getSourceRange();
5440 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5441 S.Diag(Notes[I].first, Notes[I].second);
5442
5443 S.Diag(Param->getLocation(), diag::note_template_param_here);
5444 return NPV_Error;
5445 }
5446
5447 // C++11 [temp.arg.nontype]p1:
5448 // - an address constant expression of type std::nullptr_t
5449 if (Arg->getType()->isNullPtrType())
5450 return NPV_NullPointer;
5451
5452 // - a constant expression that evaluates to a null pointer value (4.10); or
5453 // - a constant expression that evaluates to a null member pointer value
5454 // (4.11); or
5455 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5456 (EvalResult.Val.isMemberPointer() &&
5457 !EvalResult.Val.getMemberPointerDecl())) {
5458 // If our expression has an appropriate type, we've succeeded.
5459 bool ObjCLifetimeConversion;
5460 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5461 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5462 ObjCLifetimeConversion))
5463 return NPV_NullPointer;
5464
5465 // The types didn't match, but we know we got a null pointer; complain,
5466 // then recover as if the types were correct.
5467 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5468 << Arg->getType() << ParamType << Arg->getSourceRange();
5469 S.Diag(Param->getLocation(), diag::note_template_param_here);
5470 return NPV_NullPointer;
5471 }
5472
5473 // If we don't have a null pointer value, but we do have a NULL pointer
5474 // constant, suggest a cast to the appropriate type.
5475 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5476 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5477 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5478 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5479 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5480 ")");
5481 S.Diag(Param->getLocation(), diag::note_template_param_here);
5482 return NPV_NullPointer;
5483 }
5484
5485 // FIXME: If we ever want to support general, address-constant expressions
5486 // as non-type template arguments, we should return the ExprResult here to
5487 // be interpreted by the caller.
5488 return NPV_NotNullPointer;
5489}
5490
5491/// \brief Checks whether the given template argument is compatible with its
5492/// template parameter.
5493static bool CheckTemplateArgumentIsCompatibleWithParameter(
5494 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5495 Expr *Arg, QualType ArgType) {
5496 bool ObjCLifetimeConversion;
5497 if (ParamType->isPointerType() &&
5498 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5499 S.IsQualificationConversion(ArgType, ParamType, false,
5500 ObjCLifetimeConversion)) {
5501 // For pointer-to-object types, qualification conversions are
5502 // permitted.
5503 } else {
5504 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5505 if (!ParamRef->getPointeeType()->isFunctionType()) {
5506 // C++ [temp.arg.nontype]p5b3:
5507 // For a non-type template-parameter of type reference to
5508 // object, no conversions apply. The type referred to by the
5509 // reference may be more cv-qualified than the (otherwise
5510 // identical) type of the template- argument. The
5511 // template-parameter is bound directly to the
5512 // template-argument, which shall be an lvalue.
5513
5514 // FIXME: Other qualifiers?
5515 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5516 unsigned ArgQuals = ArgType.getCVRQualifiers();
5517
5518 if ((ParamQuals | ArgQuals) != ParamQuals) {
5519 S.Diag(Arg->getLocStart(),
5520 diag::err_template_arg_ref_bind_ignores_quals)
5521 << ParamType << Arg->getType() << Arg->getSourceRange();
5522 S.Diag(Param->getLocation(), diag::note_template_param_here);
5523 return true;
5524 }
5525 }
5526 }
5527
5528 // At this point, the template argument refers to an object or
5529 // function with external linkage. We now need to check whether the
5530 // argument and parameter types are compatible.
5531 if (!S.Context.hasSameUnqualifiedType(ArgType,
5532 ParamType.getNonReferenceType())) {
5533 // We can't perform this conversion or binding.
5534 if (ParamType->isReferenceType())
5535 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5536 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5537 else
5538 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5539 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5540 S.Diag(Param->getLocation(), diag::note_template_param_here);
5541 return true;
5542 }
5543 }
5544
5545 return false;
5546}
5547
5548/// \brief Checks whether the given template argument is the address
5549/// of an object or function according to C++ [temp.arg.nontype]p1.
5550static bool
5551CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5552 NonTypeTemplateParmDecl *Param,
5553 QualType ParamType,
5554 Expr *ArgIn,
5555 TemplateArgument &Converted) {
5556 bool Invalid = false;
5557 Expr *Arg = ArgIn;
5558 QualType ArgType = Arg->getType();
5559
5560 bool AddressTaken = false;
5561 SourceLocation AddrOpLoc;
5562 if (S.getLangOpts().MicrosoftExt) {
5563 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5564 // dereference and address-of operators.
5565 Arg = Arg->IgnoreParenCasts();
5566
5567 bool ExtWarnMSTemplateArg = false;
5568 UnaryOperatorKind FirstOpKind;
5569 SourceLocation FirstOpLoc;
5570 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5571 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5572 if (UnOpKind == UO_Deref)
5573 ExtWarnMSTemplateArg = true;
5574 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5575 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5576 if (!AddrOpLoc.isValid()) {
5577 FirstOpKind = UnOpKind;
5578 FirstOpLoc = UnOp->getOperatorLoc();
5579 }
5580 } else
5581 break;
5582 }
5583 if (FirstOpLoc.isValid()) {
5584 if (ExtWarnMSTemplateArg)
5585 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5586 << ArgIn->getSourceRange();
5587
5588 if (FirstOpKind == UO_AddrOf)
5589 AddressTaken = true;
5590 else if (Arg->getType()->isPointerType()) {
5591 // We cannot let pointers get dereferenced here, that is obviously not a
5592 // constant expression.
5593 assert(FirstOpKind == UO_Deref)(static_cast <bool> (FirstOpKind == UO_Deref) ? void (0
) : __assert_fail ("FirstOpKind == UO_Deref", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5593, __extension__ __PRETTY_FUNCTION__))
;
5594 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5595 << Arg->getSourceRange();
5596 }
5597 }
5598 } else {
5599 // See through any implicit casts we added to fix the type.
5600 Arg = Arg->IgnoreImpCasts();
5601
5602 // C++ [temp.arg.nontype]p1:
5603 //
5604 // A template-argument for a non-type, non-template
5605 // template-parameter shall be one of: [...]
5606 //
5607 // -- the address of an object or function with external
5608 // linkage, including function templates and function
5609 // template-ids but excluding non-static class members,
5610 // expressed as & id-expression where the & is optional if
5611 // the name refers to a function or array, or if the
5612 // corresponding template-parameter is a reference; or
5613
5614 // In C++98/03 mode, give an extension warning on any extra parentheses.
5615 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5616 bool ExtraParens = false;
5617 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5618 if (!Invalid && !ExtraParens) {
5619 S.Diag(Arg->getLocStart(),
5620 S.getLangOpts().CPlusPlus11
5621 ? diag::warn_cxx98_compat_template_arg_extra_parens
5622 : diag::ext_template_arg_extra_parens)
5623 << Arg->getSourceRange();
5624 ExtraParens = true;
5625 }
5626
5627 Arg = Parens->getSubExpr();
5628 }
5629
5630 while (SubstNonTypeTemplateParmExpr *subst =
5631 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5632 Arg = subst->getReplacement()->IgnoreImpCasts();
5633
5634 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5635 if (UnOp->getOpcode() == UO_AddrOf) {
5636 Arg = UnOp->getSubExpr();
5637 AddressTaken = true;
5638 AddrOpLoc = UnOp->getOperatorLoc();
5639 }
5640 }
5641
5642 while (SubstNonTypeTemplateParmExpr *subst =
5643 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5644 Arg = subst->getReplacement()->IgnoreImpCasts();
5645 }
5646
5647 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5648 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5649
5650 // If our parameter has pointer type, check for a null template value.
5651 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5652 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5653 Entity)) {
5654 case NPV_NullPointer:
5655 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5656 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5657 /*isNullPtr=*/true);
5658 return false;
5659
5660 case NPV_Error:
5661 return true;
5662
5663 case NPV_NotNullPointer:
5664 break;
5665 }
5666 }
5667
5668 // Stop checking the precise nature of the argument if it is value dependent,
5669 // it should be checked when instantiated.
5670 if (Arg->isValueDependent()) {
5671 Converted = TemplateArgument(ArgIn);
5672 return false;
5673 }
5674
5675 if (isa<CXXUuidofExpr>(Arg)) {
5676 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5677 ArgIn, Arg, ArgType))
5678 return true;
5679
5680 Converted = TemplateArgument(ArgIn);
5681 return false;
5682 }
5683
5684 if (!DRE) {
5685 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5686 << Arg->getSourceRange();
5687 S.Diag(Param->getLocation(), diag::note_template_param_here);
5688 return true;
5689 }
5690
5691 // Cannot refer to non-static data members
5692 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5693 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5694 << Entity << Arg->getSourceRange();
5695 S.Diag(Param->getLocation(), diag::note_template_param_here);
5696 return true;
5697 }
5698
5699 // Cannot refer to non-static member functions
5700 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5701 if (!Method->isStatic()) {
5702 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5703 << Method << Arg->getSourceRange();
5704 S.Diag(Param->getLocation(), diag::note_template_param_here);
5705 return true;
5706 }
5707 }
5708
5709 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5710 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5711
5712 // A non-type template argument must refer to an object or function.
5713 if (!Func && !Var) {
5714 // We found something, but we don't know specifically what it is.
5715 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5716 << Arg->getSourceRange();
5717 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5718 return true;
5719 }
5720
5721 // Address / reference template args must have external linkage in C++98.
5722 if (Entity->getFormalLinkage() == InternalLinkage) {
5723 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5724 diag::warn_cxx98_compat_template_arg_object_internal :
5725 diag::ext_template_arg_object_internal)
5726 << !Func << Entity << Arg->getSourceRange();
5727 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5728 << !Func;
5729 } else if (!Entity->hasLinkage()) {
5730 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5731 << !Func << Entity << Arg->getSourceRange();
5732 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5733 << !Func;
5734 return true;
5735 }
5736
5737 if (Func) {
5738 // If the template parameter has pointer type, the function decays.
5739 if (ParamType->isPointerType() && !AddressTaken)
5740 ArgType = S.Context.getPointerType(Func->getType());
5741 else if (AddressTaken && ParamType->isReferenceType()) {
5742 // If we originally had an address-of operator, but the
5743 // parameter has reference type, complain and (if things look
5744 // like they will work) drop the address-of operator.
5745 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5746 ParamType.getNonReferenceType())) {
5747 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5748 << ParamType;
5749 S.Diag(Param->getLocation(), diag::note_template_param_here);
5750 return true;
5751 }
5752
5753 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5754 << ParamType
5755 << FixItHint::CreateRemoval(AddrOpLoc);
5756 S.Diag(Param->getLocation(), diag::note_template_param_here);
5757
5758 ArgType = Func->getType();
5759 }
5760 } else {
5761 // A value of reference type is not an object.
5762 if (Var->getType()->isReferenceType()) {
5763 S.Diag(Arg->getLocStart(),
5764 diag::err_template_arg_reference_var)
5765 << Var->getType() << Arg->getSourceRange();
5766 S.Diag(Param->getLocation(), diag::note_template_param_here);
5767 return true;
5768 }
5769
5770 // A template argument must have static storage duration.
5771 if (Var->getTLSKind()) {
5772 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5773 << Arg->getSourceRange();
5774 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5775 return true;
5776 }
5777
5778 // If the template parameter has pointer type, we must have taken
5779 // the address of this object.
5780 if (ParamType->isReferenceType()) {
5781 if (AddressTaken) {
5782 // If we originally had an address-of operator, but the
5783 // parameter has reference type, complain and (if things look
5784 // like they will work) drop the address-of operator.
5785 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5786 ParamType.getNonReferenceType())) {
5787 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5788 << ParamType;
5789 S.Diag(Param->getLocation(), diag::note_template_param_here);
5790 return true;
5791 }
5792
5793 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5794 << ParamType
5795 << FixItHint::CreateRemoval(AddrOpLoc);
5796 S.Diag(Param->getLocation(), diag::note_template_param_here);
5797
5798 ArgType = Var->getType();
5799 }
5800 } else if (!AddressTaken && ParamType->isPointerType()) {
5801 if (Var->getType()->isArrayType()) {
5802 // Array-to-pointer decay.
5803 ArgType = S.Context.getArrayDecayedType(Var->getType());
5804 } else {
5805 // If the template parameter has pointer type but the address of
5806 // this object was not taken, complain and (possibly) recover by
5807 // taking the address of the entity.
5808 ArgType = S.Context.getPointerType(Var->getType());
5809 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5810 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5811 << ParamType;
5812 S.Diag(Param->getLocation(), diag::note_template_param_here);
5813 return true;
5814 }
5815
5816 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5817 << ParamType
5818 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5819
5820 S.Diag(Param->getLocation(), diag::note_template_param_here);
5821 }
5822 }
5823 }
5824
5825 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5826 Arg, ArgType))
5827 return true;
5828
5829 // Create the template argument.
5830 Converted =
5831 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5832 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5833 return false;
5834}
5835
5836/// \brief Checks whether the given template argument is a pointer to
5837/// member constant according to C++ [temp.arg.nontype]p1.
5838static bool CheckTemplateArgumentPointerToMember(Sema &S,
5839 NonTypeTemplateParmDecl *Param,
5840 QualType ParamType,
5841 Expr *&ResultArg,
5842 TemplateArgument &Converted) {
5843 bool Invalid = false;
5844
5845 Expr *Arg = ResultArg;
5846 bool ObjCLifetimeConversion;
5847
5848 // C++ [temp.arg.nontype]p1:
5849 //
5850 // A template-argument for a non-type, non-template
5851 // template-parameter shall be one of: [...]
5852 //
5853 // -- a pointer to member expressed as described in 5.3.1.
5854 DeclRefExpr *DRE = nullptr;
5855
5856 // In C++98/03 mode, give an extension warning on any extra parentheses.
5857 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5858 bool ExtraParens = false;
5859 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5860 if (!Invalid && !ExtraParens) {
5861 S.Diag(Arg->getLocStart(),
5862 S.getLangOpts().CPlusPlus11 ?
5863 diag::warn_cxx98_compat_template_arg_extra_parens :
5864 diag::ext_template_arg_extra_parens)
5865 << Arg->getSourceRange();
5866 ExtraParens = true;
5867 }
5868
5869 Arg = Parens->getSubExpr();
5870 }
5871
5872 while (SubstNonTypeTemplateParmExpr *subst =
5873 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5874 Arg = subst->getReplacement()->IgnoreImpCasts();
5875
5876 // A pointer-to-member constant written &Class::member.
5877 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5878 if (UnOp->getOpcode() == UO_AddrOf) {
5879 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5880 if (DRE && !DRE->getQualifier())
5881 DRE = nullptr;
5882 }
5883 }
5884 // A constant of pointer-to-member type.
5885 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5886 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5887 if (VD->getType()->isMemberPointerType()) {
5888 if (isa<NonTypeTemplateParmDecl>(VD)) {
5889 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5890 Converted = TemplateArgument(Arg);
5891 } else {
5892 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5893 Converted = TemplateArgument(VD, ParamType);
5894 }
5895 return Invalid;
5896 }
5897 }
5898 }
5899
5900 DRE = nullptr;
5901 }
5902
5903 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5904
5905 // Check for a null pointer value.
5906 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5907 Entity)) {
5908 case NPV_Error:
5909 return true;
5910 case NPV_NullPointer:
5911 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5912 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5913 /*isNullPtr*/true);
5914 return false;
5915 case NPV_NotNullPointer:
5916 break;
5917 }
5918
5919 if (S.IsQualificationConversion(ResultArg->getType(),
5920 ParamType.getNonReferenceType(), false,
5921 ObjCLifetimeConversion)) {
5922 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5923 ResultArg->getValueKind())
5924 .get();
5925 } else if (!S.Context.hasSameUnqualifiedType(
5926 ResultArg->getType(), ParamType.getNonReferenceType())) {
5927 // We can't perform this conversion.
5928 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5929 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5930 S.Diag(Param->getLocation(), diag::note_template_param_here);
5931 return true;
5932 }
5933
5934 if (!DRE)
5935 return S.Diag(Arg->getLocStart(),
5936 diag::err_template_arg_not_pointer_to_member_form)
5937 << Arg->getSourceRange();
5938
5939 if (isa<FieldDecl>(DRE->getDecl()) ||
5940 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5941 isa<CXXMethodDecl>(DRE->getDecl())) {
5942 assert((isa<FieldDecl>(DRE->getDecl()) ||(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? void (
0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5945, __extension__ __PRETTY_FUNCTION__))
5943 isa<IndirectFieldDecl>(DRE->getDecl()) ||(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? void (
0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5945, __extension__ __PRETTY_FUNCTION__))
5944 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? void (
0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5945, __extension__ __PRETTY_FUNCTION__))
5945 "Only non-static member pointers can make it here")(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? void (
0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5945, __extension__ __PRETTY_FUNCTION__))
;
5946
5947 // Okay: this is the address of a non-static member, and therefore
5948 // a member pointer constant.
5949 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5950 Converted = TemplateArgument(Arg);
5951 } else {
5952 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5953 Converted = TemplateArgument(D, ParamType);
5954 }
5955 return Invalid;
5956 }
5957
5958 // We found something else, but we don't know specifically what it is.
5959 S.Diag(Arg->getLocStart(),
5960 diag::err_template_arg_not_pointer_to_member_form)
5961 << Arg->getSourceRange();
5962 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5963 return true;
5964}
5965
5966/// \brief Check a template argument against its corresponding
5967/// non-type template parameter.
5968///
5969/// This routine implements the semantics of C++ [temp.arg.nontype].
5970/// If an error occurred, it returns ExprError(); otherwise, it
5971/// returns the converted template argument. \p ParamType is the
5972/// type of the non-type template parameter after it has been instantiated.
5973ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5974 QualType ParamType, Expr *Arg,
5975 TemplateArgument &Converted,
5976 CheckTemplateArgumentKind CTAK) {
5977 SourceLocation StartLoc = Arg->getLocStart();
5978
5979 // If the parameter type somehow involves auto, deduce the type now.
5980 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
5981 // During template argument deduction, we allow 'decltype(auto)' to
5982 // match an arbitrary dependent argument.
5983 // FIXME: The language rules don't say what happens in this case.
5984 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5985 // expression is merely instantiation-dependent; is this enough?
5986 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5987 auto *AT = dyn_cast<AutoType>(ParamType);
5988 if (AT && AT->isDecltypeAuto()) {
5989 Converted = TemplateArgument(Arg);
5990 return Arg;
5991 }
5992 }
5993
5994 // When checking a deduced template argument, deduce from its type even if
5995 // the type is dependent, in order to check the types of non-type template
5996 // arguments line up properly in partial ordering.
5997 Optional<unsigned> Depth;
5998 if (CTAK != CTAK_Specified)
5999 Depth = Param->getDepth() + 1;
6000 if (DeduceAutoType(
6001 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6002 Arg, ParamType, Depth) == DAR_Failed) {
6003 Diag(Arg->getExprLoc(),
6004 diag::err_non_type_template_parm_type_deduction_failure)
6005 << Param->getDeclName() << Param->getType() << Arg->getType()
6006 << Arg->getSourceRange();
6007 Diag(Param->getLocation(), diag::note_template_param_here);
6008</