Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 1827, column 31
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')

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 SemaTemplateInstantiate.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~svn326551/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/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~svn326551/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-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
13#include "clang/Sema/SemaInternal.h"
14#include "TreeTransform.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/PrettyDeclStackTrace.h"
26#include "clang/Sema/Template.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "clang/Sema/TemplateInstCallback.h"
29
30using namespace clang;
31using namespace sema;
32
33//===----------------------------------------------------------------------===/
34// Template Instantiation Support
35//===----------------------------------------------------------------------===/
36
37/// \brief Retrieve the template argument list(s) that should be used to
38/// instantiate the definition of the given declaration.
39///
40/// \param D the declaration for which we are computing template instantiation
41/// arguments.
42///
43/// \param Innermost if non-NULL, the innermost template argument list.
44///
45/// \param RelativeToPrimary true if we should get the template
46/// arguments relative to the primary template, even when we're
47/// dealing with a specialization. This is only relevant for function
48/// template specializations.
49///
50/// \param Pattern If non-NULL, indicates the pattern from which we will be
51/// instantiating the definition of the given declaration, \p D. This is
52/// used to determine the proper set of template instantiation arguments for
53/// friend function template specializations.
54MultiLevelTemplateArgumentList
55Sema::getTemplateInstantiationArgs(NamedDecl *D,
56 const TemplateArgumentList *Innermost,
57 bool RelativeToPrimary,
58 const FunctionDecl *Pattern) {
59 // Accumulate the set of template argument lists in this structure.
60 MultiLevelTemplateArgumentList Result;
61
62 if (Innermost)
63 Result.addOuterTemplateArguments(Innermost);
64
65 DeclContext *Ctx = dyn_cast<DeclContext>(D);
66 if (!Ctx) {
67 Ctx = D->getDeclContext();
68
69 // Add template arguments from a variable template instantiation.
70 if (VarTemplateSpecializationDecl *Spec =
71 dyn_cast<VarTemplateSpecializationDecl>(D)) {
72 // We're done when we hit an explicit specialization.
73 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
74 !isa<VarTemplatePartialSpecializationDecl>(Spec))
75 return Result;
76
77 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
78
79 // If this variable template specialization was instantiated from a
80 // specialized member that is a variable template, we're done.
81 assert(Spec->getSpecializedTemplate() && "No variable template?")(static_cast <bool> (Spec->getSpecializedTemplate() &&
"No variable template?") ? void (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No variable template?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 81, __extension__ __PRETTY_FUNCTION__))
;
82 llvm::PointerUnion<VarTemplateDecl*,
83 VarTemplatePartialSpecializationDecl*> Specialized
84 = Spec->getSpecializedTemplateOrPartial();
85 if (VarTemplatePartialSpecializationDecl *Partial =
86 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
87 if (Partial->isMemberSpecialization())
88 return Result;
89 } else {
90 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
91 if (Tmpl->isMemberSpecialization())
92 return Result;
93 }
94 }
95
96 // If we have a template template parameter with translation unit context,
97 // then we're performing substitution into a default template argument of
98 // this template template parameter before we've constructed the template
99 // that will own this template template parameter. In this case, we
100 // use empty template parameter lists for all of the outer templates
101 // to avoid performing any substitutions.
102 if (Ctx->isTranslationUnit()) {
103 if (TemplateTemplateParmDecl *TTP
104 = dyn_cast<TemplateTemplateParmDecl>(D)) {
105 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
106 Result.addOuterTemplateArguments(None);
107 return Result;
108 }
109 }
110 }
111
112 while (!Ctx->isFileContext()) {
113 // Add template arguments from a class template instantiation.
114 if (ClassTemplateSpecializationDecl *Spec
115 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
116 // We're done when we hit an explicit specialization.
117 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
118 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
119 break;
120
121 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
122
123 // If this class template specialization was instantiated from a
124 // specialized member that is a class template, we're done.
125 assert(Spec->getSpecializedTemplate() && "No class template?")(static_cast <bool> (Spec->getSpecializedTemplate() &&
"No class template?") ? void (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No class template?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 125, __extension__ __PRETTY_FUNCTION__))
;
126 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
127 break;
128 }
129 // Add template arguments from a function template specialization.
130 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
131 if (!RelativeToPrimary &&
132 (Function->getTemplateSpecializationKind() ==
133 TSK_ExplicitSpecialization &&
134 !Function->getClassScopeSpecializationPattern()))
135 break;
136
137 if (const TemplateArgumentList *TemplateArgs
138 = Function->getTemplateSpecializationArgs()) {
139 // Add the template arguments for this specialization.
140 Result.addOuterTemplateArguments(TemplateArgs);
141
142 // If this function was instantiated from a specialized member that is
143 // a function template, we're done.
144 assert(Function->getPrimaryTemplate() && "No function template?")(static_cast <bool> (Function->getPrimaryTemplate() &&
"No function template?") ? void (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 144, __extension__ __PRETTY_FUNCTION__))
;
145 if (Function->getPrimaryTemplate()->isMemberSpecialization())
146 break;
147
148 // If this function is a generic lambda specialization, we are done.
149 if (isGenericLambdaCallOperatorSpecialization(Function))
150 break;
151
152 } else if (FunctionTemplateDecl *FunTmpl
153 = Function->getDescribedFunctionTemplate()) {
154 // Add the "injected" template arguments.
155 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
156 }
157
158 // If this is a friend declaration and it declares an entity at
159 // namespace scope, take arguments from its lexical parent
160 // instead of its semantic parent, unless of course the pattern we're
161 // instantiating actually comes from the file's context!
162 if (Function->getFriendObjectKind() &&
163 Function->getDeclContext()->isFileContext() &&
164 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
165 Ctx = Function->getLexicalDeclContext();
166 RelativeToPrimary = false;
167 continue;
168 }
169 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
170 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
171 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
172 const TemplateSpecializationType *TST =
173 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
174 Result.addOuterTemplateArguments(
175 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
176 if (ClassTemplate->isMemberSpecialization())
177 break;
178 }
179 }
180
181 Ctx = Ctx->getParent();
182 RelativeToPrimary = false;
183 }
184
185 return Result;
186}
187
188bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
189 switch (Kind) {
190 case TemplateInstantiation:
191 case ExceptionSpecInstantiation:
192 case DefaultTemplateArgumentInstantiation:
193 case DefaultFunctionArgumentInstantiation:
194 case ExplicitTemplateArgumentSubstitution:
195 case DeducedTemplateArgumentSubstitution:
196 case PriorTemplateArgumentSubstitution:
197 return true;
198
199 case DefaultTemplateArgumentChecking:
200 case DeclaringSpecialMember:
201 case DefiningSynthesizedFunction:
202 return false;
203
204 // This function should never be called when Kind's value is Memoization.
205 case Memoization:
206 break;
207 }
208
209 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 209)
;
210}
211
212Sema::InstantiatingTemplate::InstantiatingTemplate(
213 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
214 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
215 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
216 sema::TemplateDeductionInfo *DeductionInfo)
217 : SemaRef(SemaRef) {
218 // Don't allow further instantiation if a fatal error and an uncompilable
219 // error have occurred. Any diagnostics we might have raised will not be
220 // visible, and we do not need to construct a correct AST.
221 if (SemaRef.Diags.hasFatalErrorOccurred() &&
222 SemaRef.Diags.hasUncompilableErrorOccurred()) {
223 Invalid = true;
224 return;
225 }
226 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
227 if (!Invalid) {
228 CodeSynthesisContext Inst;
229 Inst.Kind = Kind;
230 Inst.PointOfInstantiation = PointOfInstantiation;
231 Inst.Entity = Entity;
232 Inst.Template = Template;
233 Inst.TemplateArgs = TemplateArgs.data();
234 Inst.NumTemplateArgs = TemplateArgs.size();
235 Inst.DeductionInfo = DeductionInfo;
236 Inst.InstantiationRange = InstantiationRange;
237 SemaRef.pushCodeSynthesisContext(Inst);
238
239 AlreadyInstantiating =
240 !SemaRef.InstantiatingSpecializations
241 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
242 .second;
243 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
244 }
245}
246
247Sema::InstantiatingTemplate::InstantiatingTemplate(
248 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
249 SourceRange InstantiationRange)
250 : InstantiatingTemplate(SemaRef,
251 CodeSynthesisContext::TemplateInstantiation,
252 PointOfInstantiation, InstantiationRange, Entity) {}
253
254Sema::InstantiatingTemplate::InstantiatingTemplate(
255 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
256 ExceptionSpecification, SourceRange InstantiationRange)
257 : InstantiatingTemplate(
258 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
259 PointOfInstantiation, InstantiationRange, Entity) {}
260
261Sema::InstantiatingTemplate::InstantiatingTemplate(
262 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
263 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
264 SourceRange InstantiationRange)
265 : InstantiatingTemplate(
266 SemaRef,
267 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
268 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
269 Template, TemplateArgs) {}
270
271Sema::InstantiatingTemplate::InstantiatingTemplate(
272 Sema &SemaRef, SourceLocation PointOfInstantiation,
273 FunctionTemplateDecl *FunctionTemplate,
274 ArrayRef<TemplateArgument> TemplateArgs,
275 CodeSynthesisContext::SynthesisKind Kind,
276 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
277 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
278 InstantiationRange, FunctionTemplate, nullptr,
279 TemplateArgs, &DeductionInfo) {
280 assert((static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
281 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
282 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
;
283}
284
285Sema::InstantiatingTemplate::InstantiatingTemplate(
286 Sema &SemaRef, SourceLocation PointOfInstantiation,
287 TemplateDecl *Template,
288 ArrayRef<TemplateArgument> TemplateArgs,
289 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
290 : InstantiatingTemplate(
291 SemaRef,
292 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
293 PointOfInstantiation, InstantiationRange, Template, nullptr,
294 TemplateArgs, &DeductionInfo) {}
295
296Sema::InstantiatingTemplate::InstantiatingTemplate(
297 Sema &SemaRef, SourceLocation PointOfInstantiation,
298 ClassTemplatePartialSpecializationDecl *PartialSpec,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
301 : InstantiatingTemplate(
302 SemaRef,
303 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
304 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
305 TemplateArgs, &DeductionInfo) {}
306
307Sema::InstantiatingTemplate::InstantiatingTemplate(
308 Sema &SemaRef, SourceLocation PointOfInstantiation,
309 VarTemplatePartialSpecializationDecl *PartialSpec,
310 ArrayRef<TemplateArgument> TemplateArgs,
311 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
312 : InstantiatingTemplate(
313 SemaRef,
314 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
315 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
316 TemplateArgs, &DeductionInfo) {}
317
318Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
320 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
321 : InstantiatingTemplate(
322 SemaRef,
323 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
324 PointOfInstantiation, InstantiationRange, Param, nullptr,
325 TemplateArgs) {}
326
327Sema::InstantiatingTemplate::InstantiatingTemplate(
328 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
329 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
330 SourceRange InstantiationRange)
331 : InstantiatingTemplate(
332 SemaRef,
333 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
334 PointOfInstantiation, InstantiationRange, Param, Template,
335 TemplateArgs) {}
336
337Sema::InstantiatingTemplate::InstantiatingTemplate(
338 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
339 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
340 SourceRange InstantiationRange)
341 : InstantiatingTemplate(
342 SemaRef,
343 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
344 PointOfInstantiation, InstantiationRange, Param, Template,
345 TemplateArgs) {}
346
347Sema::InstantiatingTemplate::InstantiatingTemplate(
348 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
349 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
350 SourceRange InstantiationRange)
351 : InstantiatingTemplate(
352 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
353 PointOfInstantiation, InstantiationRange, Param, Template,
354 TemplateArgs) {}
355
356void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
357 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
358 InNonInstantiationSFINAEContext = false;
359
360 CodeSynthesisContexts.push_back(Ctx);
361
362 if (!Ctx.isInstantiationRecord())
363 ++NonInstantiationEntries;
364}
365
366void Sema::popCodeSynthesisContext() {
367 auto &Active = CodeSynthesisContexts.back();
368 if (!Active.isInstantiationRecord()) {
369 assert(NonInstantiationEntries > 0)(static_cast <bool> (NonInstantiationEntries > 0) ? void
(0) : __assert_fail ("NonInstantiationEntries > 0", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 369, __extension__ __PRETTY_FUNCTION__))
;
370 --NonInstantiationEntries;
371 }
372
373 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
374
375 // Name lookup no longer looks in this template's defining module.
376 assert(CodeSynthesisContexts.size() >=(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
377 CodeSynthesisContextLookupModules.size() &&(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
378 "forgot to remove a lookup module for a template instantiation")(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
;
379 if (CodeSynthesisContexts.size() ==
380 CodeSynthesisContextLookupModules.size()) {
381 if (Module *M = CodeSynthesisContextLookupModules.back())
382 LookupModulesCache.erase(M);
383 CodeSynthesisContextLookupModules.pop_back();
384 }
385
386 // If we've left the code synthesis context for the current context stack,
387 // stop remembering that we've emitted that stack.
388 if (CodeSynthesisContexts.size() ==
389 LastEmittedCodeSynthesisContextDepth)
390 LastEmittedCodeSynthesisContextDepth = 0;
391
392 CodeSynthesisContexts.pop_back();
393}
394
395void Sema::InstantiatingTemplate::Clear() {
396 if (!Invalid) {
397 if (!AlreadyInstantiating) {
398 auto &Active = SemaRef.CodeSynthesisContexts.back();
399 SemaRef.InstantiatingSpecializations.erase(
400 std::make_pair(Active.Entity, Active.Kind));
401 }
402
403 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
404 SemaRef.CodeSynthesisContexts.back());
405
406 SemaRef.popCodeSynthesisContext();
407 Invalid = true;
408 }
409}
410
411bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
412 SourceLocation PointOfInstantiation,
413 SourceRange InstantiationRange) {
414 assert(SemaRef.NonInstantiationEntries <=(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 415, __extension__ __PRETTY_FUNCTION__))
415 SemaRef.CodeSynthesisContexts.size())(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 415, __extension__ __PRETTY_FUNCTION__))
;
416 if ((SemaRef.CodeSynthesisContexts.size() -
417 SemaRef.NonInstantiationEntries)
418 <= SemaRef.getLangOpts().InstantiationDepth)
419 return false;
420
421 SemaRef.Diag(PointOfInstantiation,
422 diag::err_template_recursion_depth_exceeded)
423 << SemaRef.getLangOpts().InstantiationDepth
424 << InstantiationRange;
425 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
426 << SemaRef.getLangOpts().InstantiationDepth;
427 return true;
428}
429
430/// \brief Prints the current instantiation stack through a series of
431/// notes.
432void Sema::PrintInstantiationStack() {
433 // Determine which template instantiations to skip, if any.
434 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
435 unsigned Limit = Diags.getTemplateBacktraceLimit();
436 if (Limit && Limit < CodeSynthesisContexts.size()) {
437 SkipStart = Limit / 2 + Limit % 2;
438 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
439 }
440
441 // FIXME: In all of these cases, we need to show the template arguments
442 unsigned InstantiationIdx = 0;
443 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
444 Active = CodeSynthesisContexts.rbegin(),
445 ActiveEnd = CodeSynthesisContexts.rend();
446 Active != ActiveEnd;
447 ++Active, ++InstantiationIdx) {
448 // Skip this instantiation?
449 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
450 if (InstantiationIdx == SkipStart) {
451 // Note that we're skipping instantiations.
452 Diags.Report(Active->PointOfInstantiation,
453 diag::note_instantiation_contexts_suppressed)
454 << unsigned(CodeSynthesisContexts.size() - Limit);
455 }
456 continue;
457 }
458
459 switch (Active->Kind) {
460 case CodeSynthesisContext::TemplateInstantiation: {
461 Decl *D = Active->Entity;
462 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
463 unsigned DiagID = diag::note_template_member_class_here;
464 if (isa<ClassTemplateSpecializationDecl>(Record))
465 DiagID = diag::note_template_class_instantiation_here;
466 Diags.Report(Active->PointOfInstantiation, DiagID)
467 << Record << Active->InstantiationRange;
468 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
469 unsigned DiagID;
470 if (Function->getPrimaryTemplate())
471 DiagID = diag::note_function_template_spec_here;
472 else
473 DiagID = diag::note_template_member_function_here;
474 Diags.Report(Active->PointOfInstantiation, DiagID)
475 << Function
476 << Active->InstantiationRange;
477 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
478 Diags.Report(Active->PointOfInstantiation,
479 VD->isStaticDataMember()?
480 diag::note_template_static_data_member_def_here
481 : diag::note_template_variable_def_here)
482 << VD
483 << Active->InstantiationRange;
484 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_enum_def_here)
487 << ED
488 << Active->InstantiationRange;
489 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
490 Diags.Report(Active->PointOfInstantiation,
491 diag::note_template_nsdmi_here)
492 << FD << Active->InstantiationRange;
493 } else {
494 Diags.Report(Active->PointOfInstantiation,
495 diag::note_template_type_alias_instantiation_here)
496 << cast<TypeAliasTemplateDecl>(D)
497 << Active->InstantiationRange;
498 }
499 break;
500 }
501
502 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
503 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
504 SmallVector<char, 128> TemplateArgsStr;
505 llvm::raw_svector_ostream OS(TemplateArgsStr);
506 Template->printName(OS);
507 printTemplateArgumentList(OS, Active->template_arguments(),
508 getPrintingPolicy());
509 Diags.Report(Active->PointOfInstantiation,
510 diag::note_default_arg_instantiation_here)
511 << OS.str()
512 << Active->InstantiationRange;
513 break;
514 }
515
516 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
517 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
518 Diags.Report(Active->PointOfInstantiation,
519 diag::note_explicit_template_arg_substitution_here)
520 << FnTmpl
521 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
522 Active->TemplateArgs,
523 Active->NumTemplateArgs)
524 << Active->InstantiationRange;
525 break;
526 }
527
528 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
529 if (FunctionTemplateDecl *FnTmpl =
530 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
531 Diags.Report(Active->PointOfInstantiation,
532 diag::note_function_template_deduction_instantiation_here)
533 << FnTmpl
534 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
535 Active->TemplateArgs,
536 Active->NumTemplateArgs)
537 << Active->InstantiationRange;
538 } else {
539 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
540 isa<VarTemplateSpecializationDecl>(Active->Entity);
541 bool IsTemplate = false;
542 TemplateParameterList *Params;
543 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
544 IsTemplate = true;
545 Params = D->getTemplateParameters();
546 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
547 Active->Entity)) {
548 Params = D->getTemplateParameters();
549 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
550 Active->Entity)) {
551 Params = D->getTemplateParameters();
552 } else {
553 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 553)
;
554 }
555
556 Diags.Report(Active->PointOfInstantiation,
557 diag::note_deduced_template_arg_substitution_here)
558 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
559 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
560 Active->NumTemplateArgs)
561 << Active->InstantiationRange;
562 }
563 break;
564 }
565
566 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
567 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
568 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
569
570 SmallVector<char, 128> TemplateArgsStr;
571 llvm::raw_svector_ostream OS(TemplateArgsStr);
572 FD->printName(OS);
573 printTemplateArgumentList(OS, Active->template_arguments(),
574 getPrintingPolicy());
575 Diags.Report(Active->PointOfInstantiation,
576 diag::note_default_function_arg_instantiation_here)
577 << OS.str()
578 << Active->InstantiationRange;
579 break;
580 }
581
582 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
583 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
584 std::string Name;
585 if (!Parm->getName().empty())
586 Name = std::string(" '") + Parm->getName().str() + "'";
587
588 TemplateParameterList *TemplateParams = nullptr;
589 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
590 TemplateParams = Template->getTemplateParameters();
591 else
592 TemplateParams =
593 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
594 ->getTemplateParameters();
595 Diags.Report(Active->PointOfInstantiation,
596 diag::note_prior_template_arg_substitution)
597 << isa<TemplateTemplateParmDecl>(Parm)
598 << Name
599 << getTemplateArgumentBindingsText(TemplateParams,
600 Active->TemplateArgs,
601 Active->NumTemplateArgs)
602 << Active->InstantiationRange;
603 break;
604 }
605
606 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
607 TemplateParameterList *TemplateParams = nullptr;
608 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
609 TemplateParams = Template->getTemplateParameters();
610 else
611 TemplateParams =
612 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
613 ->getTemplateParameters();
614
615 Diags.Report(Active->PointOfInstantiation,
616 diag::note_template_default_arg_checking)
617 << getTemplateArgumentBindingsText(TemplateParams,
618 Active->TemplateArgs,
619 Active->NumTemplateArgs)
620 << Active->InstantiationRange;
621 break;
622 }
623
624 case CodeSynthesisContext::ExceptionSpecInstantiation:
625 Diags.Report(Active->PointOfInstantiation,
626 diag::note_template_exception_spec_instantiation_here)
627 << cast<FunctionDecl>(Active->Entity)
628 << Active->InstantiationRange;
629 break;
630
631 case CodeSynthesisContext::DeclaringSpecialMember:
632 Diags.Report(Active->PointOfInstantiation,
633 diag::note_in_declaration_of_implicit_special_member)
634 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
635 break;
636
637 case CodeSynthesisContext::DefiningSynthesizedFunction: {
638 // FIXME: For synthesized members other than special members, produce a note.
639 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
640 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
641 if (CSM != CXXInvalid) {
642 Diags.Report(Active->PointOfInstantiation,
643 diag::note_member_synthesized_at)
644 << CSM << Context.getTagDeclType(MD->getParent());
645 }
646 break;
647 }
648
649 case CodeSynthesisContext::Memoization:
650 break;
651 }
652 }
653}
654
655Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
656 if (InNonInstantiationSFINAEContext)
657 return Optional<TemplateDeductionInfo *>(nullptr);
658
659 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
660 Active = CodeSynthesisContexts.rbegin(),
661 ActiveEnd = CodeSynthesisContexts.rend();
662 Active != ActiveEnd;
663 ++Active)
664 {
665 switch (Active->Kind) {
666 case CodeSynthesisContext::TemplateInstantiation:
667 // An instantiation of an alias template may or may not be a SFINAE
668 // context, depending on what else is on the stack.
669 if (isa<TypeAliasTemplateDecl>(Active->Entity))
670 break;
671 // Fall through.
672 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
673 case CodeSynthesisContext::ExceptionSpecInstantiation:
674 // This is a template instantiation, so there is no SFINAE.
675 return None;
676
677 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
678 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
679 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
680 // A default template argument instantiation and substitution into
681 // template parameters with arguments for prior parameters may or may
682 // not be a SFINAE context; look further up the stack.
683 break;
684
685 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
686 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
687 // We're either substitution explicitly-specified template arguments
688 // or deduced template arguments, so SFINAE applies.
689 assert(Active->DeductionInfo && "Missing deduction info pointer")(static_cast <bool> (Active->DeductionInfo &&
"Missing deduction info pointer") ? void (0) : __assert_fail
("Active->DeductionInfo && \"Missing deduction info pointer\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 689, __extension__ __PRETTY_FUNCTION__))
;
690 return Active->DeductionInfo;
691
692 case CodeSynthesisContext::DeclaringSpecialMember:
693 case CodeSynthesisContext::DefiningSynthesizedFunction:
694 // This happens in a context unrelated to template instantiation, so
695 // there is no SFINAE.
696 return None;
697
698 case CodeSynthesisContext::Memoization:
699 break;
700 }
701
702 // The inner context was transparent for SFINAE. If it occurred within a
703 // non-instantiation SFINAE context, then SFINAE applies.
704 if (Active->SavedInNonInstantiationSFINAEContext)
705 return Optional<TemplateDeductionInfo *>(nullptr);
706 }
707
708 return None;
709}
710
711/// \brief Retrieve the depth and index of a parameter pack.
712static std::pair<unsigned, unsigned>
713getDepthAndIndex(NamedDecl *ND) {
714 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
715 return std::make_pair(TTP->getDepth(), TTP->getIndex());
716
717 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
718 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
719
720 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
721 return std::make_pair(TTP->getDepth(), TTP->getIndex());
722}
723
724//===----------------------------------------------------------------------===/
725// Template Instantiation for Types
726//===----------------------------------------------------------------------===/
727namespace {
728 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
729 const MultiLevelTemplateArgumentList &TemplateArgs;
730 SourceLocation Loc;
731 DeclarationName Entity;
732
733 public:
734 typedef TreeTransform<TemplateInstantiator> inherited;
735
736 TemplateInstantiator(Sema &SemaRef,
737 const MultiLevelTemplateArgumentList &TemplateArgs,
738 SourceLocation Loc,
739 DeclarationName Entity)
740 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
741 Entity(Entity) { }
742
743 /// \brief Determine whether the given type \p T has already been
744 /// transformed.
745 ///
746 /// For the purposes of template instantiation, a type has already been
747 /// transformed if it is NULL or if it is not dependent.
748 bool AlreadyTransformed(QualType T);
749
750 /// \brief Returns the location of the entity being instantiated, if known.
751 SourceLocation getBaseLocation() { return Loc; }
752
753 /// \brief Returns the name of the entity being instantiated, if any.
754 DeclarationName getBaseEntity() { return Entity; }
755
756 /// \brief Sets the "base" location and entity when that
757 /// information is known based on another transformation.
758 void setBase(SourceLocation Loc, DeclarationName Entity) {
759 this->Loc = Loc;
760 this->Entity = Entity;
761 }
762
763 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
764 SourceRange PatternRange,
765 ArrayRef<UnexpandedParameterPack> Unexpanded,
766 bool &ShouldExpand, bool &RetainExpansion,
767 Optional<unsigned> &NumExpansions) {
768 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
769 PatternRange, Unexpanded,
770 TemplateArgs,
771 ShouldExpand,
772 RetainExpansion,
773 NumExpansions);
774 }
775
776 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
777 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
778 }
779
780 TemplateArgument ForgetPartiallySubstitutedPack() {
781 TemplateArgument Result;
782 if (NamedDecl *PartialPack
783 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
784 MultiLevelTemplateArgumentList &TemplateArgs
785 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
786 unsigned Depth, Index;
787 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
788 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
789 Result = TemplateArgs(Depth, Index);
790 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
791 }
792 }
793
794 return Result;
795 }
796
797 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
798 if (Arg.isNull())
799 return;
800
801 if (NamedDecl *PartialPack
802 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
803 MultiLevelTemplateArgumentList &TemplateArgs
804 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
805 unsigned Depth, Index;
806 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
807 TemplateArgs.setArgument(Depth, Index, Arg);
808 }
809 }
810
811 /// \brief Transform the given declaration by instantiating a reference to
812 /// this declaration.
813 Decl *TransformDecl(SourceLocation Loc, Decl *D);
814
815 void transformAttrs(Decl *Old, Decl *New) {
816 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
817 }
818
819 void transformedLocalDecl(Decl *Old, Decl *New) {
820 // If we've instantiated the call operator of a lambda or the call
821 // operator template of a generic lambda, update the "instantiation of"
822 // information.
823 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
824 if (NewMD && isLambdaCallOperator(NewMD)) {
825 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
826 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
827 NewTD->setInstantiatedFromMemberTemplate(
828 OldMD->getDescribedFunctionTemplate());
829 else
830 NewMD->setInstantiationOfMemberFunction(OldMD,
831 TSK_ImplicitInstantiation);
832 }
833
834 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
835
836 // We recreated a local declaration, but not by instantiating it. There
837 // may be pending dependent diagnostics to produce.
838 if (auto *DC = dyn_cast<DeclContext>(Old))
839 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
840 }
841
842 /// \brief Transform the definition of the given declaration by
843 /// instantiating it.
844 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
845
846 /// \brief Transform the first qualifier within a scope by instantiating the
847 /// declaration.
848 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
849
850 /// \brief Rebuild the exception declaration and register the declaration
851 /// as an instantiated local.
852 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
853 TypeSourceInfo *Declarator,
854 SourceLocation StartLoc,
855 SourceLocation NameLoc,
856 IdentifierInfo *Name);
857
858 /// \brief Rebuild the Objective-C exception declaration and register the
859 /// declaration as an instantiated local.
860 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
861 TypeSourceInfo *TSInfo, QualType T);
862
863 /// \brief Check for tag mismatches when instantiating an
864 /// elaborated type.
865 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
866 ElaboratedTypeKeyword Keyword,
867 NestedNameSpecifierLoc QualifierLoc,
868 QualType T);
869
870 TemplateName
871 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
872 SourceLocation NameLoc,
873 QualType ObjectType = QualType(),
874 NamedDecl *FirstQualifierInScope = nullptr,
875 bool AllowInjectedClassName = false);
876
877 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
878
879 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
880 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
881 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
882
883 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
884 NonTypeTemplateParmDecl *D);
885 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
886 SubstNonTypeTemplateParmPackExpr *E);
887
888 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
889 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
890
891 /// \brief Transform a reference to a function parameter pack.
892 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
893 ParmVarDecl *PD);
894
895 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
896 /// expand a function parameter pack reference which refers to an expanded
897 /// pack.
898 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
899
900 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
901 FunctionProtoTypeLoc TL) {
902 // Call the base version; it will forward to our overridden version below.
903 return inherited::TransformFunctionProtoType(TLB, TL);
904 }
905
906 template<typename Fn>
907 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
908 FunctionProtoTypeLoc TL,
909 CXXRecordDecl *ThisContext,
910 unsigned ThisTypeQuals,
911 Fn TransformExceptionSpec);
912
913 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
914 int indexAdjustment,
915 Optional<unsigned> NumExpansions,
916 bool ExpectParameterPack);
917
918 /// \brief Transforms a template type parameter type by performing
919 /// substitution of the corresponding template type argument.
920 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
921 TemplateTypeParmTypeLoc TL);
922
923 /// \brief Transforms an already-substituted template type parameter pack
924 /// into either itself (if we aren't substituting into its pack expansion)
925 /// or the appropriate substituted argument.
926 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
927 SubstTemplateTypeParmPackTypeLoc TL);
928
929 ExprResult TransformLambdaExpr(LambdaExpr *E) {
930 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
931 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
932 }
933
934 TemplateParameterList *TransformTemplateParameterList(
935 TemplateParameterList *OrigTPL) {
936 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
937
938 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
939 TemplateDeclInstantiator DeclInstantiator(getSema(),
940 /* DeclContext *Owner */ Owner, TemplateArgs);
941 return DeclInstantiator.SubstTemplateParams(OrigTPL);
942 }
943 private:
944 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
945 SourceLocation loc,
946 TemplateArgument arg);
947 };
948}
949
950bool TemplateInstantiator::AlreadyTransformed(QualType T) {
951 if (T.isNull())
952 return true;
953
954 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
955 return false;
956
957 getSema().MarkDeclarationsReferencedInType(Loc, T);
958 return true;
959}
960
961static TemplateArgument
962getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
963 assert(S.ArgumentPackSubstitutionIndex >= 0)(static_cast <bool> (S.ArgumentPackSubstitutionIndex >=
0) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
;
964 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size())(static_cast <bool> (S.ArgumentPackSubstitutionIndex <
(int)Arg.pack_size()) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 964, __extension__ __PRETTY_FUNCTION__))
;
965 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
966 if (Arg.isPackExpansion())
967 Arg = Arg.getPackExpansionPattern();
968 return Arg;
969}
970
971Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
972 if (!D)
973 return nullptr;
974
975 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
976 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
977 // If the corresponding template argument is NULL or non-existent, it's
978 // because we are performing instantiation from explicitly-specified
979 // template arguments in a function template, but there were some
980 // arguments left unspecified.
981 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
982 TTP->getPosition()))
983 return D;
984
985 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
986
987 if (TTP->isParameterPack()) {
988 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 989, __extension__ __PRETTY_FUNCTION__))
989 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 989, __extension__ __PRETTY_FUNCTION__))
;
990 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
991 }
992
993 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
994 assert(!Template.isNull() && Template.getAsTemplateDecl() &&(static_cast <bool> (!Template.isNull() && Template
.getAsTemplateDecl() && "Wrong kind of template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 995, __extension__ __PRETTY_FUNCTION__))
995 "Wrong kind of template template argument")(static_cast <bool> (!Template.isNull() && Template
.getAsTemplateDecl() && "Wrong kind of template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 995, __extension__ __PRETTY_FUNCTION__))
;
996 return Template.getAsTemplateDecl();
997 }
998
999 // Fall through to find the instantiated declaration for this template
1000 // template parameter.
1001 }
1002
1003 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1004}
1005
1006Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1007 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1008 if (!Inst)
1009 return nullptr;
1010
1011 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1012 return Inst;
1013}
1014
1015NamedDecl *
1016TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1017 SourceLocation Loc) {
1018 // If the first part of the nested-name-specifier was a template type
1019 // parameter, instantiate that type parameter down to a tag type.
1020 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1021 const TemplateTypeParmType *TTP
1022 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1023
1024 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1025 // FIXME: This needs testing w/ member access expressions.
1026 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1027
1028 if (TTP->isParameterPack()) {
1029 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1030, __extension__ __PRETTY_FUNCTION__))
1030 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1030, __extension__ __PRETTY_FUNCTION__))
;
1031
1032 if (getSema().ArgumentPackSubstitutionIndex == -1)
1033 return nullptr;
1034
1035 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1036 }
1037
1038 QualType T = Arg.getAsType();
1039 if (T.isNull())
1040 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1041
1042 if (const TagType *Tag = T->getAs<TagType>())
1043 return Tag->getDecl();
1044
1045 // The resulting type is not a tag; complain.
1046 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1047 return nullptr;
1048 }
1049 }
1050
1051 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1052}
1053
1054VarDecl *
1055TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1056 TypeSourceInfo *Declarator,
1057 SourceLocation StartLoc,
1058 SourceLocation NameLoc,
1059 IdentifierInfo *Name) {
1060 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1061 StartLoc, NameLoc, Name);
1062 if (Var)
1063 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1064 return Var;
1065}
1066
1067VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1068 TypeSourceInfo *TSInfo,
1069 QualType T) {
1070 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1071 if (Var)
1072 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1073 return Var;
1074}
1075
1076QualType
1077TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1078 ElaboratedTypeKeyword Keyword,
1079 NestedNameSpecifierLoc QualifierLoc,
1080 QualType T) {
1081 if (const TagType *TT = T->getAs<TagType>()) {
1082 TagDecl* TD = TT->getDecl();
1083
1084 SourceLocation TagLocation = KeywordLoc;
1085
1086 IdentifierInfo *Id = TD->getIdentifier();
1087
1088 // TODO: should we even warn on struct/class mismatches for this? Seems
1089 // like it's likely to produce a lot of spurious errors.
1090 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1091 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1092 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1093 TagLocation, Id)) {
1094 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1095 << Id
1096 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1097 TD->getKindName());
1098 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1099 }
1100 }
1101 }
1102
1103 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1104 Keyword,
1105 QualifierLoc,
1106 T);
1107}
1108
1109TemplateName TemplateInstantiator::TransformTemplateName(
1110 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1111 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1112 bool AllowInjectedClassName) {
1113 if (TemplateTemplateParmDecl *TTP
1114 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1115 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1116 // If the corresponding template argument is NULL or non-existent, it's
1117 // because we are performing instantiation from explicitly-specified
1118 // template arguments in a function template, but there were some
1119 // arguments left unspecified.
1120 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1121 TTP->getPosition()))
1122 return Name;
1123
1124 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1125
1126 if (TTP->isParameterPack()) {
1127 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1128, __extension__ __PRETTY_FUNCTION__))
1128 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1128, __extension__ __PRETTY_FUNCTION__))
;
1129
1130 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1131 // We have the template argument pack to substitute, but we're not
1132 // actually expanding the enclosing pack expansion yet. So, just
1133 // keep the entire argument pack.
1134 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1135 }
1136
1137 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1138 }
1139
1140 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1141 assert(!Template.isNull() && "Null template template argument")(static_cast <bool> (!Template.isNull() && "Null template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && \"Null template template argument\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1141, __extension__ __PRETTY_FUNCTION__))
;
1142 assert(!Template.getAsQualifiedTemplateName() &&(static_cast <bool> (!Template.getAsQualifiedTemplateName
() && "template decl to substitute is qualified?") ? void
(0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1143, __extension__ __PRETTY_FUNCTION__))
1143 "template decl to substitute is qualified?")(static_cast <bool> (!Template.getAsQualifiedTemplateName
() && "template decl to substitute is qualified?") ? void
(0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1143, __extension__ __PRETTY_FUNCTION__))
;
1144
1145 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1146 return Template;
1147 }
1148 }
1149
1150 if (SubstTemplateTemplateParmPackStorage *SubstPack
1151 = Name.getAsSubstTemplateTemplateParmPack()) {
1152 if (getSema().ArgumentPackSubstitutionIndex == -1)
1153 return Name;
1154
1155 TemplateArgument Arg = SubstPack->getArgumentPack();
1156 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1157 return Arg.getAsTemplate().getNameToSubstitute();
1158 }
1159
1160 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1161 FirstQualifierInScope,
1162 AllowInjectedClassName);
1163}
1164
1165ExprResult
1166TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1167 if (!E->isTypeDependent())
1168 return E;
1169
1170 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1171}
1172
1173ExprResult
1174TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1175 NonTypeTemplateParmDecl *NTTP) {
1176 // If the corresponding template argument is NULL or non-existent, it's
1177 // because we are performing instantiation from explicitly-specified
1178 // template arguments in a function template, but there were some
1179 // arguments left unspecified.
1180 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1181 NTTP->getPosition()))
1182 return E;
1183
1184 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1185
1186 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1187 // We're performing a partial substitution, so the substituted argument
1188 // could be dependent. As a result we can't create a SubstNonType*Expr
1189 // node now, since that represents a fully-substituted argument.
1190 // FIXME: We should have some AST representation for this.
1191 if (Arg.getKind() == TemplateArgument::Pack) {
1192 // FIXME: This won't work for alias templates.
1193 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in partial substitution"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1194, __extension__ __PRETTY_FUNCTION__))
1194 "unexpected pack arguments in partial substitution")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in partial substitution"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1194, __extension__ __PRETTY_FUNCTION__))
;
1195 Arg = Arg.pack_begin()->getPackExpansionPattern();
1196 }
1197 assert(Arg.getKind() == TemplateArgument::Expression &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in partial substitution"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1198, __extension__ __PRETTY_FUNCTION__))
1198 "unexpected nontype template argument kind in partial substitution")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in partial substitution"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1198, __extension__ __PRETTY_FUNCTION__))
;
1199 return Arg.getAsExpr();
1200 }
1201
1202 if (NTTP->isParameterPack()) {
1203 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1204, __extension__ __PRETTY_FUNCTION__))
1204 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1204, __extension__ __PRETTY_FUNCTION__))
;
1205
1206 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1207 // We have an argument pack, but we can't select a particular argument
1208 // out of it yet. Therefore, we'll build an expression to hold on to that
1209 // argument pack.
1210 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1211 E->getLocation(),
1212 NTTP->getDeclName());
1213 if (TargetType.isNull())
1214 return ExprError();
1215
1216 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1217 TargetType.getNonLValueExprType(SemaRef.Context),
1218 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1219 E->getLocation(), Arg);
1220 }
1221
1222 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1223 }
1224
1225 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1226}
1227
1228const LoopHintAttr *
1229TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1230 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1231
1232 if (TransformedExpr == LH->getValue())
1233 return LH;
1234
1235 // Generate error if there is a problem with the value.
1236 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1237 return LH;
1238
1239 // Create new LoopHintValueAttr with integral expression in place of the
1240 // non-type template parameter.
1241 return LoopHintAttr::CreateImplicit(
1242 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1243 LH->getState(), TransformedExpr, LH->getRange());
1244}
1245
1246ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1247 NonTypeTemplateParmDecl *parm,
1248 SourceLocation loc,
1249 TemplateArgument arg) {
1250 ExprResult result;
1251 QualType type;
1252
1253 // The template argument itself might be an expression, in which
1254 // case we just return that expression.
1255 if (arg.getKind() == TemplateArgument::Expression) {
1256 Expr *argExpr = arg.getAsExpr();
1257 result = argExpr;
1258 type = argExpr->getType();
1259
1260 } else if (arg.getKind() == TemplateArgument::Declaration ||
1261 arg.getKind() == TemplateArgument::NullPtr) {
1262 ValueDecl *VD;
1263 if (arg.getKind() == TemplateArgument::Declaration) {
1264 VD = arg.getAsDecl();
1265
1266 // Find the instantiation of the template argument. This is
1267 // required for nested templates.
1268 VD = cast_or_null<ValueDecl>(
1269 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1270 if (!VD)
1271 return ExprError();
1272 } else {
1273 // Propagate NULL template argument.
1274 VD = nullptr;
1275 }
1276
1277 // Derive the type we want the substituted decl to have. This had
1278 // better be non-dependent, or these checks will have serious problems.
1279 if (parm->isExpandedParameterPack()) {
1280 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1281 } else if (parm->isParameterPack() &&
1282 isa<PackExpansionType>(parm->getType())) {
1283 type = SemaRef.SubstType(
1284 cast<PackExpansionType>(parm->getType())->getPattern(),
1285 TemplateArgs, loc, parm->getDeclName());
1286 } else {
1287 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1288 TemplateArgs, loc, parm->getDeclName());
1289 }
1290 assert(!type.isNull() && "type substitution failed for param type")(static_cast <bool> (!type.isNull() && "type substitution failed for param type"
) ? void (0) : __assert_fail ("!type.isNull() && \"type substitution failed for param type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1290, __extension__ __PRETTY_FUNCTION__))
;
1291 assert(!type->isDependentType() && "param type still dependent")(static_cast <bool> (!type->isDependentType() &&
"param type still dependent") ? void (0) : __assert_fail ("!type->isDependentType() && \"param type still dependent\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1291, __extension__ __PRETTY_FUNCTION__))
;
1292 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1293
1294 if (!result.isInvalid()) type = result.get()->getType();
1295 } else {
1296 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1297
1298 // Note that this type can be different from the type of 'result',
1299 // e.g. if it's an enum type.
1300 type = arg.getIntegralType();
1301 }
1302 if (result.isInvalid()) return ExprError();
1303
1304 Expr *resultExpr = result.get();
1305 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1306 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1307}
1308
1309ExprResult
1310TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1311 SubstNonTypeTemplateParmPackExpr *E) {
1312 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1313 // We aren't expanding the parameter pack, so just return ourselves.
1314 return E;
1315 }
1316
1317 TemplateArgument Arg = E->getArgumentPack();
1318 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1319 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1320 E->getParameterPackLocation(),
1321 Arg);
1322}
1323
1324ExprResult
1325TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1326 SourceLocation Loc) {
1327 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1328 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1329}
1330
1331ExprResult
1332TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1333 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1334 // We can expand this parameter pack now.
1335 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1336 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1337 if (!VD)
1338 return ExprError();
1339 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1340 }
1341
1342 QualType T = TransformType(E->getType());
1343 if (T.isNull())
1344 return ExprError();
1345
1346 // Transform each of the parameter expansions into the corresponding
1347 // parameters in the instantiation of the function decl.
1348 SmallVector<ParmVarDecl *, 8> Parms;
1349 Parms.reserve(E->getNumExpansions());
1350 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1351 I != End; ++I) {
1352 ParmVarDecl *D =
1353 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1354 if (!D)
1355 return ExprError();
1356 Parms.push_back(D);
1357 }
1358
1359 return FunctionParmPackExpr::Create(getSema().Context, T,
1360 E->getParameterPack(),
1361 E->getParameterPackLocation(), Parms);
1362}
1363
1364ExprResult
1365TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1366 ParmVarDecl *PD) {
1367 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1368 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1369 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1370 assert(Found && "no instantiation for parameter pack")(static_cast <bool> (Found && "no instantiation for parameter pack"
) ? void (0) : __assert_fail ("Found && \"no instantiation for parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1370, __extension__ __PRETTY_FUNCTION__))
;
1371
1372 Decl *TransformedDecl;
1373 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1374 // If this is a reference to a function parameter pack which we can
1375 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1376 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1377 QualType T = TransformType(E->getType());
1378 if (T.isNull())
1379 return ExprError();
1380 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1381 E->getExprLoc(), *Pack);
1382 }
1383
1384 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1385 } else {
1386 TransformedDecl = Found->get<Decl*>();
1387 }
1388
1389 // We have either an unexpanded pack or a specific expansion.
1390 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1391 E->getExprLoc());
1392}
1393
1394ExprResult
1395TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1396 NamedDecl *D = E->getDecl();
1397
1398 // Handle references to non-type template parameters and non-type template
1399 // parameter packs.
1400 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1401 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1402 return TransformTemplateParmRefExpr(E, NTTP);
1403
1404 // We have a non-type template parameter that isn't fully substituted;
1405 // FindInstantiatedDecl will find it in the local instantiation scope.
1406 }
1407
1408 // Handle references to function parameter packs.
1409 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1410 if (PD->isParameterPack())
1411 return TransformFunctionParmPackRefExpr(E, PD);
1412
1413 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1414}
1415
1416ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1417 CXXDefaultArgExpr *E) {
1418 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1420, __extension__ __PRETTY_FUNCTION__))
1419 getDescribedFunctionTemplate() &&(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1420, __extension__ __PRETTY_FUNCTION__))
1420 "Default arg expressions are never formed in dependent cases.")(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1420, __extension__ __PRETTY_FUNCTION__))
;
1421 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1422 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1423 E->getParam());
1424}
1425
1426template<typename Fn>
1427QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1428 FunctionProtoTypeLoc TL,
1429 CXXRecordDecl *ThisContext,
1430 unsigned ThisTypeQuals,
1431 Fn TransformExceptionSpec) {
1432 // We need a local instantiation scope for this function prototype.
1433 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1434 return inherited::TransformFunctionProtoType(
1435 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1436}
1437
1438ParmVarDecl *
1439TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1440 int indexAdjustment,
1441 Optional<unsigned> NumExpansions,
1442 bool ExpectParameterPack) {
1443 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1444 NumExpansions, ExpectParameterPack);
1445}
1446
1447QualType
1448TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1449 TemplateTypeParmTypeLoc TL) {
1450 const TemplateTypeParmType *T = TL.getTypePtr();
1451 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1452 // Replace the template type parameter with its corresponding
1453 // template argument.
1454
1455 // If the corresponding template argument is NULL or doesn't exist, it's
1456 // because we are performing instantiation from explicitly-specified
1457 // template arguments in a function template class, but there were some
1458 // arguments left unspecified.
1459 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1460 TemplateTypeParmTypeLoc NewTL
1461 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1462 NewTL.setNameLoc(TL.getNameLoc());
1463 return TL.getType();
1464 }
1465
1466 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1467
1468 if (T->isParameterPack()) {
1469 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1470, __extension__ __PRETTY_FUNCTION__))
1470 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1470, __extension__ __PRETTY_FUNCTION__))
;
1471
1472 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1473 // We have the template argument pack, but we're not expanding the
1474 // enclosing pack expansion yet. Just save the template argument
1475 // pack for later substitution.
1476 QualType Result
1477 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1478 SubstTemplateTypeParmPackTypeLoc NewTL
1479 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1480 NewTL.setNameLoc(TL.getNameLoc());
1481 return Result;
1482 }
1483
1484 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1485 }
1486
1487 assert(Arg.getKind() == TemplateArgument::Type &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "Template argument kind mismatch") ? void (0)
: __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1488, __extension__ __PRETTY_FUNCTION__))
1488 "Template argument kind mismatch")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "Template argument kind mismatch") ? void (0)
: __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1488, __extension__ __PRETTY_FUNCTION__))
;
1489
1490 QualType Replacement = Arg.getAsType();
1491
1492 // TODO: only do this uniquing once, at the start of instantiation.
1493 QualType Result
1494 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1495 SubstTemplateTypeParmTypeLoc NewTL
1496 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1497 NewTL.setNameLoc(TL.getNameLoc());
1498 return Result;
1499 }
1500
1501 // The template type parameter comes from an inner template (e.g.,
1502 // the template parameter list of a member template inside the
1503 // template we are instantiating). Create a new template type
1504 // parameter with the template "level" reduced by one.
1505 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1506 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1507 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1508 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1509
1510 QualType Result = getSema().Context.getTemplateTypeParmType(
1511 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1512 T->isParameterPack(), NewTTPDecl);
1513 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1514 NewTL.setNameLoc(TL.getNameLoc());
1515 return Result;
1516}
1517
1518QualType
1519TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1520 TypeLocBuilder &TLB,
1521 SubstTemplateTypeParmPackTypeLoc TL) {
1522 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1523 // We aren't expanding the parameter pack, so just return ourselves.
1524 SubstTemplateTypeParmPackTypeLoc NewTL
1525 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1526 NewTL.setNameLoc(TL.getNameLoc());
1527 return TL.getType();
1528 }
1529
1530 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1531 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1532 QualType Result = Arg.getAsType();
1533
1534 Result = getSema().Context.getSubstTemplateTypeParmType(
1535 TL.getTypePtr()->getReplacedParameter(),
1536 Result);
1537 SubstTemplateTypeParmTypeLoc NewTL
1538 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1539 NewTL.setNameLoc(TL.getNameLoc());
1540 return Result;
1541}
1542
1543/// \brief Perform substitution on the type T with a given set of template
1544/// arguments.
1545///
1546/// This routine substitutes the given template arguments into the
1547/// type T and produces the instantiated type.
1548///
1549/// \param T the type into which the template arguments will be
1550/// substituted. If this type is not dependent, it will be returned
1551/// immediately.
1552///
1553/// \param Args the template arguments that will be
1554/// substituted for the top-level template parameters within T.
1555///
1556/// \param Loc the location in the source code where this substitution
1557/// is being performed. It will typically be the location of the
1558/// declarator (if we're instantiating the type of some declaration)
1559/// or the location of the type in the source code (if, e.g., we're
1560/// instantiating the type of a cast expression).
1561///
1562/// \param Entity the name of the entity associated with a declaration
1563/// being instantiated (if any). May be empty to indicate that there
1564/// is no such entity (if, e.g., this is a type that occurs as part of
1565/// a cast expression) or that the entity has no name (e.g., an
1566/// unnamed function parameter).
1567///
1568/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1569/// acceptable as the top level type of the result.
1570///
1571/// \returns If the instantiation succeeds, the instantiated
1572/// type. Otherwise, produces diagnostics and returns a NULL type.
1573TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1574 const MultiLevelTemplateArgumentList &Args,
1575 SourceLocation Loc,
1576 DeclarationName Entity,
1577 bool AllowDeducedTST) {
1578 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1580, __extension__ __PRETTY_FUNCTION__))
1579 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1580, __extension__ __PRETTY_FUNCTION__))
1580 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1580, __extension__ __PRETTY_FUNCTION__))
;
1581
1582 if (!T->getType()->isInstantiationDependentType() &&
1583 !T->getType()->isVariablyModifiedType())
1584 return T;
1585
1586 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1587 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1588 : Instantiator.TransformType(T);
1589}
1590
1591TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1592 const MultiLevelTemplateArgumentList &Args,
1593 SourceLocation Loc,
1594 DeclarationName Entity) {
1595 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1597, __extension__ __PRETTY_FUNCTION__))
1596 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1597, __extension__ __PRETTY_FUNCTION__))
1597 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1597, __extension__ __PRETTY_FUNCTION__))
;
1598
1599 if (TL.getType().isNull())
1600 return nullptr;
1601
1602 if (!TL.getType()->isInstantiationDependentType() &&
1603 !TL.getType()->isVariablyModifiedType()) {
1604 // FIXME: Make a copy of the TypeLoc data here, so that we can
1605 // return a new TypeSourceInfo. Inefficient!
1606 TypeLocBuilder TLB;
1607 TLB.pushFullCopy(TL);
1608 return TLB.getTypeSourceInfo(Context, TL.getType());
1609 }
1610
1611 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1612 TypeLocBuilder TLB;
1613 TLB.reserve(TL.getFullDataSize());
1614 QualType Result = Instantiator.TransformType(TLB, TL);
1615 if (Result.isNull())
1616 return nullptr;
1617
1618 return TLB.getTypeSourceInfo(Context, Result);
1619}
1620
1621/// Deprecated form of the above.
1622QualType Sema::SubstType(QualType T,
1623 const MultiLevelTemplateArgumentList &TemplateArgs,
1624 SourceLocation Loc, DeclarationName Entity) {
1625 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1627, __extension__ __PRETTY_FUNCTION__))
1626 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1627, __extension__ __PRETTY_FUNCTION__))
1627 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1627, __extension__ __PRETTY_FUNCTION__))
;
1628
1629 // If T is not a dependent type or a variably-modified type, there
1630 // is nothing to do.
1631 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1632 return T;
1633
1634 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1635 return Instantiator.TransformType(T);
1636}
1637
1638static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1639 if (T->getType()->isInstantiationDependentType() ||
1640 T->getType()->isVariablyModifiedType())
1641 return true;
1642
1643 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1644 if (!TL.getAs<FunctionProtoTypeLoc>())
1645 return false;
1646
1647 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1648 for (ParmVarDecl *P : FP.getParams()) {
1649 // This must be synthesized from a typedef.
1650 if (!P) continue;
1651
1652 // If there are any parameters, a new TypeSourceInfo that refers to the
1653 // instantiated parameters must be built.
1654 return true;
1655 }
1656
1657 return false;
1658}
1659
1660/// A form of SubstType intended specifically for instantiating the
1661/// type of a FunctionDecl. Its purpose is solely to force the
1662/// instantiation of default-argument expressions and to avoid
1663/// instantiating an exception-specification.
1664TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1665 const MultiLevelTemplateArgumentList &Args,
1666 SourceLocation Loc,
1667 DeclarationName Entity,
1668 CXXRecordDecl *ThisContext,
1669 unsigned ThisTypeQuals) {
1670 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1672, __extension__ __PRETTY_FUNCTION__))
1671 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1672, __extension__ __PRETTY_FUNCTION__))
1672 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1672, __extension__ __PRETTY_FUNCTION__))
;
1673
1674 if (!NeedsInstantiationAsFunctionType(T))
1675 return T;
1676
1677 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1678
1679 TypeLocBuilder TLB;
1680
1681 TypeLoc TL = T->getTypeLoc();
1682 TLB.reserve(TL.getFullDataSize());
1683
1684 QualType Result;
1685
1686 if (FunctionProtoTypeLoc Proto =
1687 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1688 // Instantiate the type, other than its exception specification. The
1689 // exception specification is instantiated in InitFunctionInstantiation
1690 // once we've built the FunctionDecl.
1691 // FIXME: Set the exception specification to EST_Uninstantiated here,
1692 // instead of rebuilding the function type again later.
1693 Result = Instantiator.TransformFunctionProtoType(
1694 TLB, Proto, ThisContext, ThisTypeQuals,
1695 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1696 bool &Changed) { return false; });
1697 } else {
1698 Result = Instantiator.TransformType(TLB, TL);
1699 }
1700 if (Result.isNull())
1701 return nullptr;
1702
1703 return TLB.getTypeSourceInfo(Context, Result);
1704}
1705
1706bool Sema::SubstExceptionSpec(SourceLocation Loc,
1707 FunctionProtoType::ExceptionSpecInfo &ESI,
1708 SmallVectorImpl<QualType> &ExceptionStorage,
1709 const MultiLevelTemplateArgumentList &Args) {
1710 assert(ESI.Type != EST_Uninstantiated)(static_cast <bool> (ESI.Type != EST_Uninstantiated) ? void
(0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1710, __extension__ __PRETTY_FUNCTION__))
;
1711
1712 bool Changed = false;
1713 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1714 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1715 Changed);
1716}
1717
1718void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1719 const MultiLevelTemplateArgumentList &Args) {
1720 FunctionProtoType::ExceptionSpecInfo ESI =
1721 Proto->getExtProtoInfo().ExceptionSpec;
1722
1723 SmallVector<QualType, 4> ExceptionStorage;
1724 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getLocEnd(),
1725 ESI, ExceptionStorage, Args))
1726 // On error, recover by dropping the exception specification.
1727 ESI.Type = EST_None;
1728
1729 UpdateExceptionSpec(New, ESI);
1730}
1731
1732ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1733 const MultiLevelTemplateArgumentList &TemplateArgs,
1734 int indexAdjustment,
1735 Optional<unsigned> NumExpansions,
1736 bool ExpectParameterPack) {
1737 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1738 TypeSourceInfo *NewDI = nullptr;
1739
1740 TypeLoc OldTL = OldDI->getTypeLoc();
1741 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1742
1743 // We have a function parameter pack. Substitute into the pattern of the
1744 // expansion.
1745 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1746 OldParm->getLocation(), OldParm->getDeclName());
1747 if (!NewDI)
1748 return nullptr;
1749
1750 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1751 // We still have unexpanded parameter packs, which means that
1752 // our function parameter is still a function parameter pack.
1753 // Therefore, make its type a pack expansion type.
1754 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1755 NumExpansions);
1756 } else if (ExpectParameterPack) {
1757 // We expected to get a parameter pack but didn't (because the type
1758 // itself is not a pack expansion type), so complain. This can occur when
1759 // the substitution goes through an alias template that "loses" the
1760 // pack expansion.
1761 Diag(OldParm->getLocation(),
1762 diag::err_function_parameter_pack_without_parameter_packs)
1763 << NewDI->getType();
1764 return nullptr;
1765 }
1766 } else {
1767 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1768 OldParm->getDeclName());
1769 }
1770
1771 if (!NewDI)
1772 return nullptr;
1773
1774 if (NewDI->getType()->isVoidType()) {
1775 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1776 return nullptr;
1777 }
1778
1779 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1780 OldParm->getInnerLocStart(),
1781 OldParm->getLocation(),
1782 OldParm->getIdentifier(),
1783 NewDI->getType(), NewDI,
1784 OldParm->getStorageClass());
1785 if (!NewParm)
1786 return nullptr;
1787
1788 // Mark the (new) default argument as uninstantiated (if any).
1789 if (OldParm->hasUninstantiatedDefaultArg()) {
1790 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1791 NewParm->setUninstantiatedDefaultArg(Arg);
1792 } else if (OldParm->hasUnparsedDefaultArg()) {
1793 NewParm->setUnparsedDefaultArg();
1794 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1795 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1796 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1797 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1798 // Instantiate default arguments for methods of local classes (DR1484)
1799 // and non-defining declarations.
1800 Sema::ContextRAII SavedContext(*this, OwningFunc);
1801 LocalInstantiationScope Local(*this, true);
1802 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1803 if (NewArg.isUsable()) {
1804 // It would be nice if we still had this.
1805 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1806 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1807 }
1808 } else {
1809 // FIXME: if we non-lazily instantiated non-dependent default args for
1810 // non-dependent parameter types we could remove a bunch of duplicate
1811 // conversion warnings for such arguments.
1812 NewParm->setUninstantiatedDefaultArg(Arg);
1813 }
1814 }
1815
1816 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1817
1818 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1819 // Add the new parameter to the instantiated parameter pack.
1820 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1821 } else {
1822 // Introduce an Old -> New mapping
1823 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1824 }
1825
1826 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1827 // can be anything, is this right ?
1828 NewParm->setDeclContext(CurContext);
1829
1830 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1831 OldParm->getFunctionScopeIndex() + indexAdjustment);
1832
1833 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1834
1835 return NewParm;
1836}
1837
1838/// \brief Substitute the given template arguments into the given set of
1839/// parameters, producing the set of parameter types that would be generated
1840/// from such a substitution.
1841bool Sema::SubstParmTypes(
1842 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1843 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1844 const MultiLevelTemplateArgumentList &TemplateArgs,
1845 SmallVectorImpl<QualType> &ParamTypes,
1846 SmallVectorImpl<ParmVarDecl *> *OutParams,
1847 ExtParameterInfoBuilder &ParamInfos) {
1848 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1850, __extension__ __PRETTY_FUNCTION__))
1849 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1850, __extension__ __PRETTY_FUNCTION__))
1850 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1850, __extension__ __PRETTY_FUNCTION__))
;
1851
1852 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1853 DeclarationName());
1854 return Instantiator.TransformFunctionTypeParams(
1855 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1856}
1857
1858/// \brief Perform substitution on the base class specifiers of the
1859/// given class template specialization.
1860///
1861/// Produces a diagnostic and returns true on error, returns false and
1862/// attaches the instantiated base classes to the class template
1863/// specialization if successful.
1864bool
1865Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1866 CXXRecordDecl *Pattern,
1867 const MultiLevelTemplateArgumentList &TemplateArgs) {
1868 bool Invalid = false;
1869 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1870 for (const auto &Base : Pattern->bases()) {
1871 if (!Base.getType()->isDependentType()) {
1872 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1873 if (RD->isInvalidDecl())
1874 Instantiation->setInvalidDecl();
1875 }
1876 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1877 continue;
1878 }
1879
1880 SourceLocation EllipsisLoc;
1881 TypeSourceInfo *BaseTypeLoc;
1882 if (Base.isPackExpansion()) {
1883 // This is a pack expansion. See whether we should expand it now, or
1884 // wait until later.
1885 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1886 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1887 Unexpanded);
1888 bool ShouldExpand = false;
1889 bool RetainExpansion = false;
1890 Optional<unsigned> NumExpansions;
1891 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1892 Base.getSourceRange(),
1893 Unexpanded,
1894 TemplateArgs, ShouldExpand,
1895 RetainExpansion,
1896 NumExpansions)) {
1897 Invalid = true;
1898 continue;
1899 }
1900
1901 // If we should expand this pack expansion now, do so.
1902 if (ShouldExpand) {
1903 for (unsigned I = 0; I != *NumExpansions; ++I) {
1904 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1905
1906 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1907 TemplateArgs,
1908 Base.getSourceRange().getBegin(),
1909 DeclarationName());
1910 if (!BaseTypeLoc) {
1911 Invalid = true;
1912 continue;
1913 }
1914
1915 if (CXXBaseSpecifier *InstantiatedBase
1916 = CheckBaseSpecifier(Instantiation,
1917 Base.getSourceRange(),
1918 Base.isVirtual(),
1919 Base.getAccessSpecifierAsWritten(),
1920 BaseTypeLoc,
1921 SourceLocation()))
1922 InstantiatedBases.push_back(InstantiatedBase);
1923 else
1924 Invalid = true;
1925 }
1926
1927 continue;
1928 }
1929
1930 // The resulting base specifier will (still) be a pack expansion.
1931 EllipsisLoc = Base.getEllipsisLoc();
1932 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1933 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1934 TemplateArgs,
1935 Base.getSourceRange().getBegin(),
1936 DeclarationName());
1937 } else {
1938 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1939 TemplateArgs,
1940 Base.getSourceRange().getBegin(),
1941 DeclarationName());
1942 }
1943
1944 if (!BaseTypeLoc) {
1945 Invalid = true;
1946 continue;
1947 }
1948
1949 if (CXXBaseSpecifier *InstantiatedBase
1950 = CheckBaseSpecifier(Instantiation,
1951 Base.getSourceRange(),
1952 Base.isVirtual(),
1953 Base.getAccessSpecifierAsWritten(),
1954 BaseTypeLoc,
1955 EllipsisLoc))
1956 InstantiatedBases.push_back(InstantiatedBase);
1957 else
1958 Invalid = true;
1959 }
1960
1961 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1962 Invalid = true;
1963
1964 return Invalid;
1965}
1966
1967// Defined via #include from SemaTemplateInstantiateDecl.cpp
1968namespace clang {
1969 namespace sema {
1970 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1971 const MultiLevelTemplateArgumentList &TemplateArgs);
1972 Attr *instantiateTemplateAttributeForDecl(
1973 const Attr *At, ASTContext &C, Sema &S,
1974 const MultiLevelTemplateArgumentList &TemplateArgs);
1975 }
1976}
1977
1978/// \brief Instantiate the definition of a class from a given pattern.
1979///
1980/// \param PointOfInstantiation The point of instantiation within the
1981/// source code.
1982///
1983/// \param Instantiation is the declaration whose definition is being
1984/// instantiated. This will be either a class template specialization
1985/// or a member class of a class template specialization.
1986///
1987/// \param Pattern is the pattern from which the instantiation
1988/// occurs. This will be either the declaration of a class template or
1989/// the declaration of a member class of a class template.
1990///
1991/// \param TemplateArgs The template arguments to be substituted into
1992/// the pattern.
1993///
1994/// \param TSK the kind of implicit or explicit instantiation to perform.
1995///
1996/// \param Complain whether to complain if the class cannot be instantiated due
1997/// to the lack of a definition.
1998///
1999/// \returns true if an error occurred, false otherwise.
2000bool
2001Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2002 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2003 const MultiLevelTemplateArgumentList &TemplateArgs,
2004 TemplateSpecializationKind TSK,
2005 bool Complain) {
2006 CXXRecordDecl *PatternDef
2007 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2008 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2009 Instantiation->getInstantiatedFromMemberClass(),
2010 Pattern, PatternDef, TSK, Complain))
2011 return true;
2012 Pattern = PatternDef;
2013
2014 // \brief Record the point of instantiation.
2015 if (MemberSpecializationInfo *MSInfo
2016 = Instantiation->getMemberSpecializationInfo()) {
2017 MSInfo->setTemplateSpecializationKind(TSK);
2018 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2019 } else if (ClassTemplateSpecializationDecl *Spec
2020 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2021 Spec->setTemplateSpecializationKind(TSK);
2022 Spec->setPointOfInstantiation(PointOfInstantiation);
2023 }
2024
2025 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2026 if (Inst.isInvalid())
2027 return true;
2028 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller")(static_cast <bool> (!Inst.isAlreadyInstantiating() &&
"should have been caught by caller") ? void (0) : __assert_fail
("!Inst.isAlreadyInstantiating() && \"should have been caught by caller\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2028, __extension__ __PRETTY_FUNCTION__))
;
2029 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2030 "instantiating class definition");
2031
2032 // Enter the scope of this instantiation. We don't use
2033 // PushDeclContext because we don't have a scope.
2034 ContextRAII SavedContext(*this, Instantiation);
2035 EnterExpressionEvaluationContext EvalContext(
2036 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2037
2038 // If this is an instantiation of a local class, merge this local
2039 // instantiation scope with the enclosing scope. Otherwise, every
2040 // instantiation of a class has its own local instantiation scope.
2041 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2042 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2043
2044 // Some class state isn't processed immediately but delayed till class
2045 // instantiation completes. We may not be ready to handle any delayed state
2046 // already on the stack as it might correspond to a different class, so save
2047 // it now and put it back later.
2048 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2049
2050 // Pull attributes from the pattern onto the instantiation.
2051 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2052
2053 // Start the definition of this instantiation.
2054 Instantiation->startDefinition();
2055
2056 // The instantiation is visible here, even if it was first declared in an
2057 // unimported module.
2058 Instantiation->setVisibleDespiteOwningModule();
2059
2060 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2061 Instantiation->setTagKind(Pattern->getTagKind());
2062
2063 // Do substitution on the base class specifiers.
2064 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2065 Instantiation->setInvalidDecl();
2066
2067 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2068 SmallVector<Decl*, 4> Fields;
2069 // Delay instantiation of late parsed attributes.
2070 LateInstantiatedAttrVec LateAttrs;
2071 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2072
2073 for (auto *Member : Pattern->decls()) {
2074 // Don't instantiate members not belonging in this semantic context.
2075 // e.g. for:
2076 // @code
2077 // template <int i> class A {
2078 // class B *g;
2079 // };
2080 // @endcode
2081 // 'class B' has the template as lexical context but semantically it is
2082 // introduced in namespace scope.
2083 if (Member->getDeclContext() != Pattern)
2084 continue;
2085
2086 if (Member->isInvalidDecl()) {
2087 Instantiation->setInvalidDecl();
2088 continue;
2089 }
2090
2091 Decl *NewMember = Instantiator.Visit(Member);
2092 if (NewMember) {
2093 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2094 Fields.push_back(Field);
2095 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2096 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2097 // specialization causes the implicit instantiation of the definitions
2098 // of unscoped member enumerations.
2099 // Record a point of instantiation for this implicit instantiation.
2100 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2101 Enum->isCompleteDefinition()) {
2102 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2103 assert(MSInfo && "no spec info for member enum specialization")(static_cast <bool> (MSInfo && "no spec info for member enum specialization"
) ? void (0) : __assert_fail ("MSInfo && \"no spec info for member enum specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2103, __extension__ __PRETTY_FUNCTION__))
;
2104 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2105 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2106 }
2107 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2108 if (SA->isFailed()) {
2109 // A static_assert failed. Bail out; instantiating this
2110 // class is probably not meaningful.
2111 Instantiation->setInvalidDecl();
2112 break;
2113 }
2114 }
2115
2116 if (NewMember->isInvalidDecl())
2117 Instantiation->setInvalidDecl();
2118 } else {
2119 // FIXME: Eventually, a NULL return will mean that one of the
2120 // instantiations was a semantic disaster, and we'll want to mark the
2121 // declaration invalid.
2122 // For now, we expect to skip some members that we can't yet handle.
2123 }
2124 }
2125
2126 // See if trivial_abi has to be dropped.
2127 if (Instantiation && Instantiation->hasAttr<TrivialABIAttr>())
2128 checkIllFormedTrivialABIStruct(*Instantiation);
2129
2130 // Finish checking fields.
2131 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2132 SourceLocation(), SourceLocation(), nullptr);
2133 CheckCompletedCXXClass(Instantiation);
2134
2135 // Default arguments are parsed, if not instantiated. We can go instantiate
2136 // default arg exprs for default constructors if necessary now.
2137 ActOnFinishCXXNonNestedClass(Instantiation);
2138
2139 // Instantiate late parsed attributes, and attach them to their decls.
2140 // See Sema::InstantiateAttrs
2141 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2142 E = LateAttrs.end(); I != E; ++I) {
2143 assert(CurrentInstantiationScope == Instantiator.getStartingScope())(static_cast <bool> (CurrentInstantiationScope == Instantiator
.getStartingScope()) ? void (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2143, __extension__ __PRETTY_FUNCTION__))
;
2144 CurrentInstantiationScope = I->Scope;
2145
2146 // Allow 'this' within late-parsed attributes.
2147 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2148 CXXRecordDecl *ThisContext =
2149 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2150 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2151 ND && ND->isCXXInstanceMember());
2152
2153 Attr *NewAttr =
2154 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2155 I->NewDecl->addAttr(NewAttr);
2156 LocalInstantiationScope::deleteScopes(I->Scope,
2157 Instantiator.getStartingScope());
2158 }
2159 Instantiator.disableLateAttributeInstantiation();
2160 LateAttrs.clear();
2161
2162 ActOnFinishDelayedMemberInitializers(Instantiation);
2163
2164 // FIXME: We should do something similar for explicit instantiations so they
2165 // end up in the right module.
2166 if (TSK == TSK_ImplicitInstantiation) {
2167 Instantiation->setLocation(Pattern->getLocation());
2168 Instantiation->setLocStart(Pattern->getInnerLocStart());
2169 Instantiation->setBraceRange(Pattern->getBraceRange());
2170 }
2171
2172 if (!Instantiation->isInvalidDecl()) {
2173 // Perform any dependent diagnostics from the pattern.
2174 PerformDependentDiagnostics(Pattern, TemplateArgs);
2175
2176 // Instantiate any out-of-line class template partial
2177 // specializations now.
2178 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2179 P = Instantiator.delayed_partial_spec_begin(),
2180 PEnd = Instantiator.delayed_partial_spec_end();
2181 P != PEnd; ++P) {
2182 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2183 P->first, P->second)) {
2184 Instantiation->setInvalidDecl();
2185 break;
2186 }
2187 }
2188
2189 // Instantiate any out-of-line variable template partial
2190 // specializations now.
2191 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2192 P = Instantiator.delayed_var_partial_spec_begin(),
2193 PEnd = Instantiator.delayed_var_partial_spec_end();
2194 P != PEnd; ++P) {
2195 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2196 P->first, P->second)) {
2197 Instantiation->setInvalidDecl();
2198 break;
2199 }
2200 }
2201 }
2202
2203 // Exit the scope of this instantiation.
2204 SavedContext.pop();
2205
2206 if (!Instantiation->isInvalidDecl()) {
2207 Consumer.HandleTagDeclDefinition(Instantiation);
2208
2209 // Always emit the vtable for an explicit instantiation definition
2210 // of a polymorphic class template specialization.
2211 if (TSK == TSK_ExplicitInstantiationDefinition)
2212 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2213 }
2214
2215 return Instantiation->isInvalidDecl();
2216}
2217
2218/// \brief Instantiate the definition of an enum from a given pattern.
2219///
2220/// \param PointOfInstantiation The point of instantiation within the
2221/// source code.
2222/// \param Instantiation is the declaration whose definition is being
2223/// instantiated. This will be a member enumeration of a class
2224/// temploid specialization, or a local enumeration within a
2225/// function temploid specialization.
2226/// \param Pattern The templated declaration from which the instantiation
2227/// occurs.
2228/// \param TemplateArgs The template arguments to be substituted into
2229/// the pattern.
2230/// \param TSK The kind of implicit or explicit instantiation to perform.
2231///
2232/// \return \c true if an error occurred, \c false otherwise.
2233bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2234 EnumDecl *Instantiation, EnumDecl *Pattern,
2235 const MultiLevelTemplateArgumentList &TemplateArgs,
2236 TemplateSpecializationKind TSK) {
2237 EnumDecl *PatternDef = Pattern->getDefinition();
2238 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2239 Instantiation->getInstantiatedFromMemberEnum(),
2240 Pattern, PatternDef, TSK,/*Complain*/true))
2241 return true;
2242 Pattern = PatternDef;
2243
2244 // Record the point of instantiation.
2245 if (MemberSpecializationInfo *MSInfo
2246 = Instantiation->getMemberSpecializationInfo()) {
2247 MSInfo->setTemplateSpecializationKind(TSK);
2248 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2249 }
2250
2251 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2252 if (Inst.isInvalid())
2253 return true;
2254 if (Inst.isAlreadyInstantiating())
2255 return false;
2256 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2257 "instantiating enum definition");
2258
2259 // The instantiation is visible here, even if it was first declared in an
2260 // unimported module.
2261 Instantiation->setVisibleDespiteOwningModule();
2262
2263 // Enter the scope of this instantiation. We don't use
2264 // PushDeclContext because we don't have a scope.
2265 ContextRAII SavedContext(*this, Instantiation);
2266 EnterExpressionEvaluationContext EvalContext(
2267 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2268
2269 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2270
2271 // Pull attributes from the pattern onto the instantiation.
2272 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2273
2274 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2275 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2276
2277 // Exit the scope of this instantiation.
2278 SavedContext.pop();
2279
2280 return Instantiation->isInvalidDecl();
2281}
2282
2283
2284/// \brief Instantiate the definition of a field from the given pattern.
2285///
2286/// \param PointOfInstantiation The point of instantiation within the
2287/// source code.
2288/// \param Instantiation is the declaration whose definition is being
2289/// instantiated. This will be a class of a class temploid
2290/// specialization, or a local enumeration within a function temploid
2291/// specialization.
2292/// \param Pattern The templated declaration from which the instantiation
2293/// occurs.
2294/// \param TemplateArgs The template arguments to be substituted into
2295/// the pattern.
2296///
2297/// \return \c true if an error occurred, \c false otherwise.
2298bool Sema::InstantiateInClassInitializer(
2299 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2300 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2301 // If there is no initializer, we don't need to do anything.
2302 if (!Pattern->hasInClassInitializer())
2303 return false;
2304
2305 assert(Instantiation->getInClassInitStyle() ==(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2307, __extension__ __PRETTY_FUNCTION__))
2306 Pattern->getInClassInitStyle() &&(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2307, __extension__ __PRETTY_FUNCTION__))
2307 "pattern and instantiation disagree about init style")(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2307, __extension__ __PRETTY_FUNCTION__))
;
2308
2309 // Error out if we haven't parsed the initializer of the pattern yet because
2310 // we are waiting for the closing brace of the outer class.
2311 Expr *OldInit = Pattern->getInClassInitializer();
2312 if (!OldInit) {
2313 RecordDecl *PatternRD = Pattern->getParent();
2314 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2315 Diag(PointOfInstantiation,
2316 diag::err_in_class_initializer_not_yet_parsed)
2317 << OutermostClass << Pattern;
2318 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2319 Instantiation->setInvalidDecl();
2320 return true;
2321 }
2322
2323 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2324 if (Inst.isInvalid())
2325 return true;
2326 if (Inst.isAlreadyInstantiating()) {
2327 // Error out if we hit an instantiation cycle for this initializer.
2328 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2329 << Instantiation;
2330 return true;
2331 }
2332 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2333 "instantiating default member init");
2334
2335 // Enter the scope of this instantiation. We don't use PushDeclContext because
2336 // we don't have a scope.
2337 ContextRAII SavedContext(*this, Instantiation->getParent());
2338 EnterExpressionEvaluationContext EvalContext(
2339 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2340
2341 LocalInstantiationScope Scope(*this, true);
2342
2343 // Instantiate the initializer.
2344 ActOnStartCXXInClassMemberInitializer();
2345 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2346
2347 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2348 /*CXXDirectInit=*/false);
2349 Expr *Init = NewInit.get();
2350 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class")(static_cast <bool> ((!Init || !isa<ParenListExpr>
(Init)) && "call-style init in class") ? void (0) : __assert_fail
("(!Init || !isa<ParenListExpr>(Init)) && \"call-style init in class\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2350, __extension__ __PRETTY_FUNCTION__))
;
2351 ActOnFinishCXXInClassMemberInitializer(
2352 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2353
2354 if (auto *L = getASTMutationListener())
2355 L->DefaultMemberInitializerInstantiated(Instantiation);
2356
2357 // Return true if the in-class initializer is still missing.
2358 return !Instantiation->getInClassInitializer();
2359}
2360
2361namespace {
2362 /// \brief A partial specialization whose template arguments have matched
2363 /// a given template-id.
2364 struct PartialSpecMatchResult {
2365 ClassTemplatePartialSpecializationDecl *Partial;
2366 TemplateArgumentList *Args;
2367 };
2368}
2369
2370bool Sema::usesPartialOrExplicitSpecialization(
2371 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2372 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2373 TSK_ExplicitSpecialization)
2374 return true;
2375
2376 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2377 ClassTemplateSpec->getSpecializedTemplate()
2378 ->getPartialSpecializations(PartialSpecs);
2379 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2380 TemplateDeductionInfo Info(Loc);
2381 if (!DeduceTemplateArguments(PartialSpecs[I],
2382 ClassTemplateSpec->getTemplateArgs(), Info))
2383 return true;
2384 }
2385
2386 return false;
2387}
2388
2389/// Get the instantiation pattern to use to instantiate the definition of a
2390/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2391/// template or of a partial specialization).
2392static CXXRecordDecl *
2393getPatternForClassTemplateSpecialization(
2394 Sema &S, SourceLocation PointOfInstantiation,
2395 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2396 TemplateSpecializationKind TSK, bool Complain) {
2397 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2398 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4
Taking false branch
2399 return nullptr;
2400
2401 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2402 CXXRecordDecl *Pattern = nullptr;
2403
2404 // C++ [temp.class.spec.match]p1:
2405 // When a class template is used in a context that requires an
2406 // instantiation of the class, it is necessary to determine
2407 // whether the instantiation is to be generated using the primary
2408 // template or one of the partial specializations. This is done by
2409 // matching the template arguments of the class template
2410 // specialization with the template argument lists of the partial
2411 // specializations.
2412 typedef PartialSpecMatchResult MatchResult;
2413 SmallVector<MatchResult, 4> Matched;
2414 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2415 Template->getPartialSpecializations(PartialSpecs);
2416 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2417 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
5
Assuming 'I' is equal to 'N'
6
Loop condition is false. Execution continues on line 2439
2418 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2419 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2420 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2421 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2422 // Store the failed-deduction information for use in diagnostics, later.
2423 // TODO: Actually use the failed-deduction info?
2424 FailedCandidates.addCandidate().set(
2425 DeclAccessPair::make(Template, AS_public), Partial,
2426 MakeDeductionFailureInfo(S.Context, Result, Info));
2427 (void)Result;
2428 } else {
2429 Matched.push_back(PartialSpecMatchResult());
2430 Matched.back().Partial = Partial;
2431 Matched.back().Args = Info.take();
2432 }
2433 }
2434
2435 // If we're dealing with a member template where the template parameters
2436 // have been instantiated, this provides the original template parameters
2437 // from which the member template's parameters were instantiated.
2438
2439 if (Matched.size() >= 1) {
7
Assuming the condition is true
8
Taking true branch
2440 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2441 if (Matched.size() == 1) {
9
Assuming the condition is true
10
Taking true branch
2442 // -- If exactly one matching specialization is found, the
2443 // instantiation is generated from that specialization.
2444 // We don't need to do anything for this.
2445 } else {
2446 // -- If more than one matching specialization is found, the
2447 // partial order rules (14.5.4.2) are used to determine
2448 // whether one of the specializations is more specialized
2449 // than the others. If none of the specializations is more
2450 // specialized than all of the other matching
2451 // specializations, then the use of the class template is
2452 // ambiguous and the program is ill-formed.
2453 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2454 PEnd = Matched.end();
2455 P != PEnd; ++P) {
2456 if (S.getMoreSpecializedPartialSpecialization(
2457 P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
2458 Best = P;
2459 }
2460
2461 // Determine if the best partial specialization is more specialized than
2462 // the others.
2463 bool Ambiguous = false;
2464 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2465 PEnd = Matched.end();
2466 P != PEnd; ++P) {
2467 if (P != Best &&
2468 S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2469 PointOfInstantiation) !=
2470 Best->Partial) {
2471 Ambiguous = true;
2472 break;
2473 }
2474 }
2475
2476 if (Ambiguous) {
2477 // Partial ordering did not produce a clear winner. Complain.
2478 Inst.Clear();
2479 ClassTemplateSpec->setInvalidDecl();
2480 S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2481 << ClassTemplateSpec;
2482
2483 // Print the matching partial specializations.
2484 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2485 PEnd = Matched.end();
2486 P != PEnd; ++P)
2487 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2488 << S.getTemplateArgumentBindingsText(
2489 P->Partial->getTemplateParameters(), *P->Args);
2490
2491 return nullptr;
2492 }
2493 }
2494
2495 // Instantiate using the best class template partial specialization.
2496 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2497 while (OrigPartialSpec->getInstantiatedFromMember()) {
11
Loop condition is false. Execution continues on line 2506
2498 // If we've found an explicit specialization of this class template,
2499 // stop here and use that as the pattern.
2500 if (OrigPartialSpec->isMemberSpecialization())
2501 break;
2502
2503 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2504 }
2505
2506 Pattern = OrigPartialSpec;
2507 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
12
Calling 'ClassTemplateSpecializationDecl::setInstantiationOf'
2508 } else {
2509 // -- If no matches are found, the instantiation is generated
2510 // from the primary template.
2511 ClassTemplateDecl *OrigTemplate = Template;
2512 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2513 // If we've found an explicit specialization of this class template,
2514 // stop here and use that as the pattern.
2515 if (OrigTemplate->isMemberSpecialization())
2516 break;
2517
2518 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2519 }
2520
2521 Pattern = OrigTemplate->getTemplatedDecl();
2522 }
2523
2524 return Pattern;
2525}
2526
2527bool Sema::InstantiateClassTemplateSpecialization(
2528 SourceLocation PointOfInstantiation,
2529 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2530 TemplateSpecializationKind TSK, bool Complain) {
2531 // Perform the actual instantiation on the canonical declaration.
2532 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2533 ClassTemplateSpec->getCanonicalDecl());
2534 if (ClassTemplateSpec->isInvalidDecl())
1
Assuming the condition is false
2
Taking false branch
2535 return true;
2536
2537 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
3
Calling 'getPatternForClassTemplateSpecialization'
2538 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2539 if (!Pattern)
2540 return true;
2541
2542 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2543 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2544 Complain);
2545}
2546
2547/// \brief Instantiates the definitions of all of the member
2548/// of the given class, which is an instantiation of a class template
2549/// or a member class of a template.
2550void
2551Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2552 CXXRecordDecl *Instantiation,
2553 const MultiLevelTemplateArgumentList &TemplateArgs,
2554 TemplateSpecializationKind TSK) {
2555 // FIXME: We need to notify the ASTMutationListener that we did all of these
2556 // things, in case we have an explicit instantiation definition in a PCM, a
2557 // module, or preamble, and the declaration is in an imported AST.
2558 assert((static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2562, __extension__ __PRETTY_FUNCTION__))
2559 (TSK == TSK_ExplicitInstantiationDefinition ||(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2562, __extension__ __PRETTY_FUNCTION__))
2560 TSK == TSK_ExplicitInstantiationDeclaration ||(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2562, __extension__ __PRETTY_FUNCTION__))
2561 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2562, __extension__ __PRETTY_FUNCTION__))
2562 "Unexpected template specialization kind!")(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2562, __extension__ __PRETTY_FUNCTION__))
;
2563 for (auto *D : Instantiation->decls()) {
2564 bool SuppressNew = false;
2565 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2566 if (FunctionDecl *Pattern
2567 = Function->getInstantiatedFromMemberFunction()) {
2568 MemberSpecializationInfo *MSInfo
2569 = Function->getMemberSpecializationInfo();
2570 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2570, __extension__ __PRETTY_FUNCTION__))
;
2571 if (MSInfo->getTemplateSpecializationKind()
2572 == TSK_ExplicitSpecialization)
2573 continue;
2574
2575 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2576 Function,
2577 MSInfo->getTemplateSpecializationKind(),
2578 MSInfo->getPointOfInstantiation(),
2579 SuppressNew) ||
2580 SuppressNew)
2581 continue;
2582
2583 // C++11 [temp.explicit]p8:
2584 // An explicit instantiation definition that names a class template
2585 // specialization explicitly instantiates the class template
2586 // specialization and is only an explicit instantiation definition
2587 // of members whose definition is visible at the point of
2588 // instantiation.
2589 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2590 continue;
2591
2592 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2593
2594 if (Function->isDefined()) {
2595 // Let the ASTConsumer know that this function has been explicitly
2596 // instantiated now, and its linkage might have changed.
2597 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2598 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2599 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2600 } else if (TSK == TSK_ImplicitInstantiation) {
2601 PendingLocalImplicitInstantiations.push_back(
2602 std::make_pair(Function, PointOfInstantiation));
2603 }
2604 }
2605 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2606 if (isa<VarTemplateSpecializationDecl>(Var))
2607 continue;
2608
2609 if (Var->isStaticDataMember()) {
2610 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2611 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2611, __extension__ __PRETTY_FUNCTION__))
;
2612 if (MSInfo->getTemplateSpecializationKind()
2613 == TSK_ExplicitSpecialization)
2614 continue;
2615
2616 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2617 Var,
2618 MSInfo->getTemplateSpecializationKind(),
2619 MSInfo->getPointOfInstantiation(),
2620 SuppressNew) ||
2621 SuppressNew)
2622 continue;
2623
2624 if (TSK == TSK_ExplicitInstantiationDefinition) {
2625 // C++0x [temp.explicit]p8:
2626 // An explicit instantiation definition that names a class template
2627 // specialization explicitly instantiates the class template
2628 // specialization and is only an explicit instantiation definition
2629 // of members whose definition is visible at the point of
2630 // instantiation.
2631 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2632 continue;
2633
2634 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2635 InstantiateVariableDefinition(PointOfInstantiation, Var);
2636 } else {
2637 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2638 }
2639 }
2640 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2641 // Always skip the injected-class-name, along with any
2642 // redeclarations of nested classes, since both would cause us
2643 // to try to instantiate the members of a class twice.
2644 // Skip closure types; they'll get instantiated when we instantiate
2645 // the corresponding lambda-expression.
2646 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2647 Record->isLambda())
2648 continue;
2649
2650 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2651 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2651, __extension__ __PRETTY_FUNCTION__))
;
2652
2653 if (MSInfo->getTemplateSpecializationKind()
2654 == TSK_ExplicitSpecialization)
2655 continue;
2656
2657 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2658 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2659 TSK == TSK_ExplicitInstantiationDeclaration) {
2660 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2661 // outer class doesn't affect the inner class.
2662 continue;
2663 }
2664
2665 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2666 Record,
2667 MSInfo->getTemplateSpecializationKind(),
2668 MSInfo->getPointOfInstantiation(),
2669 SuppressNew) ||
2670 SuppressNew)
2671 continue;
2672
2673 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2674 assert(Pattern && "Missing instantiated-from-template information")(static_cast <bool> (Pattern && "Missing instantiated-from-template information"
) ? void (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2674, __extension__ __PRETTY_FUNCTION__))
;
2675
2676 if (!Record->getDefinition()) {
2677 if (!Pattern->getDefinition()) {
2678 // C++0x [temp.explicit]p8:
2679 // An explicit instantiation definition that names a class template
2680 // specialization explicitly instantiates the class template
2681 // specialization and is only an explicit instantiation definition
2682 // of members whose definition is visible at the point of
2683 // instantiation.
2684 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2685 MSInfo->setTemplateSpecializationKind(TSK);
2686 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2687 }
2688
2689 continue;
2690 }
2691
2692 InstantiateClass(PointOfInstantiation, Record, Pattern,
2693 TemplateArgs,
2694 TSK);
2695 } else {
2696 if (TSK == TSK_ExplicitInstantiationDefinition &&
2697 Record->getTemplateSpecializationKind() ==
2698 TSK_ExplicitInstantiationDeclaration) {
2699 Record->setTemplateSpecializationKind(TSK);
2700 MarkVTableUsed(PointOfInstantiation, Record, true);
2701 }
2702 }
2703
2704 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2705 if (Pattern)
2706 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2707 TSK);
2708 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2709 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2710 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2710, __extension__ __PRETTY_FUNCTION__))
;
2711
2712 if (MSInfo->getTemplateSpecializationKind()
2713 == TSK_ExplicitSpecialization)
2714 continue;
2715
2716 if (CheckSpecializationInstantiationRedecl(
2717 PointOfInstantiation, TSK, Enum,
2718 MSInfo->getTemplateSpecializationKind(),
2719 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2720 SuppressNew)
2721 continue;
2722
2723 if (Enum->getDefinition())
2724 continue;
2725
2726 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2727 assert(Pattern && "Missing instantiated-from-template information")(static_cast <bool> (Pattern && "Missing instantiated-from-template information"
) ? void (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2727, __extension__ __PRETTY_FUNCTION__))
;
2728
2729 if (TSK == TSK_ExplicitInstantiationDefinition) {
2730 if (!Pattern->getDefinition())
2731 continue;
2732
2733 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2734 } else {
2735 MSInfo->setTemplateSpecializationKind(TSK);
2736 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2737 }
2738 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2739 // No need to instantiate in-class initializers during explicit
2740 // instantiation.
2741 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2742 CXXRecordDecl *ClassPattern =
2743 Instantiation->getTemplateInstantiationPattern();
2744 DeclContext::lookup_result Lookup =
2745 ClassPattern->lookup(Field->getDeclName());
2746 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2747 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2748 TemplateArgs);
2749 }
2750 }
2751 }
2752}
2753
2754/// \brief Instantiate the definitions of all of the members of the
2755/// given class template specialization, which was named as part of an
2756/// explicit instantiation.
2757void
2758Sema::InstantiateClassTemplateSpecializationMembers(
2759 SourceLocation PointOfInstantiation,
2760 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2761 TemplateSpecializationKind TSK) {
2762 // C++0x [temp.explicit]p7:
2763 // An explicit instantiation that names a class template
2764 // specialization is an explicit instantion of the same kind
2765 // (declaration or definition) of each of its members (not
2766 // including members inherited from base classes) that has not
2767 // been previously explicitly specialized in the translation unit
2768 // containing the explicit instantiation, except as described
2769 // below.
2770 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2771 getTemplateInstantiationArgs(ClassTemplateSpec),
2772 TSK);
2773}
2774
2775StmtResult
2776Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2777 if (!S)
2778 return S;
2779
2780 TemplateInstantiator Instantiator(*this, TemplateArgs,
2781 SourceLocation(),
2782 DeclarationName());
2783 return Instantiator.TransformStmt(S);
2784}
2785
2786ExprResult
2787Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2788 if (!E)
2789 return E;
2790
2791 TemplateInstantiator Instantiator(*this, TemplateArgs,
2792 SourceLocation(),
2793 DeclarationName());
2794 return Instantiator.TransformExpr(E);
2795}
2796
2797ExprResult Sema::SubstInitializer(Expr *Init,
2798 const MultiLevelTemplateArgumentList &TemplateArgs,
2799 bool CXXDirectInit) {
2800 TemplateInstantiator Instantiator(*this, TemplateArgs,
2801 SourceLocation(),
2802 DeclarationName());
2803 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2804}
2805
2806bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2807 const MultiLevelTemplateArgumentList &TemplateArgs,
2808 SmallVectorImpl<Expr *> &Outputs) {
2809 if (Exprs.empty())
2810 return false;
2811
2812 TemplateInstantiator Instantiator(*this, TemplateArgs,
2813 SourceLocation(),
2814 DeclarationName());
2815 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2816 IsCall, Outputs);
2817}
2818
2819NestedNameSpecifierLoc
2820Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2821 const MultiLevelTemplateArgumentList &TemplateArgs) {
2822 if (!NNS)
2823 return NestedNameSpecifierLoc();
2824
2825 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2826 DeclarationName());
2827 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2828}
2829
2830/// \brief Do template substitution on declaration name info.
2831DeclarationNameInfo
2832Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2833 const MultiLevelTemplateArgumentList &TemplateArgs) {
2834 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2835 NameInfo.getName());
2836 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2837}
2838
2839TemplateName
2840Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2841 TemplateName Name, SourceLocation Loc,
2842 const MultiLevelTemplateArgumentList &TemplateArgs) {
2843 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2844 DeclarationName());
2845 CXXScopeSpec SS;
2846 SS.Adopt(QualifierLoc);
2847 return Instantiator.TransformTemplateName(SS, Name, Loc);
2848}
2849
2850bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2851 TemplateArgumentListInfo &Result,
2852 const MultiLevelTemplateArgumentList &TemplateArgs) {
2853 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2854 DeclarationName());
2855
2856 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2857}
2858
2859static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2860 // When storing ParmVarDecls in the local instantiation scope, we always
2861 // want to use the ParmVarDecl from the canonical function declaration,
2862 // since the map is then valid for any redeclaration or definition of that
2863 // function.
2864 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2865 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2866 unsigned i = PV->getFunctionScopeIndex();
2867 // This parameter might be from a freestanding function type within the
2868 // function and isn't necessarily referring to one of FD's parameters.
2869 if (FD->getParamDecl(i) == PV)
2870 return FD->getCanonicalDecl()->getParamDecl(i);
2871 }
2872 }
2873 return D;
2874}
2875
2876
2877llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2878LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2879 D = getCanonicalParmVarDecl(D);
2880 for (LocalInstantiationScope *Current = this; Current;
2881 Current = Current->Outer) {
2882
2883 // Check if we found something within this scope.
2884 const Decl *CheckD = D;
2885 do {
2886 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2887 if (Found != Current->LocalDecls.end())
2888 return &Found->second;
2889
2890 // If this is a tag declaration, it's possible that we need to look for
2891 // a previous declaration.
2892 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2893 CheckD = Tag->getPreviousDecl();
2894 else
2895 CheckD = nullptr;
2896 } while (CheckD);
2897
2898 // If we aren't combined with our outer scope, we're done.
2899 if (!Current->CombineWithOuterScope)
2900 break;
2901 }
2902
2903 // If we're performing a partial substitution during template argument
2904 // deduction, we may not have values for template parameters yet.
2905 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2906 isa<TemplateTemplateParmDecl>(D))
2907 return nullptr;
2908
2909 // Local types referenced prior to definition may require instantiation.
2910 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2911 if (RD->isLocalClass())
2912 return nullptr;
2913
2914 // Enumeration types referenced prior to definition may appear as a result of
2915 // error recovery.
2916 if (isa<EnumDecl>(D))
2917 return nullptr;
2918
2919 // If we didn't find the decl, then we either have a sema bug, or we have a
2920 // forward reference to a label declaration. Return null to indicate that
2921 // we have an uninstantiated label.
2922 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope")(static_cast <bool> (isa<LabelDecl>(D) &&
"declaration not instantiated in this scope") ? void (0) : __assert_fail
("isa<LabelDecl>(D) && \"declaration not instantiated in this scope\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2922, __extension__ __PRETTY_FUNCTION__))
;
2923 return nullptr;
2924}
2925
2926void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2927 D = getCanonicalParmVarDecl(D);
2928 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2929 if (Stored.isNull()) {
2930#ifndef NDEBUG
2931 // It should not be present in any surrounding scope either.
2932 LocalInstantiationScope *Current = this;
2933 while (Current->CombineWithOuterScope && Current->Outer) {
2934 Current = Current->Outer;
2935 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Instantiated local in inner and outer scopes"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2936, __extension__ __PRETTY_FUNCTION__))
2936 "Instantiated local in inner and outer scopes")(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Instantiated local in inner and outer scopes"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2936, __extension__ __PRETTY_FUNCTION__))
;
2937 }
2938#endif
2939 Stored = Inst;
2940 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2941 Pack->push_back(cast<ParmVarDecl>(Inst));
2942 } else {
2943 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local")(static_cast <bool> (Stored.get<Decl *>() == Inst
&& "Already instantiated this local") ? void (0) : __assert_fail
("Stored.get<Decl *>() == Inst && \"Already instantiated this local\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2943, __extension__ __PRETTY_FUNCTION__))
;
2944 }
2945}
2946
2947void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2948 ParmVarDecl *Inst) {
2949 D = getCanonicalParmVarDecl(D);
2950 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2951 Pack->push_back(Inst);
2952}
2953
2954void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2955#ifndef NDEBUG
2956 // This should be the first time we've been told about this decl.
2957 for (LocalInstantiationScope *Current = this;
2958 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2959 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Creating local pack after instantiation of local"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2960, __extension__ __PRETTY_FUNCTION__))
2960 "Creating local pack after instantiation of local")(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Creating local pack after instantiation of local"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2960, __extension__ __PRETTY_FUNCTION__))
;
2961#endif
2962
2963 D = getCanonicalParmVarDecl(D);
2964 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2965 DeclArgumentPack *Pack = new DeclArgumentPack;
2966 Stored = Pack;
2967 ArgumentPacks.push_back(Pack);
2968}
2969
2970void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2971 const TemplateArgument *ExplicitArgs,
2972 unsigned NumExplicitArgs) {
2973 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&(static_cast <bool> ((!PartiallySubstitutedPack || PartiallySubstitutedPack
== Pack) && "Already have a partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2974, __extension__ __PRETTY_FUNCTION__))
2974 "Already have a partially-substituted pack")(static_cast <bool> ((!PartiallySubstitutedPack || PartiallySubstitutedPack
== Pack) && "Already have a partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2974, __extension__ __PRETTY_FUNCTION__))
;
2975 assert((!PartiallySubstitutedPack(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2977, __extension__ __PRETTY_FUNCTION__))
2976 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2977, __extension__ __PRETTY_FUNCTION__))
2977 "Wrong number of arguments in partially-substituted pack")(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2977, __extension__ __PRETTY_FUNCTION__))
;
2978 PartiallySubstitutedPack = Pack;
2979 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2980 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2981}
2982
2983NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2984 const TemplateArgument **ExplicitArgs,
2985 unsigned *NumExplicitArgs) const {
2986 if (ExplicitArgs)
2987 *ExplicitArgs = nullptr;
2988 if (NumExplicitArgs)
2989 *NumExplicitArgs = 0;
2990
2991 for (const LocalInstantiationScope *Current = this; Current;
2992 Current = Current->Outer) {
2993 if (Current->PartiallySubstitutedPack) {
2994 if (ExplicitArgs)
2995 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2996 if (NumExplicitArgs)
2997 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2998
2999 return Current->PartiallySubstitutedPack;
3000 }
3001
3002 if (!Current->CombineWithOuterScope)
3003 break;
3004 }
3005
3006 return nullptr;
3007}

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h

1//===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
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//
10/// \file
11/// \brief Defines the C++ template declaration subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
16#define LLVM_CLANG_AST_DECLTEMPLATE_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/Specifiers.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/PointerUnion.h"
32#include "llvm/ADT/iterator.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/TrailingObjects.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <iterator>
41#include <utility>
42
43namespace clang {
44
45enum BuiltinTemplateKind : int;
46class ClassTemplateDecl;
47class ClassTemplatePartialSpecializationDecl;
48class Expr;
49class FunctionTemplateDecl;
50class IdentifierInfo;
51class NonTypeTemplateParmDecl;
52class TemplateDecl;
53class TemplateTemplateParmDecl;
54class TemplateTypeParmDecl;
55class UnresolvedSetImpl;
56class VarTemplateDecl;
57class VarTemplatePartialSpecializationDecl;
58
59/// \brief Stores a template parameter of any kind.
60using TemplateParameter =
61 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
62 TemplateTemplateParmDecl *>;
63
64NamedDecl *getAsNamedDecl(TemplateParameter P);
65
66/// \brief Stores a list of template parameters for a TemplateDecl and its
67/// derived classes.
68class TemplateParameterList final
69 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
70 Expr *> {
71 /// The location of the 'template' keyword.
72 SourceLocation TemplateLoc;
73
74 /// The locations of the '<' and '>' angle brackets.
75 SourceLocation LAngleLoc, RAngleLoc;
76
77 /// The number of template parameters in this template
78 /// parameter list.
79 unsigned NumParams : 30;
80
81 /// Whether this template parameter list contains an unexpanded parameter
82 /// pack.
83 unsigned ContainsUnexpandedParameterPack : 1;
84
85 /// Whether this template parameter list has an associated requires-clause
86 unsigned HasRequiresClause : 1;
87
88protected:
89 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
90 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
91 Expr *RequiresClause);
92
93 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
94 return NumParams;
95 }
96
97 size_t numTrailingObjects(OverloadToken<Expr *>) const {
98 return HasRequiresClause;
99 }
100
101public:
102 template <size_t N, bool HasRequiresClause>
103 friend class FixedSizeTemplateParameterListStorage;
104 friend TrailingObjects;
105
106 static TemplateParameterList *Create(const ASTContext &C,
107 SourceLocation TemplateLoc,
108 SourceLocation LAngleLoc,
109 ArrayRef<NamedDecl *> Params,
110 SourceLocation RAngleLoc,
111 Expr *RequiresClause);
112
113 /// \brief Iterates through the template parameters in this list.
114 using iterator = NamedDecl **;
115
116 /// \brief Iterates through the template parameters in this list.
117 using const_iterator = NamedDecl * const *;
118
119 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
120 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
121 iterator end() { return begin() + NumParams; }
122 const_iterator end() const { return begin() + NumParams; }
123
124 unsigned size() const { return NumParams; }
125
126 ArrayRef<NamedDecl*> asArray() {
127 return llvm::makeArrayRef(begin(), end());
128 }
129 ArrayRef<const NamedDecl*> asArray() const {
130 return llvm::makeArrayRef(begin(), size());
131 }
132
133 NamedDecl* getParam(unsigned Idx) {
134 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 134, __extension__ __PRETTY_FUNCTION__))
;
135 return begin()[Idx];
136 }
137 const NamedDecl* getParam(unsigned Idx) const {
138 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 138, __extension__ __PRETTY_FUNCTION__))
;
139 return begin()[Idx];
140 }
141
142 /// \brief Returns the minimum number of arguments needed to form a
143 /// template specialization.
144 ///
145 /// This may be fewer than the number of template parameters, if some of
146 /// the parameters have default arguments or if there is a parameter pack.
147 unsigned getMinRequiredArguments() const;
148
149 /// \brief Get the depth of this template parameter list in the set of
150 /// template parameter lists.
151 ///
152 /// The first template parameter list in a declaration will have depth 0,
153 /// the second template parameter list will have depth 1, etc.
154 unsigned getDepth() const;
155
156 /// \brief Determine whether this template parameter list contains an
157 /// unexpanded parameter pack.
158 bool containsUnexpandedParameterPack() const {
159 return ContainsUnexpandedParameterPack;
160 }
161
162 /// \brief The constraint-expression of the associated requires-clause.
163 Expr *getRequiresClause() {
164 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
165 }
166
167 /// \brief The constraint-expression of the associated requires-clause.
168 const Expr *getRequiresClause() const {
169 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
170 }
171
172 SourceLocation getTemplateLoc() const { return TemplateLoc; }
173 SourceLocation getLAngleLoc() const { return LAngleLoc; }
174 SourceLocation getRAngleLoc() const { return RAngleLoc; }
175
176 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
177 return SourceRange(TemplateLoc, RAngleLoc);
178 }
179
180public:
181 // FIXME: workaround for MSVC 2013; remove when no longer needed
182 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
183};
184
185/// \brief Stores a list of template parameters and the associated
186/// requires-clause (if any) for a TemplateDecl and its derived classes.
187/// Suitable for creating on the stack.
188template <size_t N, bool HasRequiresClause>
189class FixedSizeTemplateParameterListStorage
190 : public TemplateParameterList::FixedSizeStorageOwner {
191 typename TemplateParameterList::FixedSizeStorage<
192 NamedDecl *, Expr *>::with_counts<
193 N, HasRequiresClause ? 1u : 0u
194 >::type storage;
195
196public:
197 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
198 SourceLocation LAngleLoc,
199 ArrayRef<NamedDecl *> Params,
200 SourceLocation RAngleLoc,
201 Expr *RequiresClause)
202 : FixedSizeStorageOwner(
203 (assert(N == Params.size())(static_cast <bool> (N == Params.size()) ? void (0) : __assert_fail
("N == Params.size()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 203, __extension__ __PRETTY_FUNCTION__))
,
204 assert(HasRequiresClause == static_cast<bool>(RequiresClause))(static_cast <bool> (HasRequiresClause == static_cast<
bool>(RequiresClause)) ? void (0) : __assert_fail ("HasRequiresClause == static_cast<bool>(RequiresClause)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 204, __extension__ __PRETTY_FUNCTION__))
,
205 new (static_cast<void *>(&storage)) TemplateParameterList(
206 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
207};
208
209/// \brief A template argument list.
210class TemplateArgumentList final
211 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
212 /// \brief The template argument list.
213 const TemplateArgument *Arguments;
214
215 /// \brief The number of template arguments in this template
216 /// argument list.
217 unsigned NumArguments;
218
219 // Constructs an instance with an internal Argument list, containing
220 // a copy of the Args array. (Called by CreateCopy)
221 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
222
223public:
224 friend TrailingObjects;
225
226 TemplateArgumentList(const TemplateArgumentList &) = delete;
227 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
228
229 /// \brief Type used to indicate that the template argument list itself is a
230 /// stack object. It does not own its template arguments.
231 enum OnStackType { OnStack };
232
233 /// \brief Create a new template argument list that copies the given set of
234 /// template arguments.
235 static TemplateArgumentList *CreateCopy(ASTContext &Context,
236 ArrayRef<TemplateArgument> Args);
237
238 /// \brief Construct a new, temporary template argument list on the stack.
239 ///
240 /// The template argument list does not own the template arguments
241 /// provided.
242 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
243 : Arguments(Args.data()), NumArguments(Args.size()) {}
244
245 /// \brief Produces a shallow copy of the given template argument list.
246 ///
247 /// This operation assumes that the input argument list outlives it.
248 /// This takes the list as a pointer to avoid looking like a copy
249 /// constructor, since this really really isn't safe to use that
250 /// way.
251 explicit TemplateArgumentList(const TemplateArgumentList *Other)
252 : Arguments(Other->data()), NumArguments(Other->size()) {}
253
254 /// \brief Retrieve the template argument at a given index.
255 const TemplateArgument &get(unsigned Idx) const {
256 assert(Idx < NumArguments && "Invalid template argument index")(static_cast <bool> (Idx < NumArguments && "Invalid template argument index"
) ? void (0) : __assert_fail ("Idx < NumArguments && \"Invalid template argument index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 256, __extension__ __PRETTY_FUNCTION__))
;
257 return data()[Idx];
258 }
259
260 /// \brief Retrieve the template argument at a given index.
261 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
262
263 /// \brief Produce this as an array ref.
264 ArrayRef<TemplateArgument> asArray() const {
265 return llvm::makeArrayRef(data(), size());
266 }
267
268 /// \brief Retrieve the number of template arguments in this
269 /// template argument list.
270 unsigned size() const { return NumArguments; }
271
272 /// \brief Retrieve a pointer to the template argument list.
273 const TemplateArgument *data() const { return Arguments; }
274};
275
276void *allocateDefaultArgStorageChain(const ASTContext &C);
277
278/// Storage for a default argument. This is conceptually either empty, or an
279/// argument value, or a pointer to a previous declaration that had a default
280/// argument.
281///
282/// However, this is complicated by modules: while we require all the default
283/// arguments for a template to be equivalent, there may be more than one, and
284/// we need to track all the originating parameters to determine if the default
285/// argument is visible.
286template<typename ParmDecl, typename ArgType>
287class DefaultArgStorage {
288 /// Storage for both the value *and* another parameter from which we inherit
289 /// the default argument. This is used when multiple default arguments for a
290 /// parameter are merged together from different modules.
291 struct Chain {
292 ParmDecl *PrevDeclWithDefaultArg;
293 ArgType Value;
294 };
295 static_assert(sizeof(Chain) == sizeof(void *) * 2,
296 "non-pointer argument type?");
297
298 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
299
300 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
301 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
302 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
303 Parm = Prev;
304 assert(!Parm->getDefaultArgStorage()(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
305 .ValueOrInherited.template is<ParmDecl *>() &&(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
306 "should only be one level of indirection")(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
;
307 return Parm;
308 }
309
310public:
311 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
312
313 /// Determine whether there is a default argument for this parameter.
314 bool isSet() const { return !ValueOrInherited.isNull(); }
315
316 /// Determine whether the default argument for this parameter was inherited
317 /// from a previous declaration of the same entity.
318 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
319
320 /// Get the default argument's value. This does not consider whether the
321 /// default argument is visible.
322 ArgType get() const {
323 const DefaultArgStorage *Storage = this;
324 if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
325 Storage = &Prev->getDefaultArgStorage();
326 if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
327 return C->Value;
328 return Storage->ValueOrInherited.template get<ArgType>();
329 }
330
331 /// Get the parameter from which we inherit the default argument, if any.
332 /// This is the parameter on which the default argument was actually written.
333 const ParmDecl *getInheritedFrom() const {
334 if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
335 return D;
336 if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
337 return C->PrevDeclWithDefaultArg;
338 return nullptr;
339 }
340
341 /// Set the default argument.
342 void set(ArgType Arg) {
343 assert(!isSet() && "default argument already set")(static_cast <bool> (!isSet() && "default argument already set"
) ? void (0) : __assert_fail ("!isSet() && \"default argument already set\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 343, __extension__ __PRETTY_FUNCTION__))
;
344 ValueOrInherited = Arg;
345 }
346
347 /// Set that the default argument was inherited from another parameter.
348 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
349 assert(!isInherited() && "default argument already inherited")(static_cast <bool> (!isInherited() && "default argument already inherited"
) ? void (0) : __assert_fail ("!isInherited() && \"default argument already inherited\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
351 if (!isSet())
352 ValueOrInherited = InheritedFrom;
353 else
354 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
355 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
356 }
357
358 /// Remove the default argument, even if it was inherited.
359 void clear() {
360 ValueOrInherited = ArgType();
361 }
362};
363
364//===----------------------------------------------------------------------===//
365// Kinds of Templates
366//===----------------------------------------------------------------------===//
367
368/// \brief Stores the template parameter list and associated constraints for
369/// \c TemplateDecl objects that track associated constraints.
370class ConstrainedTemplateDeclInfo {
371 friend TemplateDecl;
372
373public:
374 ConstrainedTemplateDeclInfo() = default;
375
376 TemplateParameterList *getTemplateParameters() const {
377 return TemplateParams;
378 }
379
380 Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
381
382protected:
383 void setTemplateParameters(TemplateParameterList *TParams) {
384 TemplateParams = TParams;
385 }
386
387 void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
388
389 TemplateParameterList *TemplateParams = nullptr;
390 Expr *AssociatedConstraints = nullptr;
391};
392
393
394/// \brief The base class of all kinds of template declarations (e.g.,
395/// class, function, etc.).
396///
397/// The TemplateDecl class stores the list of template parameters and a
398/// reference to the templated scoped declaration: the underlying AST node.
399class TemplateDecl : public NamedDecl {
400 void anchor() override;
401
402protected:
403 // Construct a template decl with the given name and parameters.
404 // Used when there is no templated element (e.g., for tt-params).
405 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
406 SourceLocation L, DeclarationName Name,
407 TemplateParameterList *Params)
408 : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
409 TemplateParams(CTDI) {
410 this->setTemplateParameters(Params);
411 }
412
413 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
414 TemplateParameterList *Params)
415 : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
416
417 // Construct a template decl with name, parameters, and templated element.
418 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
419 SourceLocation L, DeclarationName Name,
420 TemplateParameterList *Params, NamedDecl *Decl)
421 : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
422 TemplateParams(CTDI) {
423 this->setTemplateParameters(Params);
424 }
425
426 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
427 TemplateParameterList *Params, NamedDecl *Decl)
428 : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
429
430public:
431 /// Get the list of template parameters
432 TemplateParameterList *getTemplateParameters() const {
433 const auto *const CTDI =
434 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
435 return CTDI ? CTDI->getTemplateParameters()
436 : TemplateParams.get<TemplateParameterList *>();
437 }
438
439 /// Get the constraint-expression from the associated requires-clause (if any)
440 const Expr *getRequiresClause() const {
441 const TemplateParameterList *const TP = getTemplateParameters();
442 return TP ? TP->getRequiresClause() : nullptr;
443 }
444
445 Expr *getAssociatedConstraints() const {
446 const TemplateDecl *const C = cast<TemplateDecl>(getCanonicalDecl());
447 const auto *const CTDI =
448 C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
449 return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
450 }
451
452 /// Get the underlying, templated declaration.
453 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
454
455 // Implement isa/cast/dyncast/etc.
456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
457
458 static bool classofKind(Kind K) {
459 return K >= firstTemplate && K <= lastTemplate;
460 }
461
462 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
463 return SourceRange(getTemplateParameters()->getTemplateLoc(),
464 TemplatedDecl->getSourceRange().getEnd());
465 }
466
467protected:
468 NamedDecl *TemplatedDecl;
469 /// \brief The template parameter list and optional requires-clause
470 /// associated with this declaration; alternatively, a
471 /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
472 /// template are being tracked by this particular declaration.
473 llvm::PointerUnion<TemplateParameterList *,
474 ConstrainedTemplateDeclInfo *>
475 TemplateParams;
476
477 void setTemplateParameters(TemplateParameterList *TParams) {
478 if (auto *const CTDI =
479 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
480 CTDI->setTemplateParameters(TParams);
481 } else {
482 TemplateParams = TParams;
483 }
484 }
485
486 void setAssociatedConstraints(Expr *AC) {
487 assert(isCanonicalDecl() &&(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 488, __extension__ __PRETTY_FUNCTION__))
488 "Attaching associated constraints to non-canonical Decl")(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 488, __extension__ __PRETTY_FUNCTION__))
;
489 TemplateParams.get<ConstrainedTemplateDeclInfo *>()
490 ->setAssociatedConstraints(AC);
491 }
492
493public:
494 /// \brief Initialize the underlying templated declaration and
495 /// template parameters.
496 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
497 assert(!TemplatedDecl && "TemplatedDecl already set!")(static_cast <bool> (!TemplatedDecl && "TemplatedDecl already set!"
) ? void (0) : __assert_fail ("!TemplatedDecl && \"TemplatedDecl already set!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 497, __extension__ __PRETTY_FUNCTION__))
;
498 assert(!TemplateParams && "TemplateParams already set!")(static_cast <bool> (!TemplateParams && "TemplateParams already set!"
) ? void (0) : __assert_fail ("!TemplateParams && \"TemplateParams already set!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 498, __extension__ __PRETTY_FUNCTION__))
;
499 TemplatedDecl = templatedDecl;
500 TemplateParams = templateParams;
501 }
502};
503
504/// \brief Provides information about a function template specialization,
505/// which is a FunctionDecl that has been explicitly specialization or
506/// instantiated from a function template.
507class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
508 FunctionTemplateSpecializationInfo(FunctionDecl *FD,
509 FunctionTemplateDecl *Template,
510 TemplateSpecializationKind TSK,
511 const TemplateArgumentList *TemplateArgs,
512 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
513 SourceLocation POI)
514 : Function(FD), Template(Template, TSK - 1),
515 TemplateArguments(TemplateArgs),
516 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
517 PointOfInstantiation(POI) {}
518
519public:
520 static FunctionTemplateSpecializationInfo *
521 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
522 TemplateSpecializationKind TSK,
523 const TemplateArgumentList *TemplateArgs,
524 const TemplateArgumentListInfo *TemplateArgsAsWritten,
525 SourceLocation POI);
526
527 /// \brief The function template specialization that this structure
528 /// describes.
529 FunctionDecl *Function;
530
531 /// \brief The function template from which this function template
532 /// specialization was generated.
533 ///
534 /// The two bits contain the top 4 values of TemplateSpecializationKind.
535 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
536
537 /// \brief The template arguments used to produce the function template
538 /// specialization from the function template.
539 const TemplateArgumentList *TemplateArguments;
540
541 /// \brief The template arguments as written in the sources, if provided.
542 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
543
544 /// \brief The point at which this function template specialization was
545 /// first instantiated.
546 SourceLocation PointOfInstantiation;
547
548 /// \brief Retrieve the template from which this function was specialized.
549 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
550
551 /// \brief Determine what kind of template specialization this is.
552 TemplateSpecializationKind getTemplateSpecializationKind() const {
553 return (TemplateSpecializationKind)(Template.getInt() + 1);
554 }
555
556 bool isExplicitSpecialization() const {
557 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
558 }
559
560 /// \brief True if this declaration is an explicit specialization,
561 /// explicit instantiation declaration, or explicit instantiation
562 /// definition.
563 bool isExplicitInstantiationOrSpecialization() const {
564 return isTemplateExplicitInstantiationOrSpecialization(
565 getTemplateSpecializationKind());
566 }
567
568 /// \brief Set the template specialization kind.
569 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
570 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 571, __extension__ __PRETTY_FUNCTION__))
571 "Cannot encode TSK_Undeclared for a function template specialization")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 571, __extension__ __PRETTY_FUNCTION__))
;
572 Template.setInt(TSK - 1);
573 }
574
575 /// \brief Retrieve the first point of instantiation of this function
576 /// template specialization.
577 ///
578 /// The point of instantiation may be an invalid source location if this
579 /// function has yet to be instantiated.
580 SourceLocation getPointOfInstantiation() const {
581 return PointOfInstantiation;
582 }
583
584 /// \brief Set the (first) point of instantiation of this function template
585 /// specialization.
586 void setPointOfInstantiation(SourceLocation POI) {
587 PointOfInstantiation = POI;
588 }
589
590 void Profile(llvm::FoldingSetNodeID &ID) {
591 Profile(ID, TemplateArguments->asArray(),
592 Function->getASTContext());
593 }
594
595 static void
596 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
597 ASTContext &Context) {
598 ID.AddInteger(TemplateArgs.size());
599 for (const TemplateArgument &TemplateArg : TemplateArgs)
600 TemplateArg.Profile(ID, Context);
601 }
602};
603
604/// \brief Provides information a specialization of a member of a class
605/// template, which may be a member function, static data member,
606/// member class or member enumeration.
607class MemberSpecializationInfo {
608 // The member declaration from which this member was instantiated, and the
609 // manner in which the instantiation occurred (in the lower two bits).
610 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
611
612 // The point at which this member was first instantiated.
613 SourceLocation PointOfInstantiation;
614
615public:
616 explicit
617 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
618 SourceLocation POI = SourceLocation())
619 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
620 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 621, __extension__ __PRETTY_FUNCTION__))
621 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 621, __extension__ __PRETTY_FUNCTION__))
;
622 }
623
624 /// \brief Retrieve the member declaration from which this member was
625 /// instantiated.
626 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
627
628 /// \brief Determine what kind of template specialization this is.
629 TemplateSpecializationKind getTemplateSpecializationKind() const {
630 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
631 }
632
633 bool isExplicitSpecialization() const {
634 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
635 }
636
637 /// \brief Set the template specialization kind.
638 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
639 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 640, __extension__ __PRETTY_FUNCTION__))
640 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 640, __extension__ __PRETTY_FUNCTION__))
;
641 MemberAndTSK.setInt(TSK - 1);
642 }
643
644 /// \brief Retrieve the first point of instantiation of this member.
645 /// If the point of instantiation is an invalid location, then this member
646 /// has not yet been instantiated.
647 SourceLocation getPointOfInstantiation() const {
648 return PointOfInstantiation;
649 }
650
651 /// \brief Set the first point of instantiation.
652 void setPointOfInstantiation(SourceLocation POI) {
653 PointOfInstantiation = POI;
654 }
655};
656
657/// \brief Provides information about a dependent function-template
658/// specialization declaration.
659///
660/// Since explicit function template specialization and instantiation
661/// declarations can only appear in namespace scope, and you can only
662/// specialize a member of a fully-specialized class, the only way to
663/// get one of these is in a friend declaration like the following:
664///
665/// \code
666/// template \<class T> void foo(T);
667/// template \<class T> class A {
668/// friend void foo<>(T);
669/// };
670/// \endcode
671class DependentFunctionTemplateSpecializationInfo final
672 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
673 TemplateArgumentLoc,
674 FunctionTemplateDecl *> {
675 /// The number of potential template candidates.
676 unsigned NumTemplates;
677
678 /// The number of template arguments.
679 unsigned NumArgs;
680
681 /// The locations of the left and right angle brackets.
682 SourceRange AngleLocs;
683
684 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
685 return NumArgs;
686 }
687 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
688 return NumTemplates;
689 }
690
691 DependentFunctionTemplateSpecializationInfo(
692 const UnresolvedSetImpl &Templates,
693 const TemplateArgumentListInfo &TemplateArgs);
694
695public:
696 friend TrailingObjects;
697
698 static DependentFunctionTemplateSpecializationInfo *
699 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
700 const TemplateArgumentListInfo &TemplateArgs);
701
702 /// \brief Returns the number of function templates that this might
703 /// be a specialization of.
704 unsigned getNumTemplates() const { return NumTemplates; }
705
706 /// \brief Returns the i'th template candidate.
707 FunctionTemplateDecl *getTemplate(unsigned I) const {
708 assert(I < getNumTemplates() && "template index out of range")(static_cast <bool> (I < getNumTemplates() &&
"template index out of range") ? void (0) : __assert_fail ("I < getNumTemplates() && \"template index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 708, __extension__ __PRETTY_FUNCTION__))
;
709 return getTrailingObjects<FunctionTemplateDecl *>()[I];
710 }
711
712 /// \brief Returns the explicit template arguments that were given.
713 const TemplateArgumentLoc *getTemplateArgs() const {
714 return getTrailingObjects<TemplateArgumentLoc>();
715 }
716
717 /// \brief Returns the number of explicit template arguments that were given.
718 unsigned getNumTemplateArgs() const { return NumArgs; }
719
720 /// \brief Returns the nth template argument.
721 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
722 assert(I < getNumTemplateArgs() && "template arg index out of range")(static_cast <bool> (I < getNumTemplateArgs() &&
"template arg index out of range") ? void (0) : __assert_fail
("I < getNumTemplateArgs() && \"template arg index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 722, __extension__ __PRETTY_FUNCTION__))
;
723 return getTemplateArgs()[I];
724 }
725
726 SourceLocation getLAngleLoc() const {
727 return AngleLocs.getBegin();
728 }
729
730 SourceLocation getRAngleLoc() const {
731 return AngleLocs.getEnd();
732 }
733};
734
735/// Declaration of a redeclarable template.
736class RedeclarableTemplateDecl : public TemplateDecl,
737 public Redeclarable<RedeclarableTemplateDecl>
738{
739 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
740
741 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
742 return getNextRedeclaration();
743 }
744
745 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
746 return getPreviousDecl();
747 }
748
749 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
750 return getMostRecentDecl();
751 }
752
753protected:
754 template <typename EntryType> struct SpecEntryTraits {
755 using DeclType = EntryType;
756
757 static DeclType *getDecl(EntryType *D) {
758 return D;
759 }
760
761 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
762 return D->getTemplateArgs().asArray();
763 }
764 };
765
766 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
767 typename DeclType = typename SETraits::DeclType>
768 struct SpecIterator
769 : llvm::iterator_adaptor_base<
770 SpecIterator<EntryType, SETraits, DeclType>,
771 typename llvm::FoldingSetVector<EntryType>::iterator,
772 typename std::iterator_traits<typename llvm::FoldingSetVector<
773 EntryType>::iterator>::iterator_category,
774 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
775 SpecIterator() = default;
776 explicit SpecIterator(
777 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
778 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
779
780 DeclType *operator*() const {
781 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
782 }
783
784 DeclType *operator->() const { return **this; }
785 };
786
787 template <typename EntryType>
788 static SpecIterator<EntryType>
789 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
790 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
791 }
792
793 void loadLazySpecializationsImpl() const;
794
795 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
796 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
797 ArrayRef<TemplateArgument> Args, void *&InsertPos);
798
799 template <class Derived, class EntryType>
800 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
801 EntryType *Entry, void *InsertPos);
802
803 struct CommonBase {
804 CommonBase() : InstantiatedFromMember(nullptr, false) {}
805
806 /// \brief The template from which this was most
807 /// directly instantiated (or null).
808 ///
809 /// The boolean value indicates whether this template
810 /// was explicitly specialized.
811 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
812 InstantiatedFromMember;
813
814 /// \brief If non-null, points to an array of specializations (including
815 /// partial specializations) known only by their external declaration IDs.
816 ///
817 /// The first value in the array is the number of specializations/partial
818 /// specializations that follow.
819 uint32_t *LazySpecializations = nullptr;
820 };
821
822 /// \brief Pointer to the common data shared by all declarations of this
823 /// template.
824 mutable CommonBase *Common = nullptr;
825
826 /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
827 /// the same template. Calling this routine may implicitly allocate memory
828 /// for the common pointer.
829 CommonBase *getCommonPtr() const;
830
831 virtual CommonBase *newCommon(ASTContext &C) const = 0;
832
833 // Construct a template decl with name, parameters, and templated element.
834 RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
835 ASTContext &C, DeclContext *DC, SourceLocation L,
836 DeclarationName Name, TemplateParameterList *Params,
837 NamedDecl *Decl)
838 : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C)
839 {}
840
841 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
842 SourceLocation L, DeclarationName Name,
843 TemplateParameterList *Params, NamedDecl *Decl)
844 : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
845
846public:
847 friend class ASTDeclReader;
848 friend class ASTDeclWriter;
849 friend class ASTReader;
850 template <class decl_type> friend class RedeclarableTemplate;
851
852 /// \brief Retrieves the canonical declaration of this template.
853 RedeclarableTemplateDecl *getCanonicalDecl() override {
854 return getFirstDecl();
855 }
856 const RedeclarableTemplateDecl *getCanonicalDecl() const {
857 return getFirstDecl();
858 }
859
860 /// \brief Determines whether this template was a specialization of a
861 /// member template.
862 ///
863 /// In the following example, the function template \c X<int>::f and the
864 /// member template \c X<int>::Inner are member specializations.
865 ///
866 /// \code
867 /// template<typename T>
868 /// struct X {
869 /// template<typename U> void f(T, U);
870 /// template<typename U> struct Inner;
871 /// };
872 ///
873 /// template<> template<typename T>
874 /// void X<int>::f(int, T);
875 /// template<> template<typename T>
876 /// struct X<int>::Inner { /* ... */ };
877 /// \endcode
878 bool isMemberSpecialization() const {
879 return getCommonPtr()->InstantiatedFromMember.getInt();
880 }
881
882 /// \brief Note that this member template is a specialization.
883 void setMemberSpecialization() {
884 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 885, __extension__ __PRETTY_FUNCTION__))
885 "Only member templates can be member template specializations")(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 885, __extension__ __PRETTY_FUNCTION__))
;
886 getCommonPtr()->InstantiatedFromMember.setInt(true);
887 }
888
889 /// \brief Retrieve the member template from which this template was
890 /// instantiated, or nullptr if this template was not instantiated from a
891 /// member template.
892 ///
893 /// A template is instantiated from a member template when the member
894 /// template itself is part of a class template (or member thereof). For
895 /// example, given
896 ///
897 /// \code
898 /// template<typename T>
899 /// struct X {
900 /// template<typename U> void f(T, U);
901 /// };
902 ///
903 /// void test(X<int> x) {
904 /// x.f(1, 'a');
905 /// };
906 /// \endcode
907 ///
908 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
909 /// template
910 ///
911 /// \code
912 /// template<typename U> void X<int>::f(int, U);
913 /// \endcode
914 ///
915 /// which was itself created during the instantiation of \c X<int>. Calling
916 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
917 /// retrieve the FunctionTemplateDecl for the original template \c f within
918 /// the class template \c X<T>, i.e.,
919 ///
920 /// \code
921 /// template<typename T>
922 /// template<typename U>
923 /// void X<T>::f(T, U);
924 /// \endcode
925 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
926 return getCommonPtr()->InstantiatedFromMember.getPointer();
927 }
928
929 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
930 assert(!getCommonPtr()->InstantiatedFromMember.getPointer())(static_cast <bool> (!getCommonPtr()->InstantiatedFromMember
.getPointer()) ? void (0) : __assert_fail ("!getCommonPtr()->InstantiatedFromMember.getPointer()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 930, __extension__ __PRETTY_FUNCTION__))
;
931 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
932 }
933
934 using redecl_range = redeclarable_base::redecl_range;
935 using redecl_iterator = redeclarable_base::redecl_iterator;
936
937 using redeclarable_base::redecls_begin;
938 using redeclarable_base::redecls_end;
939 using redeclarable_base::redecls;
940 using redeclarable_base::getPreviousDecl;
941 using redeclarable_base::getMostRecentDecl;
942 using redeclarable_base::isFirstDecl;
943
944 // Implement isa/cast/dyncast/etc.
945 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
946
947 static bool classofKind(Kind K) {
948 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
949 }
950};
951
952template <> struct RedeclarableTemplateDecl::
953SpecEntryTraits<FunctionTemplateSpecializationInfo> {
954 using DeclType = FunctionDecl;
955
956 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
957 return I->Function;
958 }
959
960 static ArrayRef<TemplateArgument>
961 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
962 return I->TemplateArguments->asArray();
963 }
964};
965
966/// Declaration of a template function.
967class FunctionTemplateDecl : public RedeclarableTemplateDecl {
968protected:
969 friend class FunctionDecl;
970
971 /// \brief Data that is common to all of the declarations of a given
972 /// function template.
973 struct Common : CommonBase {
974 /// \brief The function template specializations for this function
975 /// template, including explicit specializations and instantiations.
976 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
977
978 /// \brief The set of "injected" template arguments used within this
979 /// function template.
980 ///
981 /// This pointer refers to the template arguments (there are as
982 /// many template arguments as template parameaters) for the function
983 /// template, and is allocated lazily, since most function templates do not
984 /// require the use of this information.
985 TemplateArgument *InjectedArgs = nullptr;
986
987 Common() = default;
988 };
989
990 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
991 DeclarationName Name, TemplateParameterList *Params,
992 NamedDecl *Decl)
993 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
994 Decl) {}
995
996 CommonBase *newCommon(ASTContext &C) const override;
997
998 Common *getCommonPtr() const {
999 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1000 }
1001
1002 /// \brief Retrieve the set of function template specializations of this
1003 /// function template.
1004 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
1005 getSpecializations() const;
1006
1007 /// \brief Add a specialization of this function template.
1008 ///
1009 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1010 /// retrieved by an earlier call to findSpecialization().
1011 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1012 void *InsertPos);
1013
1014public:
1015 friend class ASTDeclReader;
1016 friend class ASTDeclWriter;
1017
1018 /// \brief Load any lazily-loaded specializations from the external source.
1019 void LoadLazySpecializations() const;
1020
1021 /// Get the underlying function declaration of the template.
1022 FunctionDecl *getTemplatedDecl() const {
1023 return static_cast<FunctionDecl *>(TemplatedDecl);
1024 }
1025
1026 /// Returns whether this template declaration defines the primary
1027 /// pattern.
1028 bool isThisDeclarationADefinition() const {
1029 return getTemplatedDecl()->isThisDeclarationADefinition();
1030 }
1031
1032 /// \brief Return the specialization with the provided arguments if it exists,
1033 /// otherwise return the insertion point.
1034 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1035 void *&InsertPos);
1036
1037 FunctionTemplateDecl *getCanonicalDecl() override {
1038 return cast<FunctionTemplateDecl>(
1039 RedeclarableTemplateDecl::getCanonicalDecl());
1040 }
1041 const FunctionTemplateDecl *getCanonicalDecl() const {
1042 return cast<FunctionTemplateDecl>(
1043 RedeclarableTemplateDecl::getCanonicalDecl());
1044 }
1045
1046 /// \brief Retrieve the previous declaration of this function template, or
1047 /// nullptr if no such declaration exists.
1048 FunctionTemplateDecl *getPreviousDecl() {
1049 return cast_or_null<FunctionTemplateDecl>(
1050 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1051 }
1052 const FunctionTemplateDecl *getPreviousDecl() const {
1053 return cast_or_null<FunctionTemplateDecl>(
1054 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1055 }
1056
1057 FunctionTemplateDecl *getMostRecentDecl() {
1058 return cast<FunctionTemplateDecl>(
1059 static_cast<RedeclarableTemplateDecl *>(this)
1060 ->getMostRecentDecl());
1061 }
1062 const FunctionTemplateDecl *getMostRecentDecl() const {
1063 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1064 }
1065
1066 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1067 return cast_or_null<FunctionTemplateDecl>(
1068 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1069 }
1070
1071 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1072 using spec_range = llvm::iterator_range<spec_iterator>;
1073
1074 spec_range specializations() const {
1075 return spec_range(spec_begin(), spec_end());
1076 }
1077
1078 spec_iterator spec_begin() const {
1079 return makeSpecIterator(getSpecializations(), false);
1080 }
1081
1082 spec_iterator spec_end() const {
1083 return makeSpecIterator(getSpecializations(), true);
1084 }
1085
1086 /// \brief Retrieve the "injected" template arguments that correspond to the
1087 /// template parameters of this function template.
1088 ///
1089 /// Although the C++ standard has no notion of the "injected" template
1090 /// arguments for a function template, the notion is convenient when
1091 /// we need to perform substitutions inside the definition of a function
1092 /// template.
1093 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1094
1095 /// \brief Create a function template node.
1096 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1097 SourceLocation L,
1098 DeclarationName Name,
1099 TemplateParameterList *Params,
1100 NamedDecl *Decl);
1101
1102 /// \brief Create an empty function template node.
1103 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1104
1105 // Implement isa/cast/dyncast support
1106 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1107 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1108};
1109
1110//===----------------------------------------------------------------------===//
1111// Kinds of Template Parameters
1112//===----------------------------------------------------------------------===//
1113
1114/// \brief Defines the position of a template parameter within a template
1115/// parameter list.
1116///
1117/// Because template parameter can be listed
1118/// sequentially for out-of-line template members, each template parameter is
1119/// given a Depth - the nesting of template parameter scopes - and a Position -
1120/// the occurrence within the parameter list.
1121/// This class is inheritedly privately by different kinds of template
1122/// parameters and is not part of the Decl hierarchy. Just a facility.
1123class TemplateParmPosition {
1124protected:
1125 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1126 // position? Maybe?
1127 unsigned Depth;
1128 unsigned Position;
1129
1130 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1131
1132public:
1133 TemplateParmPosition() = delete;
1134
1135 /// Get the nesting depth of the template parameter.
1136 unsigned getDepth() const { return Depth; }
1137 void setDepth(unsigned D) { Depth = D; }
1138
1139 /// Get the position of the template parameter within its parameter list.
1140 unsigned getPosition() const { return Position; }
1141 void setPosition(unsigned P) { Position = P; }
1142
1143 /// Get the index of the template parameter within its parameter list.
1144 unsigned getIndex() const { return Position; }
1145};
1146
1147/// \brief Declaration of a template type parameter.
1148///
1149/// For example, "T" in
1150/// \code
1151/// template<typename T> class vector;
1152/// \endcode
1153class TemplateTypeParmDecl : public TypeDecl {
1154 /// Sema creates these on the stack during auto type deduction.
1155 friend class Sema;
1156
1157 /// \brief Whether this template type parameter was declaration with
1158 /// the 'typename' keyword.
1159 ///
1160 /// If false, it was declared with the 'class' keyword.
1161 bool Typename : 1;
1162
1163 /// \brief The default template argument, if any.
1164 using DefArgStorage =
1165 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1166 DefArgStorage DefaultArgument;
1167
1168 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1169 SourceLocation IdLoc, IdentifierInfo *Id,
1170 bool Typename)
1171 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1172
1173public:
1174 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1175 SourceLocation KeyLoc,
1176 SourceLocation NameLoc,
1177 unsigned D, unsigned P,
1178 IdentifierInfo *Id, bool Typename,
1179 bool ParameterPack);
1180 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1181 unsigned ID);
1182
1183 /// \brief Whether this template type parameter was declared with
1184 /// the 'typename' keyword.
1185 ///
1186 /// If not, it was declared with the 'class' keyword.
1187 bool wasDeclaredWithTypename() const { return Typename; }
1188
1189 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1190
1191 /// \brief Determine whether this template parameter has a default
1192 /// argument.
1193 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1194
1195 /// \brief Retrieve the default argument, if any.
1196 QualType getDefaultArgument() const {
1197 return DefaultArgument.get()->getType();
1198 }
1199
1200 /// \brief Retrieves the default argument's source information, if any.
1201 TypeSourceInfo *getDefaultArgumentInfo() const {
1202 return DefaultArgument.get();
1203 }
1204
1205 /// \brief Retrieves the location of the default argument declaration.
1206 SourceLocation getDefaultArgumentLoc() const;
1207
1208 /// \brief Determines whether the default argument was inherited
1209 /// from a previous declaration of this template.
1210 bool defaultArgumentWasInherited() const {
1211 return DefaultArgument.isInherited();
1212 }
1213
1214 /// \brief Set the default argument for this template parameter.
1215 void setDefaultArgument(TypeSourceInfo *DefArg) {
1216 DefaultArgument.set(DefArg);
1217 }
1218
1219 /// \brief Set that this default argument was inherited from another
1220 /// parameter.
1221 void setInheritedDefaultArgument(const ASTContext &C,
1222 TemplateTypeParmDecl *Prev) {
1223 DefaultArgument.setInherited(C, Prev);
1224 }
1225
1226 /// \brief Removes the default argument of this template parameter.
1227 void removeDefaultArgument() {
1228 DefaultArgument.clear();
1229 }
1230
1231 /// \brief Set whether this template type parameter was declared with
1232 /// the 'typename' or 'class' keyword.
1233 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1234
1235 /// \brief Retrieve the depth of the template parameter.
1236 unsigned getDepth() const;
1237
1238 /// \brief Retrieve the index of the template parameter.
1239 unsigned getIndex() const;
1240
1241 /// \brief Returns whether this is a parameter pack.
1242 bool isParameterPack() const;
1243
1244 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1245
1246 // Implement isa/cast/dyncast/etc.
1247 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1248 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1249};
1250
1251/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1252/// e.g., "Size" in
1253/// @code
1254/// template<int Size> class array { };
1255/// @endcode
1256class NonTypeTemplateParmDecl final
1257 : public DeclaratorDecl,
1258 protected TemplateParmPosition,
1259 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1260 std::pair<QualType, TypeSourceInfo *>> {
1261 friend class ASTDeclReader;
1262 friend TrailingObjects;
1263
1264 /// \brief The default template argument, if any, and whether or not
1265 /// it was inherited.
1266 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1267 DefArgStorage DefaultArgument;
1268
1269 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1270 // down here to save memory.
1271
1272 /// \brief Whether this non-type template parameter is a parameter pack.
1273 bool ParameterPack;
1274
1275 /// \brief Whether this non-type template parameter is an "expanded"
1276 /// parameter pack, meaning that its type is a pack expansion and we
1277 /// already know the set of types that expansion expands to.
1278 bool ExpandedParameterPack = false;
1279
1280 /// \brief The number of types in an expanded parameter pack.
1281 unsigned NumExpandedTypes = 0;
1282
1283 size_t numTrailingObjects(
1284 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1285 return NumExpandedTypes;
1286 }
1287
1288 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1289 SourceLocation IdLoc, unsigned D, unsigned P,
1290 IdentifierInfo *Id, QualType T,
1291 bool ParameterPack, TypeSourceInfo *TInfo)
1292 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1293 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1294
1295 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1296 SourceLocation IdLoc, unsigned D, unsigned P,
1297 IdentifierInfo *Id, QualType T,
1298 TypeSourceInfo *TInfo,
1299 ArrayRef<QualType> ExpandedTypes,
1300 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1301
1302public:
1303 static NonTypeTemplateParmDecl *
1304 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1305 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1306 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1307
1308 static NonTypeTemplateParmDecl *
1309 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1310 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1311 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1312 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1313
1314 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1315 unsigned ID);
1316 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1317 unsigned ID,
1318 unsigned NumExpandedTypes);
1319
1320 using TemplateParmPosition::getDepth;
1321 using TemplateParmPosition::setDepth;
1322 using TemplateParmPosition::getPosition;
1323 using TemplateParmPosition::setPosition;
1324 using TemplateParmPosition::getIndex;
1325
1326 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1327
1328 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1329
1330 /// \brief Determine whether this template parameter has a default
1331 /// argument.
1332 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1333
1334 /// \brief Retrieve the default argument, if any.
1335 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1336
1337 /// \brief Retrieve the location of the default argument, if any.
1338 SourceLocation getDefaultArgumentLoc() const;
1339
1340 /// \brief Determines whether the default argument was inherited
1341 /// from a previous declaration of this template.
1342 bool defaultArgumentWasInherited() const {
1343 return DefaultArgument.isInherited();
1344 }
1345
1346 /// \brief Set the default argument for this template parameter, and
1347 /// whether that default argument was inherited from another
1348 /// declaration.
1349 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1350 void setInheritedDefaultArgument(const ASTContext &C,
1351 NonTypeTemplateParmDecl *Parm) {
1352 DefaultArgument.setInherited(C, Parm);
1353 }
1354
1355 /// \brief Removes the default argument of this template parameter.
1356 void removeDefaultArgument() { DefaultArgument.clear(); }
1357
1358 /// \brief Whether this parameter is a non-type template parameter pack.
1359 ///
1360 /// If the parameter is a parameter pack, the type may be a
1361 /// \c PackExpansionType. In the following example, the \c Dims parameter
1362 /// is a parameter pack (whose type is 'unsigned').
1363 ///
1364 /// \code
1365 /// template<typename T, unsigned ...Dims> struct multi_array;
1366 /// \endcode
1367 bool isParameterPack() const { return ParameterPack; }
1368
1369 /// \brief Whether this parameter pack is a pack expansion.
1370 ///
1371 /// A non-type template parameter pack is a pack expansion if its type
1372 /// contains an unexpanded parameter pack. In this case, we will have
1373 /// built a PackExpansionType wrapping the type.
1374 bool isPackExpansion() const {
1375 return ParameterPack && getType()->getAs<PackExpansionType>();
1376 }
1377
1378 /// \brief Whether this parameter is a non-type template parameter pack
1379 /// that has a known list of different types at different positions.
1380 ///
1381 /// A parameter pack is an expanded parameter pack when the original
1382 /// parameter pack's type was itself a pack expansion, and that expansion
1383 /// has already been expanded. For example, given:
1384 ///
1385 /// \code
1386 /// template<typename ...Types>
1387 /// struct X {
1388 /// template<Types ...Values>
1389 /// struct Y { /* ... */ };
1390 /// };
1391 /// \endcode
1392 ///
1393 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1394 /// which expands \c Types. When \c Types is supplied with template arguments
1395 /// by instantiating \c X, the instantiation of \c Values becomes an
1396 /// expanded parameter pack. For example, instantiating
1397 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1398 /// pack with expansion types \c int and \c unsigned int.
1399 ///
1400 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1401 /// return the expansion types.
1402 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1403
1404 /// \brief Retrieves the number of expansion types in an expanded parameter
1405 /// pack.
1406 unsigned getNumExpansionTypes() const {
1407 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1407, __extension__ __PRETTY_FUNCTION__))
;
1408 return NumExpandedTypes;
1409 }
1410
1411 /// \brief Retrieve a particular expansion type within an expanded parameter
1412 /// pack.
1413 QualType getExpansionType(unsigned I) const {
1414 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1414, __extension__ __PRETTY_FUNCTION__))
;
1415 auto TypesAndInfos =
1416 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1417 return TypesAndInfos[I].first;
1418 }
1419
1420 /// \brief Retrieve a particular expansion type source info within an
1421 /// expanded parameter pack.
1422 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1423 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1423, __extension__ __PRETTY_FUNCTION__))
;
1424 auto TypesAndInfos =
1425 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1426 return TypesAndInfos[I].second;
1427 }
1428
1429 // Implement isa/cast/dyncast/etc.
1430 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1431 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1432};
1433
1434/// TemplateTemplateParmDecl - Declares a template template parameter,
1435/// e.g., "T" in
1436/// @code
1437/// template <template <typename> class T> class container { };
1438/// @endcode
1439/// A template template parameter is a TemplateDecl because it defines the
1440/// name of a template and the template parameters allowable for substitution.
1441class TemplateTemplateParmDecl final
1442 : public TemplateDecl,
1443 protected TemplateParmPosition,
1444 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1445 TemplateParameterList *> {
1446 /// \brief The default template argument, if any.
1447 using DefArgStorage =
1448 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1449 DefArgStorage DefaultArgument;
1450
1451 /// \brief Whether this parameter is a parameter pack.
1452 bool ParameterPack;
1453
1454 /// \brief Whether this template template parameter is an "expanded"
1455 /// parameter pack, meaning that it is a pack expansion and we
1456 /// already know the set of template parameters that expansion expands to.
1457 bool ExpandedParameterPack = false;
1458
1459 /// \brief The number of parameters in an expanded parameter pack.
1460 unsigned NumExpandedParams = 0;
1461
1462 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1463 unsigned D, unsigned P, bool ParameterPack,
1464 IdentifierInfo *Id, TemplateParameterList *Params)
1465 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1466 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1467
1468 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1469 unsigned D, unsigned P,
1470 IdentifierInfo *Id, TemplateParameterList *Params,
1471 ArrayRef<TemplateParameterList *> Expansions);
1472
1473 void anchor() override;
1474
1475public:
1476 friend class ASTDeclReader;
1477 friend class ASTDeclWriter;
1478 friend TrailingObjects;
1479
1480 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1481 SourceLocation L, unsigned D,
1482 unsigned P, bool ParameterPack,
1483 IdentifierInfo *Id,
1484 TemplateParameterList *Params);
1485 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1486 SourceLocation L, unsigned D,
1487 unsigned P,
1488 IdentifierInfo *Id,
1489 TemplateParameterList *Params,
1490 ArrayRef<TemplateParameterList *> Expansions);
1491
1492 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1493 unsigned ID);
1494 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1495 unsigned ID,
1496 unsigned NumExpansions);
1497
1498 using TemplateParmPosition::getDepth;
1499 using TemplateParmPosition::setDepth;
1500 using TemplateParmPosition::getPosition;
1501 using TemplateParmPosition::setPosition;
1502 using TemplateParmPosition::getIndex;
1503
1504 /// \brief Whether this template template parameter is a template
1505 /// parameter pack.
1506 ///
1507 /// \code
1508 /// template<template <class T> ...MetaFunctions> struct Apply;
1509 /// \endcode
1510 bool isParameterPack() const { return ParameterPack; }
1511
1512 /// \brief Whether this parameter pack is a pack expansion.
1513 ///
1514 /// A template template parameter pack is a pack expansion if its template
1515 /// parameter list contains an unexpanded parameter pack.
1516 bool isPackExpansion() const {
1517 return ParameterPack &&
1518 getTemplateParameters()->containsUnexpandedParameterPack();
1519 }
1520
1521 /// \brief Whether this parameter is a template template parameter pack that
1522 /// has a known list of different template parameter lists at different
1523 /// positions.
1524 ///
1525 /// A parameter pack is an expanded parameter pack when the original parameter
1526 /// pack's template parameter list was itself a pack expansion, and that
1527 /// expansion has already been expanded. For exampe, given:
1528 ///
1529 /// \code
1530 /// template<typename...Types> struct Outer {
1531 /// template<template<Types> class...Templates> struct Inner;
1532 /// };
1533 /// \endcode
1534 ///
1535 /// The parameter pack \c Templates is a pack expansion, which expands the
1536 /// pack \c Types. When \c Types is supplied with template arguments by
1537 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1538 /// parameter pack.
1539 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1540
1541 /// \brief Retrieves the number of expansion template parameters in
1542 /// an expanded parameter pack.
1543 unsigned getNumExpansionTemplateParameters() const {
1544 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1544, __extension__ __PRETTY_FUNCTION__))
;
1545 return NumExpandedParams;
1546 }
1547
1548 /// \brief Retrieve a particular expansion type within an expanded parameter
1549 /// pack.
1550 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1551 assert(I < NumExpandedParams && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedParams &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedParams && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1551, __extension__ __PRETTY_FUNCTION__))
;
1552 return getTrailingObjects<TemplateParameterList *>()[I];
1553 }
1554
1555 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1556
1557 /// \brief Determine whether this template parameter has a default
1558 /// argument.
1559 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1560
1561 /// \brief Retrieve the default argument, if any.
1562 const TemplateArgumentLoc &getDefaultArgument() const {
1563 static const TemplateArgumentLoc None;
1564 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1565 }
1566
1567 /// \brief Retrieve the location of the default argument, if any.
1568 SourceLocation getDefaultArgumentLoc() const;
1569
1570 /// \brief Determines whether the default argument was inherited
1571 /// from a previous declaration of this template.
1572 bool defaultArgumentWasInherited() const {
1573 return DefaultArgument.isInherited();
1574 }
1575
1576 /// \brief Set the default argument for this template parameter, and
1577 /// whether that default argument was inherited from another
1578 /// declaration.
1579 void setDefaultArgument(const ASTContext &C,
1580 const TemplateArgumentLoc &DefArg);
1581 void setInheritedDefaultArgument(const ASTContext &C,
1582 TemplateTemplateParmDecl *Prev) {
1583 DefaultArgument.setInherited(C, Prev);
1584 }
1585
1586 /// \brief Removes the default argument of this template parameter.
1587 void removeDefaultArgument() { DefaultArgument.clear(); }
1588
1589 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1590 SourceLocation End = getLocation();
1591 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1592 End = getDefaultArgument().getSourceRange().getEnd();
1593 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1594 }
1595
1596 // Implement isa/cast/dyncast/etc.
1597 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1598 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1599};
1600
1601/// \brief Represents the builtin template declaration which is used to
1602/// implement __make_integer_seq and other builtin templates. It serves
1603/// no real purpose beyond existing as a place to hold template parameters.
1604class BuiltinTemplateDecl : public TemplateDecl {
1605 BuiltinTemplateKind BTK;
1606
1607 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1608 DeclarationName Name, BuiltinTemplateKind BTK);
1609
1610 void anchor() override;
1611
1612public:
1613 // Implement isa/cast/dyncast support
1614 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1615 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1616
1617 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1618 DeclarationName Name,
1619 BuiltinTemplateKind BTK) {
1620 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1621 }
1622
1623 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1624 return SourceRange();
1625 }
1626
1627 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1628};
1629
1630/// \brief Represents a class template specialization, which refers to
1631/// a class template with a given set of template arguments.
1632///
1633/// Class template specializations represent both explicit
1634/// specialization of class templates, as in the example below, and
1635/// implicit instantiations of class templates.
1636///
1637/// \code
1638/// template<typename T> class array;
1639///
1640/// template<>
1641/// class array<bool> { }; // class template specialization array<bool>
1642/// \endcode
1643class ClassTemplateSpecializationDecl
1644 : public CXXRecordDecl, public llvm::FoldingSetNode {
1645 /// \brief Structure that stores information about a class template
1646 /// specialization that was instantiated from a class template partial
1647 /// specialization.
1648 struct SpecializedPartialSpecialization {
1649 /// \brief The class template partial specialization from which this
1650 /// class template specialization was instantiated.
1651 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1652
1653 /// \brief The template argument list deduced for the class template
1654 /// partial specialization itself.
1655 const TemplateArgumentList *TemplateArgs;
1656 };
1657
1658 /// \brief The template that this specialization specializes
1659 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1660 SpecializedTemplate;
1661
1662 /// \brief Further info for explicit template specialization/instantiation.
1663 struct ExplicitSpecializationInfo {
1664 /// \brief The type-as-written.
1665 TypeSourceInfo *TypeAsWritten = nullptr;
1666
1667 /// \brief The location of the extern keyword.
1668 SourceLocation ExternLoc;
1669
1670 /// \brief The location of the template keyword.
1671 SourceLocation TemplateKeywordLoc;
1672
1673 ExplicitSpecializationInfo() = default;
1674 };
1675
1676 /// \brief Further info for explicit template specialization/instantiation.
1677 /// Does not apply to implicit specializations.
1678 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1679
1680 /// \brief The template arguments used to describe this specialization.
1681 const TemplateArgumentList *TemplateArgs;
1682
1683 /// \brief The point where this template was instantiated (if any)
1684 SourceLocation PointOfInstantiation;
1685
1686 /// \brief The kind of specialization this declaration refers to.
1687 /// Really a value of type TemplateSpecializationKind.
1688 unsigned SpecializationKind : 3;
1689
1690protected:
1691 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1692 DeclContext *DC, SourceLocation StartLoc,
1693 SourceLocation IdLoc,
1694 ClassTemplateDecl *SpecializedTemplate,
1695 ArrayRef<TemplateArgument> Args,
1696 ClassTemplateSpecializationDecl *PrevDecl);
1697
1698 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1699
1700public:
1701 friend class ASTDeclReader;
1702 friend class ASTDeclWriter;
1703
1704 static ClassTemplateSpecializationDecl *
1705 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1706 SourceLocation StartLoc, SourceLocation IdLoc,
1707 ClassTemplateDecl *SpecializedTemplate,
1708 ArrayRef<TemplateArgument> Args,
1709 ClassTemplateSpecializationDecl *PrevDecl);
1710 static ClassTemplateSpecializationDecl *
1711 CreateDeserialized(ASTContext &C, unsigned ID);
1712
1713 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1714 bool Qualified) const override;
1715
1716 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1717 // different "most recent" declaration from this function for the same
1718 // declaration, because we don't override getMostRecentDeclImpl(). But
1719 // it's not clear that we should override that, because the most recent
1720 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1721 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1722 CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
1723 this)->getMostRecentDecl();
1724 while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1725 // FIXME: Does injected class name need to be in the redeclarations chain?
1726 assert(Recent->isInjectedClassName() && Recent->getPreviousDecl())(static_cast <bool> (Recent->isInjectedClassName() &&
Recent->getPreviousDecl()) ? void (0) : __assert_fail ("Recent->isInjectedClassName() && Recent->getPreviousDecl()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1726, __extension__ __PRETTY_FUNCTION__))
;
1727 Recent = Recent->getPreviousDecl();
1728 }
1729 return cast<ClassTemplateSpecializationDecl>(Recent);
1730 }
1731
1732 /// \brief Retrieve the template that this specialization specializes.
1733 ClassTemplateDecl *getSpecializedTemplate() const;
1734
1735 /// \brief Retrieve the template arguments of the class template
1736 /// specialization.
1737 const TemplateArgumentList &getTemplateArgs() const {
1738 return *TemplateArgs;
1739 }
1740
1741 /// \brief Determine the kind of specialization that this
1742 /// declaration represents.
1743 TemplateSpecializationKind getSpecializationKind() const {
1744 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1745 }
1746
1747 bool isExplicitSpecialization() const {
1748 return getSpecializationKind() == TSK_ExplicitSpecialization;
1749 }
1750
1751 /// \brief True if this declaration is an explicit specialization,
1752 /// explicit instantiation declaration, or explicit instantiation
1753 /// definition.
1754 bool isExplicitInstantiationOrSpecialization() const {
1755 return isTemplateExplicitInstantiationOrSpecialization(
1756 getTemplateSpecializationKind());
1757 }
1758
1759 void setSpecializationKind(TemplateSpecializationKind TSK) {
1760 SpecializationKind = TSK;
1761 }
1762
1763 /// \brief Get the point of instantiation (if any), or null if none.
1764 SourceLocation getPointOfInstantiation() const {
1765 return PointOfInstantiation;
1766 }
1767
1768 void setPointOfInstantiation(SourceLocation Loc) {
1769 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1769, __extension__ __PRETTY_FUNCTION__))
;
1770 PointOfInstantiation = Loc;
1771 }
1772
1773 /// \brief If this class template specialization is an instantiation of
1774 /// a template (rather than an explicit specialization), return the
1775 /// class template or class template partial specialization from which it
1776 /// was instantiated.
1777 llvm::PointerUnion<ClassTemplateDecl *,
1778 ClassTemplatePartialSpecializationDecl *>
1779 getInstantiatedFrom() const {
1780 if (!isTemplateInstantiation(getSpecializationKind()))
1781 return llvm::PointerUnion<ClassTemplateDecl *,
1782 ClassTemplatePartialSpecializationDecl *>();
1783
1784 return getSpecializedTemplateOrPartial();
1785 }
1786
1787 /// \brief Retrieve the class template or class template partial
1788 /// specialization which was specialized by this.
1789 llvm::PointerUnion<ClassTemplateDecl *,
1790 ClassTemplatePartialSpecializationDecl *>
1791 getSpecializedTemplateOrPartial() const {
1792 if (SpecializedPartialSpecialization *PartialSpec
1793 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1794 return PartialSpec->PartialSpecialization;
1795
1796 return SpecializedTemplate.get<ClassTemplateDecl*>();
1797 }
1798
1799 /// \brief Retrieve the set of template arguments that should be used
1800 /// to instantiate members of the class template or class template partial
1801 /// specialization from which this class template specialization was
1802 /// instantiated.
1803 ///
1804 /// \returns For a class template specialization instantiated from the primary
1805 /// template, this function will return the same template arguments as
1806 /// getTemplateArgs(). For a class template specialization instantiated from
1807 /// a class template partial specialization, this function will return the
1808 /// deduced template arguments for the class template partial specialization
1809 /// itself.
1810 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1811 if (SpecializedPartialSpecialization *PartialSpec
1812 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1813 return *PartialSpec->TemplateArgs;
1814
1815 return getTemplateArgs();
1816 }
1817
1818 /// \brief Note that this class template specialization is actually an
1819 /// instantiation of the given class template partial specialization whose
1820 /// template arguments have been deduced.
1821 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1822 const TemplateArgumentList *TemplateArgs) {
1823 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1824, __extension__ __PRETTY_FUNCTION__))
1824 "Already set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1824, __extension__ __PRETTY_FUNCTION__))
;
1825 SpecializedPartialSpecialization *PS
13
'PS' initialized to a null pointer value
1826 = new (getASTContext()) SpecializedPartialSpecialization();
1827 PS->PartialSpecialization = PartialSpec;
14
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')
1828 PS->TemplateArgs = TemplateArgs;
1829 SpecializedTemplate = PS;
1830 }
1831
1832 /// \brief Note that this class template specialization is an instantiation
1833 /// of the given class template.
1834 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1835 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1836, __extension__ __PRETTY_FUNCTION__))
1836 "Previously set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1836, __extension__ __PRETTY_FUNCTION__))
;
1837 SpecializedTemplate = TemplDecl;
1838 }
1839
1840 /// \brief Sets the type of this specialization as it was written by
1841 /// the user. This will be a class template specialization type.
1842 void setTypeAsWritten(TypeSourceInfo *T) {
1843 if (!ExplicitInfo)
1844 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1845 ExplicitInfo->TypeAsWritten = T;
1846 }
1847
1848 /// \brief Gets the type of this specialization as it was written by
1849 /// the user, if it was so written.
1850 TypeSourceInfo *getTypeAsWritten() const {
1851 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1852 }
1853
1854 /// \brief Gets the location of the extern keyword, if present.
1855 SourceLocation getExternLoc() const {
1856 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1857 }
1858
1859 /// \brief Sets the location of the extern keyword.
1860 void setExternLoc(SourceLocation Loc) {
1861 if (!ExplicitInfo)
1862 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1863 ExplicitInfo->ExternLoc = Loc;
1864 }
1865
1866 /// \brief Sets the location of the template keyword.
1867 void setTemplateKeywordLoc(SourceLocation Loc) {
1868 if (!ExplicitInfo)
1869 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1870 ExplicitInfo->TemplateKeywordLoc = Loc;
1871 }
1872
1873 /// \brief Gets the location of the template keyword, if present.
1874 SourceLocation getTemplateKeywordLoc() const {
1875 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1876 }
1877
1878 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1879
1880 void Profile(llvm::FoldingSetNodeID &ID) const {
1881 Profile(ID, TemplateArgs->asArray(), getASTContext());
1882 }
1883
1884 static void
1885 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1886 ASTContext &Context) {
1887 ID.AddInteger(TemplateArgs.size());
1888 for (const TemplateArgument &TemplateArg : TemplateArgs)
1889 TemplateArg.Profile(ID, Context);
1890 }
1891
1892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1893
1894 static bool classofKind(Kind K) {
1895 return K >= firstClassTemplateSpecialization &&
1896 K <= lastClassTemplateSpecialization;
1897 }
1898};
1899
1900class ClassTemplatePartialSpecializationDecl
1901 : public ClassTemplateSpecializationDecl {
1902 /// \brief The list of template parameters
1903 TemplateParameterList* TemplateParams = nullptr;
1904
1905 /// \brief The source info for the template arguments as written.
1906 /// FIXME: redundant with TypeAsWritten?
1907 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1908
1909 /// \brief The class template partial specialization from which this
1910 /// class template partial specialization was instantiated.
1911 ///
1912 /// The boolean value will be true to indicate that this class template
1913 /// partial specialization was specialized at this level.
1914 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1915 InstantiatedFromMember;
1916
1917 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1918 DeclContext *DC,
1919 SourceLocation StartLoc,
1920 SourceLocation IdLoc,
1921 TemplateParameterList *Params,
1922 ClassTemplateDecl *SpecializedTemplate,
1923 ArrayRef<TemplateArgument> Args,
1924 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1925 ClassTemplatePartialSpecializationDecl *PrevDecl);
1926
1927 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1928 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1929 InstantiatedFromMember(nullptr, false) {}
1930
1931 void anchor() override;
1932
1933public:
1934 friend class ASTDeclReader;
1935 friend class ASTDeclWriter;
1936
1937 static ClassTemplatePartialSpecializationDecl *
1938 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1939 SourceLocation StartLoc, SourceLocation IdLoc,
1940 TemplateParameterList *Params,
1941 ClassTemplateDecl *SpecializedTemplate,
1942 ArrayRef<TemplateArgument> Args,
1943 const TemplateArgumentListInfo &ArgInfos,
1944 QualType CanonInjectedType,
1945 ClassTemplatePartialSpecializationDecl *PrevDecl);
1946
1947 static ClassTemplatePartialSpecializationDecl *
1948 CreateDeserialized(ASTContext &C, unsigned ID);
1949
1950 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1951 return cast<ClassTemplatePartialSpecializationDecl>(
1952 static_cast<ClassTemplateSpecializationDecl *>(
1953 this)->getMostRecentDecl());
1954 }
1955
1956 /// Get the list of template parameters
1957 TemplateParameterList *getTemplateParameters() const {
1958 return TemplateParams;
1959 }
1960
1961 /// Get the template arguments as written.
1962 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1963 return ArgsAsWritten;
1964 }
1965
1966 /// \brief Retrieve the member class template partial specialization from
1967 /// which this particular class template partial specialization was
1968 /// instantiated.
1969 ///
1970 /// \code
1971 /// template<typename T>
1972 /// struct Outer {
1973 /// template<typename U> struct Inner;
1974 /// template<typename U> struct Inner<U*> { }; // #1
1975 /// };
1976 ///
1977 /// Outer<float>::Inner<int*> ii;
1978 /// \endcode
1979 ///
1980 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1981 /// end up instantiating the partial specialization
1982 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1983 /// template partial specialization \c Outer<T>::Inner<U*>. Given
1984 /// \c Outer<float>::Inner<U*>, this function would return
1985 /// \c Outer<T>::Inner<U*>.
1986 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
1987 const ClassTemplatePartialSpecializationDecl *First =
1988 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1989 return First->InstantiatedFromMember.getPointer();
1990 }
1991 ClassTemplatePartialSpecializationDecl *
1992 getInstantiatedFromMemberTemplate() const {
1993 return getInstantiatedFromMember();
1994 }
1995
1996 void setInstantiatedFromMember(
1997 ClassTemplatePartialSpecializationDecl *PartialSpec) {
1998 ClassTemplatePartialSpecializationDecl *First =
1999 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2000 First->InstantiatedFromMember.setPointer(PartialSpec);
2001 }
2002
2003 /// \brief Determines whether this class template partial specialization
2004 /// template was a specialization of a member partial specialization.
2005 ///
2006 /// In the following example, the member template partial specialization
2007 /// \c X<int>::Inner<T*> is a member specialization.
2008 ///
2009 /// \code
2010 /// template<typename T>
2011 /// struct X {
2012 /// template<typename U> struct Inner;
2013 /// template<typename U> struct Inner<U*>;
2014 /// };
2015 ///
2016 /// template<> template<typename T>
2017 /// struct X<int>::Inner<T*> { /* ... */ };
2018 /// \endcode
2019 bool isMemberSpecialization() {
2020 ClassTemplatePartialSpecializationDecl *First =
2021 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2022 return First->InstantiatedFromMember.getInt();
2023 }
2024
2025 /// \brief Note that this member template is a specialization.
2026 void setMemberSpecialization() {
2027 ClassTemplatePartialSpecializationDecl *First =
2028 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2029 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
2030 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
;
2031 return First->InstantiatedFromMember.setInt(true);
2032 }
2033
2034 /// Retrieves the injected specialization type for this partial
2035 /// specialization. This is not the same as the type-decl-type for
2036 /// this partial specialization, which is an InjectedClassNameType.
2037 QualType getInjectedSpecializationType() const {
2038 assert(getTypeForDecl() && "partial specialization has no type set!")(static_cast <bool> (getTypeForDecl() && "partial specialization has no type set!"
) ? void (0) : __assert_fail ("getTypeForDecl() && \"partial specialization has no type set!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2038, __extension__ __PRETTY_FUNCTION__))
;
2039 return cast<InjectedClassNameType>(getTypeForDecl())
2040 ->getInjectedSpecializationType();
2041 }
2042
2043 // FIXME: Add Profile support!
2044
2045 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2046
2047 static bool classofKind(Kind K) {
2048 return K == ClassTemplatePartialSpecialization;
2049 }
2050};
2051
2052/// Declaration of a class template.
2053class ClassTemplateDecl : public RedeclarableTemplateDecl {
2054protected:
2055 /// \brief Data that is common to all of the declarations of a given
2056 /// class template.
2057 struct Common : CommonBase {
2058 /// \brief The class template specializations for this class
2059 /// template, including explicit specializations and instantiations.
2060 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2061
2062 /// \brief The class template partial specializations for this class
2063 /// template.
2064 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2065 PartialSpecializations;
2066
2067 /// \brief The injected-class-name type for this class template.
2068 QualType InjectedClassNameType;
2069
2070 Common() = default;
2071 };
2072
2073 /// \brief Retrieve the set of specializations of this class template.
2074 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2075 getSpecializations() const;
2076
2077 /// \brief Retrieve the set of partial specializations of this class
2078 /// template.
2079 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2080 getPartialSpecializations();
2081
2082 ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
2083 DeclContext *DC, SourceLocation L, DeclarationName Name,
2084 TemplateParameterList *Params, NamedDecl *Decl)
2085 : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
2086 Decl) {}
2087
2088 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2089 DeclarationName Name, TemplateParameterList *Params,
2090 NamedDecl *Decl)
2091 : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
2092
2093 CommonBase *newCommon(ASTContext &C) const override;
2094
2095 Common *getCommonPtr() const {
2096 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2097 }
2098
2099public:
2100 friend class ASTDeclReader;
2101 friend class ASTDeclWriter;
2102
2103 /// \brief Load any lazily-loaded specializations from the external source.
2104 void LoadLazySpecializations() const;
2105
2106 /// \brief Get the underlying class declarations of the template.
2107 CXXRecordDecl *getTemplatedDecl() const {
2108 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2109 }
2110
2111 /// \brief Returns whether this template declaration defines the primary
2112 /// class pattern.
2113 bool isThisDeclarationADefinition() const {
2114 return getTemplatedDecl()->isThisDeclarationADefinition();
2115 }
2116
2117 // FIXME: remove default argument for AssociatedConstraints
2118 /// \brief Create a class template node.
2119 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2120 SourceLocation L,
2121 DeclarationName Name,
2122 TemplateParameterList *Params,
2123 NamedDecl *Decl,
2124 Expr *AssociatedConstraints = nullptr);
2125
2126 /// \brief Create an empty class template node.
2127 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2128
2129 /// \brief Return the specialization with the provided arguments if it exists,
2130 /// otherwise return the insertion point.
2131 ClassTemplateSpecializationDecl *
2132 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2133
2134 /// \brief Insert the specified specialization knowing that it is not already
2135 /// in. InsertPos must be obtained from findSpecialization.
2136 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2137
2138 ClassTemplateDecl *getCanonicalDecl() override {
2139 return cast<ClassTemplateDecl>(
2140 RedeclarableTemplateDecl::getCanonicalDecl());
2141 }
2142 const ClassTemplateDecl *getCanonicalDecl() const {
2143 return cast<ClassTemplateDecl>(
2144 RedeclarableTemplateDecl::getCanonicalDecl());
2145 }
2146
2147 /// \brief Retrieve the previous declaration of this class template, or
2148 /// nullptr if no such declaration exists.
2149 ClassTemplateDecl *getPreviousDecl() {
2150 return cast_or_null<ClassTemplateDecl>(
2151 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2152 }
2153 const ClassTemplateDecl *getPreviousDecl() const {
2154 return cast_or_null<ClassTemplateDecl>(
2155 static_cast<const RedeclarableTemplateDecl *>(
2156 this)->getPreviousDecl());
2157 }
2158
2159 ClassTemplateDecl *getMostRecentDecl() {
2160 return cast<ClassTemplateDecl>(
2161 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2162 }
2163 const ClassTemplateDecl *getMostRecentDecl() const {
2164 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2165 }
2166
2167 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2168 return cast_or_null<ClassTemplateDecl>(
2169 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2170 }
2171
2172 /// \brief Return the partial specialization with the provided arguments if it
2173 /// exists, otherwise return the insertion point.
2174 ClassTemplatePartialSpecializationDecl *
2175 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2176
2177 /// \brief Insert the specified partial specialization knowing that it is not
2178 /// already in. InsertPos must be obtained from findPartialSpecialization.
2179 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2180 void *InsertPos);
2181
2182 /// \brief Retrieve the partial specializations as an ordered list.
2183 void getPartialSpecializations(
2184 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2185
2186 /// \brief Find a class template partial specialization with the given
2187 /// type T.
2188 ///
2189 /// \param T a dependent type that names a specialization of this class
2190 /// template.
2191 ///
2192 /// \returns the class template partial specialization that exactly matches
2193 /// the type \p T, or nullptr if no such partial specialization exists.
2194 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2195
2196 /// \brief Find a class template partial specialization which was instantiated
2197 /// from the given member partial specialization.
2198 ///
2199 /// \param D a member class template partial specialization.
2200 ///
2201 /// \returns the class template partial specialization which was instantiated
2202 /// from the given member partial specialization, or nullptr if no such
2203 /// partial specialization exists.
2204 ClassTemplatePartialSpecializationDecl *
2205 findPartialSpecInstantiatedFromMember(
2206 ClassTemplatePartialSpecializationDecl *D);
2207
2208 /// \brief Retrieve the template specialization type of the
2209 /// injected-class-name for this class template.
2210 ///
2211 /// The injected-class-name for a class template \c X is \c
2212 /// X<template-args>, where \c template-args is formed from the
2213 /// template arguments that correspond to the template parameters of
2214 /// \c X. For example:
2215 ///
2216 /// \code
2217 /// template<typename T, int N>
2218 /// struct array {
2219 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2220 /// };
2221 /// \endcode
2222 QualType getInjectedClassNameSpecialization();
2223
2224 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2225 using spec_range = llvm::iterator_range<spec_iterator>;
2226
2227 spec_range specializations() const {
2228 return spec_range(spec_begin(), spec_end());
2229 }
2230
2231 spec_iterator spec_begin() const {
2232 return makeSpecIterator(getSpecializations(), false);
2233 }
2234
2235 spec_iterator spec_end() const {
2236 return makeSpecIterator(getSpecializations(), true);
2237 }
2238
2239 // Implement isa/cast/dyncast support
2240 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2241 static bool classofKind(Kind K) { return K == ClassTemplate; }
2242};
2243
2244/// \brief Declaration of a friend template.
2245///
2246/// For example:
2247/// \code
2248/// template \<typename T> class A {
2249/// friend class MyVector<T>; // not a friend template
2250/// template \<typename U> friend class B; // not a friend template
2251/// template \<typename U> friend class Foo<T>::Nested; // friend template
2252/// };
2253/// \endcode
2254///
2255/// \note This class is not currently in use. All of the above
2256/// will yield a FriendDecl, not a FriendTemplateDecl.
2257class FriendTemplateDecl : public Decl {
2258 virtual void anchor();
2259
2260public:
2261 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2262
2263private:
2264 // The number of template parameters; always non-zero.
2265 unsigned NumParams = 0;
2266
2267 // The parameter list.
2268 TemplateParameterList **Params = nullptr;
2269
2270 // The declaration that's a friend of this class.
2271 FriendUnion Friend;
2272
2273 // Location of the 'friend' specifier.
2274 SourceLocation FriendLoc;
2275
2276 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2277 MutableArrayRef<TemplateParameterList *> Params,
2278 FriendUnion Friend, SourceLocation FriendLoc)
2279 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2280 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2281
2282 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2283
2284public:
2285 friend class ASTDeclReader;
2286
2287 static FriendTemplateDecl *
2288 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2289 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2290 SourceLocation FriendLoc);
2291
2292 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2293
2294 /// If this friend declaration names a templated type (or
2295 /// a dependent member type of a templated type), return that
2296 /// type; otherwise return null.
2297 TypeSourceInfo *getFriendType() const {
2298 return Friend.dyn_cast<TypeSourceInfo*>();
2299 }
2300
2301 /// If this friend declaration names a templated function (or
2302 /// a member function of a templated type), return that type;
2303 /// otherwise return null.
2304 NamedDecl *getFriendDecl() const {
2305 return Friend.dyn_cast<NamedDecl*>();
2306 }
2307
2308 /// \brief Retrieves the location of the 'friend' keyword.
2309 SourceLocation getFriendLoc() const {
2310 return FriendLoc;
2311 }
2312
2313 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2314 assert(i <= NumParams)(static_cast <bool> (i <= NumParams) ? void (0) : __assert_fail
("i <= NumParams", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2314, __extension__ __PRETTY_FUNCTION__))
;
2315 return Params[i];
2316 }
2317
2318 unsigned getNumTemplateParameters() const {
2319 return NumParams;
2320 }
2321
2322 // Implement isa/cast/dyncast/etc.
2323 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2324 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2325};
2326
2327/// \brief Declaration of an alias template.
2328///
2329/// For example:
2330/// \code
2331/// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2332/// \endcode
2333class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2334protected:
2335 using Common = CommonBase;
2336
2337 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2338 DeclarationName Name, TemplateParameterList *Params,
2339 NamedDecl *Decl)
2340 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2341 Decl) {}
2342
2343 CommonBase *newCommon(ASTContext &C) const override;
2344
2345 Common *getCommonPtr() {
2346 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2347 }
2348
2349public:
2350 friend class ASTDeclReader;
2351 friend class ASTDeclWriter;
2352
2353 /// Get the underlying function declaration of the template.
2354 TypeAliasDecl *getTemplatedDecl() const {
2355 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2356 }
2357
2358
2359 TypeAliasTemplateDecl *getCanonicalDecl() override {
2360 return cast<TypeAliasTemplateDecl>(
2361 RedeclarableTemplateDecl::getCanonicalDecl());
2362 }
2363 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2364 return cast<TypeAliasTemplateDecl>(
2365 RedeclarableTemplateDecl::getCanonicalDecl());
2366 }
2367
2368 /// \brief Retrieve the previous declaration of this function template, or
2369 /// nullptr if no such declaration exists.
2370 TypeAliasTemplateDecl *getPreviousDecl() {
2371 return cast_or_null<TypeAliasTemplateDecl>(
2372 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2373 }
2374 const TypeAliasTemplateDecl *getPreviousDecl() const {
2375 return cast_or_null<TypeAliasTemplateDecl>(
2376 static_cast<const RedeclarableTemplateDecl *>(
2377 this)->getPreviousDecl());
2378 }
2379
2380 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2381 return cast_or_null<TypeAliasTemplateDecl>(
2382 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2383 }
2384
2385 /// \brief Create a function template node.
2386 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2387 SourceLocation L,
2388 DeclarationName Name,
2389 TemplateParameterList *Params,
2390 NamedDecl *Decl);
2391
2392 /// \brief Create an empty alias template node.
2393 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2394
2395 // Implement isa/cast/dyncast support
2396 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2397 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2398};
2399
2400/// \brief Declaration of a function specialization at template class scope.
2401///
2402/// This is a non-standard extension needed to support MSVC.
2403///
2404/// For example:
2405/// \code
2406/// template <class T>
2407/// class A {
2408/// template <class U> void foo(U a) { }
2409/// template<> void foo(int a) { }
2410/// }
2411/// \endcode
2412///
2413/// "template<> foo(int a)" will be saved in Specialization as a normal
2414/// CXXMethodDecl. Then during an instantiation of class A, it will be
2415/// transformed into an actual function specialization.
2416class ClassScopeFunctionSpecializationDecl : public Decl {
2417 CXXMethodDecl *Specialization;
2418 bool HasExplicitTemplateArgs;
2419 TemplateArgumentListInfo TemplateArgs;
2420
2421 ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2422 CXXMethodDecl *FD, bool Args,
2423 TemplateArgumentListInfo TemplArgs)
2424 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2425 Specialization(FD), HasExplicitTemplateArgs(Args),
2426 TemplateArgs(std::move(TemplArgs)) {}
2427
2428 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2429 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2430
2431 virtual void anchor();
2432
2433public:
2434 friend class ASTDeclReader;
2435 friend class ASTDeclWriter;
2436
2437 CXXMethodDecl *getSpecialization() const { return Specialization; }
2438 bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
2439 const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
2440
2441 static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2442 DeclContext *DC,
2443 SourceLocation Loc,
2444 CXXMethodDecl *FD,
2445 bool HasExplicitTemplateArgs,
2446 TemplateArgumentListInfo TemplateArgs) {
2447 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2448 DC, Loc, FD, HasExplicitTemplateArgs, std::move(TemplateArgs));
2449 }
2450
2451 static ClassScopeFunctionSpecializationDecl *
2452 CreateDeserialized(ASTContext &Context, unsigned ID);
2453
2454 // Implement isa/cast/dyncast/etc.
2455 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2456
2457 static bool classofKind(Kind K) {
2458 return K == Decl::ClassScopeFunctionSpecialization;
2459 }
2460};
2461
2462/// Implementation of inline functions that require the template declarations
2463inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2464 : Function(FTD) {}
2465
2466/// \brief Represents a variable template specialization, which refers to
2467/// a variable template with a given set of template arguments.
2468///
2469/// Variable template specializations represent both explicit
2470/// specializations of variable templates, as in the example below, and
2471/// implicit instantiations of variable templates.
2472///
2473/// \code
2474/// template<typename T> constexpr T pi = T(3.1415926535897932385);
2475///
2476/// template<>
2477/// constexpr float pi<float>; // variable template specialization pi<float>
2478/// \endcode
2479class VarTemplateSpecializationDecl : public VarDecl,
2480 public llvm::FoldingSetNode {
2481
2482 /// \brief Structure that stores information about a variable template
2483 /// specialization that was instantiated from a variable template partial
2484 /// specialization.
2485 struct SpecializedPartialSpecialization {
2486 /// \brief The variable template partial specialization from which this
2487 /// variable template specialization was instantiated.
2488 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2489
2490 /// \brief The template argument list deduced for the variable template
2491 /// partial specialization itself.
2492 const TemplateArgumentList *TemplateArgs;
2493 };
2494
2495 /// \brief The template that this specialization specializes.
2496 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2497 SpecializedTemplate;
2498
2499 /// \brief Further info for explicit template specialization/instantiation.
2500 struct ExplicitSpecializationInfo {
2501 /// \brief The type-as-written.
2502 TypeSourceInfo *TypeAsWritten = nullptr;
2503
2504 /// \brief The location of the extern keyword.
2505 SourceLocation ExternLoc;
2506
2507 /// \brief The location of the template keyword.
2508 SourceLocation TemplateKeywordLoc;
2509
2510 ExplicitSpecializationInfo() = default;
2511 };
2512
2513 /// \brief Further info for explicit template specialization/instantiation.
2514 /// Does not apply to implicit specializations.
2515 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2516
2517 /// \brief The template arguments used to describe this specialization.
2518 const TemplateArgumentList *TemplateArgs;
2519 TemplateArgumentListInfo TemplateArgsInfo;
2520
2521 /// \brief The point where this template was instantiated (if any).
2522 SourceLocation PointOfInstantiation;
2523
2524 /// \brief The kind of specialization this declaration refers to.
2525 /// Really a value of type TemplateSpecializationKind.
2526 unsigned SpecializationKind : 3;
2527
2528 /// \brief Whether this declaration is a complete definition of the
2529 /// variable template specialization. We can't otherwise tell apart
2530 /// an instantiated declaration from an instantiated definition with
2531 /// no initializer.
2532 unsigned IsCompleteDefinition : 1;
2533
2534protected:
2535 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2536 SourceLocation StartLoc, SourceLocation IdLoc,
2537 VarTemplateDecl *SpecializedTemplate,
2538 QualType T, TypeSourceInfo *TInfo,
2539 StorageClass S,
2540 ArrayRef<TemplateArgument> Args);
2541
2542 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2543
2544public:
2545 friend class ASTDeclReader;
2546 friend class ASTDeclWriter;
2547 friend class VarDecl;
2548
2549 static VarTemplateSpecializationDecl *
2550 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2551 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2552 TypeSourceInfo *TInfo, StorageClass S,
2553 ArrayRef<TemplateArgument> Args);
2554 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2555 unsigned ID);
2556
2557 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2558 bool Qualified) const override;
2559
2560 VarTemplateSpecializationDecl *getMostRecentDecl() {
2561 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2562 return cast<VarTemplateSpecializationDecl>(Recent);
2563 }
2564
2565 /// \brief Retrieve the template that this specialization specializes.
2566 VarTemplateDecl *getSpecializedTemplate() const;
2567
2568 /// \brief Retrieve the template arguments of the variable template
2569 /// specialization.
2570 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2571
2572 // TODO: Always set this when creating the new specialization?
2573 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2574
2575 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2576 return TemplateArgsInfo;
2577 }
2578
2579 /// \brief Determine the kind of specialization that this
2580 /// declaration represents.
2581 TemplateSpecializationKind getSpecializationKind() const {
2582 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2583 }
2584
2585 bool isExplicitSpecialization() const {
2586 return getSpecializationKind() == TSK_ExplicitSpecialization;
2587 }
2588
2589 /// \brief True if this declaration is an explicit specialization,
2590 /// explicit instantiation declaration, or explicit instantiation
2591 /// definition.
2592 bool isExplicitInstantiationOrSpecialization() const {
2593 return isTemplateExplicitInstantiationOrSpecialization(
2594 getTemplateSpecializationKind());
2595 }
2596
2597 void setSpecializationKind(TemplateSpecializationKind TSK) {
2598 SpecializationKind = TSK;
2599 }
2600
2601 /// \brief Get the point of instantiation (if any), or null if none.
2602 SourceLocation getPointOfInstantiation() const {
2603 return PointOfInstantiation;
2604 }
2605
2606 void setPointOfInstantiation(SourceLocation Loc) {
2607 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2607, __extension__ __PRETTY_FUNCTION__))
;
2608 PointOfInstantiation = Loc;
2609 }
2610
2611 void setCompleteDefinition() { IsCompleteDefinition = true; }
2612
2613 /// \brief If this variable template specialization is an instantiation of
2614 /// a template (rather than an explicit specialization), return the
2615 /// variable template or variable template partial specialization from which
2616 /// it was instantiated.
2617 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2618 getInstantiatedFrom() const {
2619 if (!isTemplateInstantiation(getSpecializationKind()))
2620 return llvm::PointerUnion<VarTemplateDecl *,
2621 VarTemplatePartialSpecializationDecl *>();
2622
2623 return getSpecializedTemplateOrPartial();
2624 }
2625
2626 /// \brief Retrieve the variable template or variable template partial
2627 /// specialization which was specialized by this.
2628 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2629 getSpecializedTemplateOrPartial() const {
2630 if (SpecializedPartialSpecialization *PartialSpec =
2631 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2632 return PartialSpec->PartialSpecialization;
2633
2634 return SpecializedTemplate.get<VarTemplateDecl *>();
2635 }
2636
2637 /// \brief Retrieve the set of template arguments that should be used
2638 /// to instantiate the initializer of the variable template or variable
2639 /// template partial specialization from which this variable template
2640 /// specialization was instantiated.
2641 ///
2642 /// \returns For a variable template specialization instantiated from the
2643 /// primary template, this function will return the same template arguments
2644 /// as getTemplateArgs(). For a variable template specialization instantiated
2645 /// from a variable template partial specialization, this function will the
2646 /// return deduced template arguments for the variable template partial
2647 /// specialization itself.
2648 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2649 if (SpecializedPartialSpecialization *PartialSpec =
2650 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2651 return *PartialSpec->TemplateArgs;
2652
2653 return getTemplateArgs();
2654 }
2655
2656 /// \brief Note that this variable template specialization is actually an
2657 /// instantiation of the given variable template partial specialization whose
2658 /// template arguments have been deduced.
2659 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2660 const TemplateArgumentList *TemplateArgs) {
2661 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
2662 "Already set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
;
2663 SpecializedPartialSpecialization *PS =
2664 new (getASTContext()) SpecializedPartialSpecialization();
2665 PS->PartialSpecialization = PartialSpec;
2666 PS->TemplateArgs = TemplateArgs;
2667 SpecializedTemplate = PS;
2668 }
2669
2670 /// \brief Note that this variable template specialization is an instantiation
2671 /// of the given variable template.
2672 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2673 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
2674 "Previously set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
;
2675 SpecializedTemplate = TemplDecl;
2676 }
2677
2678 /// \brief Sets the type of this specialization as it was written by
2679 /// the user.
2680 void setTypeAsWritten(TypeSourceInfo *T) {
2681 if (!ExplicitInfo)
2682 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2683 ExplicitInfo->TypeAsWritten = T;
2684 }
2685
2686 /// \brief Gets the type of this specialization as it was written by
2687 /// the user, if it was so written.
2688 TypeSourceInfo *getTypeAsWritten() const {
2689 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2690 }
2691
2692 /// \brief Gets the location of the extern keyword, if present.
2693 SourceLocation getExternLoc() const {
2694 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2695 }
2696
2697 /// \brief Sets the location of the extern keyword.
2698 void setExternLoc(SourceLocation Loc) {
2699 if (!ExplicitInfo)
2700 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2701 ExplicitInfo->ExternLoc = Loc;
2702 }
2703
2704 /// \brief Sets the location of the template keyword.
2705 void setTemplateKeywordLoc(SourceLocation Loc) {
2706 if (!ExplicitInfo)
2707 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2708 ExplicitInfo->TemplateKeywordLoc = Loc;
2709 }
2710
2711 /// \brief Gets the location of the template keyword, if present.
2712 SourceLocation getTemplateKeywordLoc() const {
2713 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2714 }
2715
2716 void Profile(llvm::FoldingSetNodeID &ID) const {
2717 Profile(ID, TemplateArgs->asArray(), getASTContext());
2718 }
2719
2720 static void Profile(llvm::FoldingSetNodeID &ID,
2721 ArrayRef<TemplateArgument> TemplateArgs,
2722 ASTContext &Context) {
2723 ID.AddInteger(TemplateArgs.size());
2724 for (const TemplateArgument &TemplateArg : TemplateArgs)
2725 TemplateArg.Profile(ID, Context);
2726 }
2727
2728 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2729
2730 static bool classofKind(Kind K) {
2731 return K >= firstVarTemplateSpecialization &&
2732 K <= lastVarTemplateSpecialization;
2733 }
2734};
2735
2736class VarTemplatePartialSpecializationDecl
2737 : public VarTemplateSpecializationDecl {
2738 /// \brief The list of template parameters
2739 TemplateParameterList *TemplateParams = nullptr;
2740
2741 /// \brief The source info for the template arguments as written.
2742 /// FIXME: redundant with TypeAsWritten?
2743 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2744
2745 /// \brief The variable template partial specialization from which this
2746 /// variable template partial specialization was instantiated.
2747 ///
2748 /// The boolean value will be true to indicate that this variable template
2749 /// partial specialization was specialized at this level.
2750 llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2751 InstantiatedFromMember;
2752
2753 VarTemplatePartialSpecializationDecl(
2754 ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2755 SourceLocation IdLoc, TemplateParameterList *Params,
2756 VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2757 StorageClass S, ArrayRef<TemplateArgument> Args,
2758 const ASTTemplateArgumentListInfo *ArgInfos);
2759
2760 VarTemplatePartialSpecializationDecl(ASTContext &Context)
2761 : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2762 Context),
2763 InstantiatedFromMember(nullptr, false) {}
2764
2765 void anchor() override;
2766
2767public:
2768 friend class ASTDeclReader;
2769 friend class ASTDeclWriter;
2770
2771 static VarTemplatePartialSpecializationDecl *
2772 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2773 SourceLocation IdLoc, TemplateParameterList *Params,
2774 VarTemplateDecl *SpecializedTemplate, QualType T,
2775 TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
2776 const TemplateArgumentListInfo &ArgInfos);
2777
2778 static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2779 unsigned ID);
2780