Bug Summary

File:clang/lib/Sema/TreeTransform.h
Warning:line 5607, column 24
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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-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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-08-06-171148-17323-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/TreeTransform.h

1//===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements a semantic tree transformation that takes a given
9// AST and rebuilds it, possibly transforming some nodes in the process.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14#define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15
16#include "CoroutineStmtBuilder.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprConcepts.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/OpenMPClause.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/StmtOpenMP.h"
31#include "clang/Basic/OpenMPKinds.h"
32#include "clang/Sema/Designator.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/Ownership.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/SemaDiagnostic.h"
38#include "clang/Sema/SemaInternal.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/Support/ErrorHandling.h"
41#include <algorithm>
42
43using namespace llvm::omp;
44
45namespace clang {
46using namespace sema;
47
48/// A semantic tree transformation that allows one to transform one
49/// abstract syntax tree into another.
50///
51/// A new tree transformation is defined by creating a new subclass \c X of
52/// \c TreeTransform<X> and then overriding certain operations to provide
53/// behavior specific to that transformation. For example, template
54/// instantiation is implemented as a tree transformation where the
55/// transformation of TemplateTypeParmType nodes involves substituting the
56/// template arguments for their corresponding template parameters; a similar
57/// transformation is performed for non-type template parameters and
58/// template template parameters.
59///
60/// This tree-transformation template uses static polymorphism to allow
61/// subclasses to customize any of its operations. Thus, a subclass can
62/// override any of the transformation or rebuild operators by providing an
63/// operation with the same signature as the default implementation. The
64/// overriding function should not be virtual.
65///
66/// Semantic tree transformations are split into two stages, either of which
67/// can be replaced by a subclass. The "transform" step transforms an AST node
68/// or the parts of an AST node using the various transformation functions,
69/// then passes the pieces on to the "rebuild" step, which constructs a new AST
70/// node of the appropriate kind from the pieces. The default transformation
71/// routines recursively transform the operands to composite AST nodes (e.g.,
72/// the pointee type of a PointerType node) and, if any of those operand nodes
73/// were changed by the transformation, invokes the rebuild operation to create
74/// a new AST node.
75///
76/// Subclasses can customize the transformation at various levels. The
77/// most coarse-grained transformations involve replacing TransformType(),
78/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
79/// TransformTemplateName(), or TransformTemplateArgument() with entirely
80/// new implementations.
81///
82/// For more fine-grained transformations, subclasses can replace any of the
83/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
84/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
85/// replacing TransformTemplateTypeParmType() allows template instantiation
86/// to substitute template arguments for their corresponding template
87/// parameters. Additionally, subclasses can override the \c RebuildXXX
88/// functions to control how AST nodes are rebuilt when their operands change.
89/// By default, \c TreeTransform will invoke semantic analysis to rebuild
90/// AST nodes. However, certain other tree transformations (e.g, cloning) may
91/// be able to use more efficient rebuild steps.
92///
93/// There are a handful of other functions that can be overridden, allowing one
94/// to avoid traversing nodes that don't need any transformation
95/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
96/// operands have not changed (\c AlwaysRebuild()), and customize the
97/// default locations and entity names used for type-checking
98/// (\c getBaseLocation(), \c getBaseEntity()).
99template<typename Derived>
100class TreeTransform {
101 /// Private RAII object that helps us forget and then re-remember
102 /// the template argument corresponding to a partially-substituted parameter
103 /// pack.
104 class ForgetPartiallySubstitutedPackRAII {
105 Derived &Self;
106 TemplateArgument Old;
107
108 public:
109 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
110 Old = Self.ForgetPartiallySubstitutedPack();
111 }
112
113 ~ForgetPartiallySubstitutedPackRAII() {
114 Self.RememberPartiallySubstitutedPack(Old);
115 }
116 };
117
118protected:
119 Sema &SemaRef;
120
121 /// The set of local declarations that have been transformed, for
122 /// cases where we are forced to build new declarations within the transformer
123 /// rather than in the subclass (e.g., lambda closure types).
124 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
125
126public:
127 /// Initializes a new tree transformer.
128 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
129
130 /// Retrieves a reference to the derived class.
131 Derived &getDerived() { return static_cast<Derived&>(*this); }
132
133 /// Retrieves a reference to the derived class.
134 const Derived &getDerived() const {
135 return static_cast<const Derived&>(*this);
136 }
137
138 static inline ExprResult Owned(Expr *E) { return E; }
139 static inline StmtResult Owned(Stmt *S) { return S; }
140
141 /// Retrieves a reference to the semantic analysis object used for
142 /// this tree transform.
143 Sema &getSema() const { return SemaRef; }
144
145 /// Whether the transformation should always rebuild AST nodes, even
146 /// if none of the children have changed.
147 ///
148 /// Subclasses may override this function to specify when the transformation
149 /// should rebuild all AST nodes.
150 ///
151 /// We must always rebuild all AST nodes when performing variadic template
152 /// pack expansion, in order to avoid violating the AST invariant that each
153 /// statement node appears at most once in its containing declaration.
154 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
155
156 /// Whether the transformation is forming an expression or statement that
157 /// replaces the original. In this case, we'll reuse mangling numbers from
158 /// existing lambdas.
159 bool ReplacingOriginal() { return false; }
160
161 /// Wether CXXConstructExpr can be skipped when they are implicit.
162 /// They will be reconstructed when used if needed.
163 /// This is usefull when the user that cause rebuilding of the
164 /// CXXConstructExpr is outside of the expression at which the TreeTransform
165 /// started.
166 bool AllowSkippingCXXConstructExpr() { return true; }
167
168 /// Returns the location of the entity being transformed, if that
169 /// information was not available elsewhere in the AST.
170 ///
171 /// By default, returns no source-location information. Subclasses can
172 /// provide an alternative implementation that provides better location
173 /// information.
174 SourceLocation getBaseLocation() { return SourceLocation(); }
175
176 /// Returns the name of the entity being transformed, if that
177 /// information was not available elsewhere in the AST.
178 ///
179 /// By default, returns an empty name. Subclasses can provide an alternative
180 /// implementation with a more precise name.
181 DeclarationName getBaseEntity() { return DeclarationName(); }
182
183 /// Sets the "base" location and entity when that
184 /// information is known based on another transformation.
185 ///
186 /// By default, the source location and entity are ignored. Subclasses can
187 /// override this function to provide a customized implementation.
188 void setBase(SourceLocation Loc, DeclarationName Entity) { }
189
190 /// RAII object that temporarily sets the base location and entity
191 /// used for reporting diagnostics in types.
192 class TemporaryBase {
193 TreeTransform &Self;
194 SourceLocation OldLocation;
195 DeclarationName OldEntity;
196
197 public:
198 TemporaryBase(TreeTransform &Self, SourceLocation Location,
199 DeclarationName Entity) : Self(Self) {
200 OldLocation = Self.getDerived().getBaseLocation();
201 OldEntity = Self.getDerived().getBaseEntity();
202
203 if (Location.isValid())
204 Self.getDerived().setBase(Location, Entity);
205 }
206
207 ~TemporaryBase() {
208 Self.getDerived().setBase(OldLocation, OldEntity);
209 }
210 };
211
212 /// Determine whether the given type \p T has already been
213 /// transformed.
214 ///
215 /// Subclasses can provide an alternative implementation of this routine
216 /// to short-circuit evaluation when it is known that a given type will
217 /// not change. For example, template instantiation need not traverse
218 /// non-dependent types.
219 bool AlreadyTransformed(QualType T) {
220 return T.isNull();
221 }
222
223 /// Transform a template parameter depth level.
224 ///
225 /// During a transformation that transforms template parameters, this maps
226 /// an old template parameter depth to a new depth.
227 unsigned TransformTemplateDepth(unsigned Depth) {
228 return Depth;
229 }
230
231 /// Determine whether the given call argument should be dropped, e.g.,
232 /// because it is a default argument.
233 ///
234 /// Subclasses can provide an alternative implementation of this routine to
235 /// determine which kinds of call arguments get dropped. By default,
236 /// CXXDefaultArgument nodes are dropped (prior to transformation).
237 bool DropCallArgument(Expr *E) {
238 return E->isDefaultArgument();
239 }
240
241 /// Determine whether we should expand a pack expansion with the
242 /// given set of parameter packs into separate arguments by repeatedly
243 /// transforming the pattern.
244 ///
245 /// By default, the transformer never tries to expand pack expansions.
246 /// Subclasses can override this routine to provide different behavior.
247 ///
248 /// \param EllipsisLoc The location of the ellipsis that identifies the
249 /// pack expansion.
250 ///
251 /// \param PatternRange The source range that covers the entire pattern of
252 /// the pack expansion.
253 ///
254 /// \param Unexpanded The set of unexpanded parameter packs within the
255 /// pattern.
256 ///
257 /// \param ShouldExpand Will be set to \c true if the transformer should
258 /// expand the corresponding pack expansions into separate arguments. When
259 /// set, \c NumExpansions must also be set.
260 ///
261 /// \param RetainExpansion Whether the caller should add an unexpanded
262 /// pack expansion after all of the expanded arguments. This is used
263 /// when extending explicitly-specified template argument packs per
264 /// C++0x [temp.arg.explicit]p9.
265 ///
266 /// \param NumExpansions The number of separate arguments that will be in
267 /// the expanded form of the corresponding pack expansion. This is both an
268 /// input and an output parameter, which can be set by the caller if the
269 /// number of expansions is known a priori (e.g., due to a prior substitution)
270 /// and will be set by the callee when the number of expansions is known.
271 /// The callee must set this value when \c ShouldExpand is \c true; it may
272 /// set this value in other cases.
273 ///
274 /// \returns true if an error occurred (e.g., because the parameter packs
275 /// are to be instantiated with arguments of different lengths), false
276 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
277 /// must be set.
278 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
279 SourceRange PatternRange,
280 ArrayRef<UnexpandedParameterPack> Unexpanded,
281 bool &ShouldExpand,
282 bool &RetainExpansion,
283 Optional<unsigned> &NumExpansions) {
284 ShouldExpand = false;
285 return false;
286 }
287
288 /// "Forget" about the partially-substituted pack template argument,
289 /// when performing an instantiation that must preserve the parameter pack
290 /// use.
291 ///
292 /// This routine is meant to be overridden by the template instantiator.
293 TemplateArgument ForgetPartiallySubstitutedPack() {
294 return TemplateArgument();
295 }
296
297 /// "Remember" the partially-substituted pack template argument
298 /// after performing an instantiation that must preserve the parameter pack
299 /// use.
300 ///
301 /// This routine is meant to be overridden by the template instantiator.
302 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
303
304 /// Note to the derived class when a function parameter pack is
305 /// being expanded.
306 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
307
308 /// Transforms the given type into another type.
309 ///
310 /// By default, this routine transforms a type by creating a
311 /// TypeSourceInfo for it and delegating to the appropriate
312 /// function. This is expensive, but we don't mind, because
313 /// this method is deprecated anyway; all users should be
314 /// switched to storing TypeSourceInfos.
315 ///
316 /// \returns the transformed type.
317 QualType TransformType(QualType T);
318
319 /// Transforms the given type-with-location into a new
320 /// type-with-location.
321 ///
322 /// By default, this routine transforms a type by delegating to the
323 /// appropriate TransformXXXType to build a new type. Subclasses
324 /// may override this function (to take over all type
325 /// transformations) or some set of the TransformXXXType functions
326 /// to alter the transformation.
327 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
328
329 /// Transform the given type-with-location into a new
330 /// type, collecting location information in the given builder
331 /// as necessary.
332 ///
333 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
334
335 /// Transform a type that is permitted to produce a
336 /// DeducedTemplateSpecializationType.
337 ///
338 /// This is used in the (relatively rare) contexts where it is acceptable
339 /// for transformation to produce a class template type with deduced
340 /// template arguments.
341 /// @{
342 QualType TransformTypeWithDeducedTST(QualType T);
343 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
344 /// @}
345
346 /// The reason why the value of a statement is not discarded, if any.
347 enum StmtDiscardKind {
348 SDK_Discarded,
349 SDK_NotDiscarded,
350 SDK_StmtExprResult,
351 };
352
353 /// Transform the given statement.
354 ///
355 /// By default, this routine transforms a statement by delegating to the
356 /// appropriate TransformXXXStmt function to transform a specific kind of
357 /// statement or the TransformExpr() function to transform an expression.
358 /// Subclasses may override this function to transform statements using some
359 /// other mechanism.
360 ///
361 /// \returns the transformed statement.
362 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
363
364 /// Transform the given statement.
365 ///
366 /// By default, this routine transforms a statement by delegating to the
367 /// appropriate TransformOMPXXXClause function to transform a specific kind
368 /// of clause. Subclasses may override this function to transform statements
369 /// using some other mechanism.
370 ///
371 /// \returns the transformed OpenMP clause.
372 OMPClause *TransformOMPClause(OMPClause *S);
373
374 /// Transform the given attribute.
375 ///
376 /// By default, this routine transforms a statement by delegating to the
377 /// appropriate TransformXXXAttr function to transform a specific kind
378 /// of attribute. Subclasses may override this function to transform
379 /// attributed statements using some other mechanism.
380 ///
381 /// \returns the transformed attribute
382 const Attr *TransformAttr(const Attr *S);
383
384/// Transform the specified attribute.
385///
386/// Subclasses should override the transformation of attributes with a pragma
387/// spelling to transform expressions stored within the attribute.
388///
389/// \returns the transformed attribute.
390#define ATTR(X)
391#define PRAGMA_SPELLING_ATTR(X) \
392 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
393#include "clang/Basic/AttrList.inc"
394
395 /// Transform the given expression.
396 ///
397 /// By default, this routine transforms an expression by delegating to the
398 /// appropriate TransformXXXExpr function to build a new expression.
399 /// Subclasses may override this function to transform expressions using some
400 /// other mechanism.
401 ///
402 /// \returns the transformed expression.
403 ExprResult TransformExpr(Expr *E);
404
405 /// Transform the given initializer.
406 ///
407 /// By default, this routine transforms an initializer by stripping off the
408 /// semantic nodes added by initialization, then passing the result to
409 /// TransformExpr or TransformExprs.
410 ///
411 /// \returns the transformed initializer.
412 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
413
414 /// Transform the given list of expressions.
415 ///
416 /// This routine transforms a list of expressions by invoking
417 /// \c TransformExpr() for each subexpression. However, it also provides
418 /// support for variadic templates by expanding any pack expansions (if the
419 /// derived class permits such expansion) along the way. When pack expansions
420 /// are present, the number of outputs may not equal the number of inputs.
421 ///
422 /// \param Inputs The set of expressions to be transformed.
423 ///
424 /// \param NumInputs The number of expressions in \c Inputs.
425 ///
426 /// \param IsCall If \c true, then this transform is being performed on
427 /// function-call arguments, and any arguments that should be dropped, will
428 /// be.
429 ///
430 /// \param Outputs The transformed input expressions will be added to this
431 /// vector.
432 ///
433 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
434 /// due to transformation.
435 ///
436 /// \returns true if an error occurred, false otherwise.
437 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
438 SmallVectorImpl<Expr *> &Outputs,
439 bool *ArgChanged = nullptr);
440
441 /// Transform the given declaration, which is referenced from a type
442 /// or expression.
443 ///
444 /// By default, acts as the identity function on declarations, unless the
445 /// transformer has had to transform the declaration itself. Subclasses
446 /// may override this function to provide alternate behavior.
447 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
448 llvm::DenseMap<Decl *, Decl *>::iterator Known
449 = TransformedLocalDecls.find(D);
450 if (Known != TransformedLocalDecls.end())
451 return Known->second;
452
453 return D;
454 }
455
456 /// Transform the specified condition.
457 ///
458 /// By default, this transforms the variable and expression and rebuilds
459 /// the condition.
460 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
461 Expr *Expr,
462 Sema::ConditionKind Kind);
463
464 /// Transform the attributes associated with the given declaration and
465 /// place them on the new declaration.
466 ///
467 /// By default, this operation does nothing. Subclasses may override this
468 /// behavior to transform attributes.
469 void transformAttrs(Decl *Old, Decl *New) { }
470
471 /// Note that a local declaration has been transformed by this
472 /// transformer.
473 ///
474 /// Local declarations are typically transformed via a call to
475 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
476 /// the transformer itself has to transform the declarations. This routine
477 /// can be overridden by a subclass that keeps track of such mappings.
478 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
479 assert(New.size() == 1 &&((New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? static_cast<void> (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/TreeTransform.h"
, 480, __PRETTY_FUNCTION__))
480 "must override transformedLocalDecl if performing pack expansion")((New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? static_cast<void> (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/TreeTransform.h"
, 480, __PRETTY_FUNCTION__))
;
481 TransformedLocalDecls[Old] = New.front();
482 }
483
484 /// Transform the definition of the given declaration.
485 ///
486 /// By default, invokes TransformDecl() to transform the declaration.
487 /// Subclasses may override this function to provide alternate behavior.
488 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
489 return getDerived().TransformDecl(Loc, D);
490 }
491
492 /// Transform the given declaration, which was the first part of a
493 /// nested-name-specifier in a member access expression.
494 ///
495 /// This specific declaration transformation only applies to the first
496 /// identifier in a nested-name-specifier of a member access expression, e.g.,
497 /// the \c T in \c x->T::member
498 ///
499 /// By default, invokes TransformDecl() to transform the declaration.
500 /// Subclasses may override this function to provide alternate behavior.
501 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
502 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
503 }
504
505 /// Transform the set of declarations in an OverloadExpr.
506 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
507 LookupResult &R);
508
509 /// Transform the given nested-name-specifier with source-location
510 /// information.
511 ///
512 /// By default, transforms all of the types and declarations within the
513 /// nested-name-specifier. Subclasses may override this function to provide
514 /// alternate behavior.
515 NestedNameSpecifierLoc
516 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
517 QualType ObjectType = QualType(),
518 NamedDecl *FirstQualifierInScope = nullptr);
519
520 /// Transform the given declaration name.
521 ///
522 /// By default, transforms the types of conversion function, constructor,
523 /// and destructor names and then (if needed) rebuilds the declaration name.
524 /// Identifiers and selectors are returned unmodified. Sublcasses may
525 /// override this function to provide alternate behavior.
526 DeclarationNameInfo
527 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
528
529 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
530 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
531 concepts::TypeRequirement *
532 TransformTypeRequirement(concepts::TypeRequirement *Req);
533 concepts::ExprRequirement *
534 TransformExprRequirement(concepts::ExprRequirement *Req);
535 concepts::NestedRequirement *
536 TransformNestedRequirement(concepts::NestedRequirement *Req);
537
538 /// Transform the given template name.
539 ///
540 /// \param SS The nested-name-specifier that qualifies the template
541 /// name. This nested-name-specifier must already have been transformed.
542 ///
543 /// \param Name The template name to transform.
544 ///
545 /// \param NameLoc The source location of the template name.
546 ///
547 /// \param ObjectType If we're translating a template name within a member
548 /// access expression, this is the type of the object whose member template
549 /// is being referenced.
550 ///
551 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
552 /// also refers to a name within the current (lexical) scope, this is the
553 /// declaration it refers to.
554 ///
555 /// By default, transforms the template name by transforming the declarations
556 /// and nested-name-specifiers that occur within the template name.
557 /// Subclasses may override this function to provide alternate behavior.
558 TemplateName
559 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
560 SourceLocation NameLoc,
561 QualType ObjectType = QualType(),
562 NamedDecl *FirstQualifierInScope = nullptr,
563 bool AllowInjectedClassName = false);
564
565 /// Transform the given template argument.
566 ///
567 /// By default, this operation transforms the type, expression, or
568 /// declaration stored within the template argument and constructs a
569 /// new template argument from the transformed result. Subclasses may
570 /// override this function to provide alternate behavior.
571 ///
572 /// Returns true if there was an error.
573 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
574 TemplateArgumentLoc &Output,
575 bool Uneval = false);
576
577 /// Transform the given set of template arguments.
578 ///
579 /// By default, this operation transforms all of the template arguments
580 /// in the input set using \c TransformTemplateArgument(), and appends
581 /// the transformed arguments to the output list.
582 ///
583 /// Note that this overload of \c TransformTemplateArguments() is merely
584 /// a convenience function. Subclasses that wish to override this behavior
585 /// should override the iterator-based member template version.
586 ///
587 /// \param Inputs The set of template arguments to be transformed.
588 ///
589 /// \param NumInputs The number of template arguments in \p Inputs.
590 ///
591 /// \param Outputs The set of transformed template arguments output by this
592 /// routine.
593 ///
594 /// Returns true if an error occurred.
595 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
596 unsigned NumInputs,
597 TemplateArgumentListInfo &Outputs,
598 bool Uneval = false) {
599 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
600 Uneval);
601 }
602
603 /// Transform the given set of template arguments.
604 ///
605 /// By default, this operation transforms all of the template arguments
606 /// in the input set using \c TransformTemplateArgument(), and appends
607 /// the transformed arguments to the output list.
608 ///
609 /// \param First An iterator to the first template argument.
610 ///
611 /// \param Last An iterator one step past the last template argument.
612 ///
613 /// \param Outputs The set of transformed template arguments output by this
614 /// routine.
615 ///
616 /// Returns true if an error occurred.
617 template<typename InputIterator>
618 bool TransformTemplateArguments(InputIterator First,
619 InputIterator Last,
620 TemplateArgumentListInfo &Outputs,
621 bool Uneval = false);
622
623 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
624 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
625 TemplateArgumentLoc &ArgLoc);
626
627 /// Fakes up a TypeSourceInfo for a type.
628 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
629 return SemaRef.Context.getTrivialTypeSourceInfo(T,
630 getDerived().getBaseLocation());
631 }
632
633#define ABSTRACT_TYPELOC(CLASS, PARENT)
634#define TYPELOC(CLASS, PARENT) \
635 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
636#include "clang/AST/TypeLocNodes.def"
637
638 template<typename Fn>
639 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
640 FunctionProtoTypeLoc TL,
641 CXXRecordDecl *ThisContext,
642 Qualifiers ThisTypeQuals,
643 Fn TransformExceptionSpec);
644
645 bool TransformExceptionSpec(SourceLocation Loc,
646 FunctionProtoType::ExceptionSpecInfo &ESI,
647 SmallVectorImpl<QualType> &Exceptions,
648 bool &Changed);
649
650 StmtResult TransformSEHHandler(Stmt *Handler);
651
652 QualType
653 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
654 TemplateSpecializationTypeLoc TL,
655 TemplateName Template);
656
657 QualType
658 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
659 DependentTemplateSpecializationTypeLoc TL,
660 TemplateName Template,
661 CXXScopeSpec &SS);
662
663 QualType TransformDependentTemplateSpecializationType(
664 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
665 NestedNameSpecifierLoc QualifierLoc);
666
667 /// Transforms the parameters of a function type into the
668 /// given vectors.
669 ///
670 /// The result vectors should be kept in sync; null entries in the
671 /// variables vector are acceptable.
672 ///
673 /// Return true on error.
674 bool TransformFunctionTypeParams(
675 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
676 const QualType *ParamTypes,
677 const FunctionProtoType::ExtParameterInfo *ParamInfos,
678 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
679 Sema::ExtParameterInfoBuilder &PInfos);
680
681 /// Transforms a single function-type parameter. Return null
682 /// on error.
683 ///
684 /// \param indexAdjustment - A number to add to the parameter's
685 /// scope index; can be negative
686 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
687 int indexAdjustment,
688 Optional<unsigned> NumExpansions,
689 bool ExpectParameterPack);
690
691 /// Transform the body of a lambda-expression.
692 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
693 /// Alternative implementation of TransformLambdaBody that skips transforming
694 /// the body.
695 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
696
697 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
698
699 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
700 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
701
702 TemplateParameterList *TransformTemplateParameterList(
703 TemplateParameterList *TPL) {
704 return TPL;
705 }
706
707 ExprResult TransformAddressOfOperand(Expr *E);
708
709 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
710 bool IsAddressOfOperand,
711 TypeSourceInfo **RecoveryTSI);
712
713 ExprResult TransformParenDependentScopeDeclRefExpr(
714 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
715 TypeSourceInfo **RecoveryTSI);
716
717 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
718
719// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
720// amount of stack usage with clang.
721#define STMT(Node, Parent) \
722 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
723 StmtResult Transform##Node(Node *S);
724#define VALUESTMT(Node, Parent) \
725 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
726 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
727#define EXPR(Node, Parent) \
728 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
729 ExprResult Transform##Node(Node *E);
730#define ABSTRACT_STMT(Stmt)
731#include "clang/AST/StmtNodes.inc"
732
733#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
734 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
735 OMPClause *Transform ## Class(Class *S);
736#include "llvm/Frontend/OpenMP/OMPKinds.def"
737
738 /// Build a new qualified type given its unqualified type and type location.
739 ///
740 /// By default, this routine adds type qualifiers only to types that can
741 /// have qualifiers, and silently suppresses those qualifiers that are not
742 /// permitted. Subclasses may override this routine to provide different
743 /// behavior.
744 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
745
746 /// Build a new pointer type given its pointee type.
747 ///
748 /// By default, performs semantic analysis when building the pointer type.
749 /// Subclasses may override this routine to provide different behavior.
750 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
751
752 /// Build a new block pointer type given its pointee type.
753 ///
754 /// By default, performs semantic analysis when building the block pointer
755 /// type. Subclasses may override this routine to provide different behavior.
756 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
757
758 /// Build a new reference type given the type it references.
759 ///
760 /// By default, performs semantic analysis when building the
761 /// reference type. Subclasses may override this routine to provide
762 /// different behavior.
763 ///
764 /// \param LValue whether the type was written with an lvalue sigil
765 /// or an rvalue sigil.
766 QualType RebuildReferenceType(QualType ReferentType,
767 bool LValue,
768 SourceLocation Sigil);
769
770 /// Build a new member pointer type given the pointee type and the
771 /// class type it refers into.
772 ///
773 /// By default, performs semantic analysis when building the member pointer
774 /// type. Subclasses may override this routine to provide different behavior.
775 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
776 SourceLocation Sigil);
777
778 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
779 SourceLocation ProtocolLAngleLoc,
780 ArrayRef<ObjCProtocolDecl *> Protocols,
781 ArrayRef<SourceLocation> ProtocolLocs,
782 SourceLocation ProtocolRAngleLoc);
783
784 /// Build an Objective-C object type.
785 ///
786 /// By default, performs semantic analysis when building the object type.
787 /// Subclasses may override this routine to provide different behavior.
788 QualType RebuildObjCObjectType(QualType BaseType,
789 SourceLocation Loc,
790 SourceLocation TypeArgsLAngleLoc,
791 ArrayRef<TypeSourceInfo *> TypeArgs,
792 SourceLocation TypeArgsRAngleLoc,
793 SourceLocation ProtocolLAngleLoc,
794 ArrayRef<ObjCProtocolDecl *> Protocols,
795 ArrayRef<SourceLocation> ProtocolLocs,
796 SourceLocation ProtocolRAngleLoc);
797
798 /// Build a new Objective-C object pointer type given the pointee type.
799 ///
800 /// By default, directly builds the pointer type, with no additional semantic
801 /// analysis.
802 QualType RebuildObjCObjectPointerType(QualType PointeeType,
803 SourceLocation Star);
804
805 /// Build a new array type given the element type, size
806 /// modifier, size of the array (if known), size expression, and index type
807 /// qualifiers.
808 ///
809 /// By default, performs semantic analysis when building the array type.
810 /// Subclasses may override this routine to provide different behavior.
811 /// Also by default, all of the other Rebuild*Array
812 QualType RebuildArrayType(QualType ElementType,
813 ArrayType::ArraySizeModifier SizeMod,
814 const llvm::APInt *Size,
815 Expr *SizeExpr,
816 unsigned IndexTypeQuals,
817 SourceRange BracketsRange);
818
819 /// Build a new constant array type given the element type, size
820 /// modifier, (known) size of the array, and index type qualifiers.
821 ///
822 /// By default, performs semantic analysis when building the array type.
823 /// Subclasses may override this routine to provide different behavior.
824 QualType RebuildConstantArrayType(QualType ElementType,
825 ArrayType::ArraySizeModifier SizeMod,
826 const llvm::APInt &Size,
827 Expr *SizeExpr,
828 unsigned IndexTypeQuals,
829 SourceRange BracketsRange);
830
831 /// Build a new incomplete array type given the element type, size
832 /// modifier, and index type qualifiers.
833 ///
834 /// By default, performs semantic analysis when building the array type.
835 /// Subclasses may override this routine to provide different behavior.
836 QualType RebuildIncompleteArrayType(QualType ElementType,
837 ArrayType::ArraySizeModifier SizeMod,
838 unsigned IndexTypeQuals,
839 SourceRange BracketsRange);
840
841 /// Build a new variable-length array type given the element type,
842 /// size modifier, size expression, and index type qualifiers.
843 ///
844 /// By default, performs semantic analysis when building the array type.
845 /// Subclasses may override this routine to provide different behavior.
846 QualType RebuildVariableArrayType(QualType ElementType,
847 ArrayType::ArraySizeModifier SizeMod,
848 Expr *SizeExpr,
849 unsigned IndexTypeQuals,
850 SourceRange BracketsRange);
851
852 /// Build a new dependent-sized array type given the element type,
853 /// size modifier, size expression, and index type qualifiers.
854 ///
855 /// By default, performs semantic analysis when building the array type.
856 /// Subclasses may override this routine to provide different behavior.
857 QualType RebuildDependentSizedArrayType(QualType ElementType,
858 ArrayType::ArraySizeModifier SizeMod,
859 Expr *SizeExpr,
860 unsigned IndexTypeQuals,
861 SourceRange BracketsRange);
862
863 /// Build a new vector type given the element type and
864 /// number of elements.
865 ///
866 /// By default, performs semantic analysis when building the vector type.
867 /// Subclasses may override this routine to provide different behavior.
868 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
869 VectorType::VectorKind VecKind);
870
871 /// Build a new potentially dependently-sized extended vector type
872 /// given the element type and number of elements.
873 ///
874 /// By default, performs semantic analysis when building the vector type.
875 /// Subclasses may override this routine to provide different behavior.
876 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
877 SourceLocation AttributeLoc,
878 VectorType::VectorKind);
879
880 /// Build a new extended vector type given the element type and
881 /// number of elements.
882 ///
883 /// By default, performs semantic analysis when building the vector type.
884 /// Subclasses may override this routine to provide different behavior.
885 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
886 SourceLocation AttributeLoc);
887
888 /// Build a new potentially dependently-sized extended vector type
889 /// given the element type and number of elements.
890 ///
891 /// By default, performs semantic analysis when building the vector type.
892 /// Subclasses may override this routine to provide different behavior.
893 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
894 Expr *SizeExpr,
895 SourceLocation AttributeLoc);
896
897 /// Build a new matrix type given the element type and dimensions.
898 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
899 unsigned NumColumns);
900
901 /// Build a new matrix type given the type and dependently-defined
902 /// dimensions.
903 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
904 Expr *ColumnExpr,
905 SourceLocation AttributeLoc);
906
907 /// Build a new DependentAddressSpaceType or return the pointee
908 /// type variable with the correct address space (retrieved from
909 /// AddrSpaceExpr) applied to it. The former will be returned in cases
910 /// where the address space remains dependent.
911 ///
912 /// By default, performs semantic analysis when building the type with address
913 /// space applied. Subclasses may override this routine to provide different
914 /// behavior.
915 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
916 Expr *AddrSpaceExpr,
917 SourceLocation AttributeLoc);
918
919 /// Build a new function type.
920 ///
921 /// By default, performs semantic analysis when building the function type.
922 /// Subclasses may override this routine to provide different behavior.
923 QualType RebuildFunctionProtoType(QualType T,
924 MutableArrayRef<QualType> ParamTypes,
925 const FunctionProtoType::ExtProtoInfo &EPI);
926
927 /// Build a new unprototyped function type.
928 QualType RebuildFunctionNoProtoType(QualType ResultType);
929
930 /// Rebuild an unresolved typename type, given the decl that
931 /// the UnresolvedUsingTypenameDecl was transformed to.
932 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
933
934 /// Build a new typedef type.
935 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
936 return SemaRef.Context.getTypeDeclType(Typedef);
937 }
938
939 /// Build a new MacroDefined type.
940 QualType RebuildMacroQualifiedType(QualType T,
941 const IdentifierInfo *MacroII) {
942 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
943 }
944
945 /// Build a new class/struct/union type.
946 QualType RebuildRecordType(RecordDecl *Record) {
947 return SemaRef.Context.getTypeDeclType(Record);
948 }
949
950 /// Build a new Enum type.
951 QualType RebuildEnumType(EnumDecl *Enum) {
952 return SemaRef.Context.getTypeDeclType(Enum);
953 }
954
955 /// Build a new typeof(expr) type.
956 ///
957 /// By default, performs semantic analysis when building the typeof type.
958 /// Subclasses may override this routine to provide different behavior.
959 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
960
961 /// Build a new typeof(type) type.
962 ///
963 /// By default, builds a new TypeOfType with the given underlying type.
964 QualType RebuildTypeOfType(QualType Underlying);
965
966 /// Build a new unary transform type.
967 QualType RebuildUnaryTransformType(QualType BaseType,
968 UnaryTransformType::UTTKind UKind,
969 SourceLocation Loc);
970
971 /// Build a new C++11 decltype type.
972 ///
973 /// By default, performs semantic analysis when building the decltype type.
974 /// Subclasses may override this routine to provide different behavior.
975 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
976
977 /// Build a new C++11 auto type.
978 ///
979 /// By default, builds a new AutoType with the given deduced type.
980 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
981 ConceptDecl *TypeConstraintConcept,
982 ArrayRef<TemplateArgument> TypeConstraintArgs) {
983 // Note, IsDependent is always false here: we implicitly convert an 'auto'
984 // which has been deduced to a dependent type into an undeduced 'auto', so
985 // that we'll retry deduction after the transformation.
986 return SemaRef.Context.getAutoType(Deduced, Keyword,
987 /*IsDependent*/ false, /*IsPack=*/false,
988 TypeConstraintConcept,
989 TypeConstraintArgs);
990 }
991
992 /// By default, builds a new DeducedTemplateSpecializationType with the given
993 /// deduced type.
994 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
995 QualType Deduced) {
996 return SemaRef.Context.getDeducedTemplateSpecializationType(
997 Template, Deduced, /*IsDependent*/ false);
998 }
999
1000 /// Build a new template specialization type.
1001 ///
1002 /// By default, performs semantic analysis when building the template
1003 /// specialization type. Subclasses may override this routine to provide
1004 /// different behavior.
1005 QualType RebuildTemplateSpecializationType(TemplateName Template,
1006 SourceLocation TemplateLoc,
1007 TemplateArgumentListInfo &Args);
1008
1009 /// Build a new parenthesized type.
1010 ///
1011 /// By default, builds a new ParenType type from the inner type.
1012 /// Subclasses may override this routine to provide different behavior.
1013 QualType RebuildParenType(QualType InnerType) {
1014 return SemaRef.BuildParenType(InnerType);
1015 }
1016
1017 /// Build a new qualified name type.
1018 ///
1019 /// By default, builds a new ElaboratedType type from the keyword,
1020 /// the nested-name-specifier and the named type.
1021 /// Subclasses may override this routine to provide different behavior.
1022 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1023 ElaboratedTypeKeyword Keyword,
1024 NestedNameSpecifierLoc QualifierLoc,
1025 QualType Named) {
1026 return SemaRef.Context.getElaboratedType(Keyword,
1027 QualifierLoc.getNestedNameSpecifier(),
1028 Named);
1029 }
1030
1031 /// Build a new typename type that refers to a template-id.
1032 ///
1033 /// By default, builds a new DependentNameType type from the
1034 /// nested-name-specifier and the given type. Subclasses may override
1035 /// this routine to provide different behavior.
1036 QualType RebuildDependentTemplateSpecializationType(
1037 ElaboratedTypeKeyword Keyword,
1038 NestedNameSpecifierLoc QualifierLoc,
1039 SourceLocation TemplateKWLoc,
1040 const IdentifierInfo *Name,
1041 SourceLocation NameLoc,
1042 TemplateArgumentListInfo &Args,
1043 bool AllowInjectedClassName) {
1044 // Rebuild the template name.
1045 // TODO: avoid TemplateName abstraction
1046 CXXScopeSpec SS;
1047 SS.Adopt(QualifierLoc);
1048 TemplateName InstName = getDerived().RebuildTemplateName(
1049 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1050 AllowInjectedClassName);
1051
1052 if (InstName.isNull())
1053 return QualType();
1054
1055 // If it's still dependent, make a dependent specialization.
1056 if (InstName.getAsDependentTemplateName())
1057 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1058 QualifierLoc.getNestedNameSpecifier(),
1059 Name,
1060 Args);
1061
1062 // Otherwise, make an elaborated type wrapping a non-dependent
1063 // specialization.
1064 QualType T =
1065 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1066 if (T.isNull()) return QualType();
1067
1068 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1069 return T;
1070
1071 return SemaRef.Context.getElaboratedType(Keyword,
1072 QualifierLoc.getNestedNameSpecifier(),
1073 T);
1074 }
1075
1076 /// Build a new typename type that refers to an identifier.
1077 ///
1078 /// By default, performs semantic analysis when building the typename type
1079 /// (or elaborated type). Subclasses may override this routine to provide
1080 /// different behavior.
1081 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1082 SourceLocation KeywordLoc,
1083 NestedNameSpecifierLoc QualifierLoc,
1084 const IdentifierInfo *Id,
1085 SourceLocation IdLoc,
1086 bool DeducedTSTContext) {
1087 CXXScopeSpec SS;
1088 SS.Adopt(QualifierLoc);
1089
1090 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1091 // If the name is still dependent, just build a new dependent name type.
1092 if (!SemaRef.computeDeclContext(SS))
1093 return SemaRef.Context.getDependentNameType(Keyword,
1094 QualifierLoc.getNestedNameSpecifier(),
1095 Id);
1096 }
1097
1098 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1099 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1100 *Id, IdLoc, DeducedTSTContext);
1101 }
1102
1103 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1104
1105 // We had a dependent elaborated-type-specifier that has been transformed
1106 // into a non-dependent elaborated-type-specifier. Find the tag we're
1107 // referring to.
1108 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1109 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1110 if (!DC)
1111 return QualType();
1112
1113 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1114 return QualType();
1115
1116 TagDecl *Tag = nullptr;
1117 SemaRef.LookupQualifiedName(Result, DC);
1118 switch (Result.getResultKind()) {
1119 case LookupResult::NotFound:
1120 case LookupResult::NotFoundInCurrentInstantiation:
1121 break;
1122
1123 case LookupResult::Found:
1124 Tag = Result.getAsSingle<TagDecl>();
1125 break;
1126
1127 case LookupResult::FoundOverloaded:
1128 case LookupResult::FoundUnresolvedValue:
1129 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/TreeTransform.h"
, 1129)
;
1130
1131 case LookupResult::Ambiguous:
1132 // Let the LookupResult structure handle ambiguities.
1133 return QualType();
1134 }
1135
1136 if (!Tag) {
1137 // Check where the name exists but isn't a tag type and use that to emit
1138 // better diagnostics.
1139 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1140 SemaRef.LookupQualifiedName(Result, DC);
1141 switch (Result.getResultKind()) {
1142 case LookupResult::Found:
1143 case LookupResult::FoundOverloaded:
1144 case LookupResult::FoundUnresolvedValue: {
1145 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1146 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1147 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1148 << NTK << Kind;
1149 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1150 break;
1151 }
1152 default:
1153 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1154 << Kind << Id << DC << QualifierLoc.getSourceRange();
1155 break;
1156 }
1157 return QualType();
1158 }
1159
1160 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1161 IdLoc, Id)) {
1162 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1163 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1164 return QualType();
1165 }
1166
1167 // Build the elaborated-type-specifier type.
1168 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1169 return SemaRef.Context.getElaboratedType(Keyword,
1170 QualifierLoc.getNestedNameSpecifier(),
1171 T);
1172 }
1173
1174 /// Build a new pack expansion type.
1175 ///
1176 /// By default, builds a new PackExpansionType type from the given pattern.
1177 /// Subclasses may override this routine to provide different behavior.
1178 QualType RebuildPackExpansionType(QualType Pattern,
1179 SourceRange PatternRange,
1180 SourceLocation EllipsisLoc,
1181 Optional<unsigned> NumExpansions) {
1182 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1183 NumExpansions);
1184 }
1185
1186 /// Build a new atomic type given its value type.
1187 ///
1188 /// By default, performs semantic analysis when building the atomic type.
1189 /// Subclasses may override this routine to provide different behavior.
1190 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1191
1192 /// Build a new pipe type given its value type.
1193 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1194 bool isReadPipe);
1195
1196 /// Build an extended int given its value type.
1197 QualType RebuildExtIntType(bool IsUnsigned, unsigned NumBits,
1198 SourceLocation Loc);
1199
1200 /// Build a dependent extended int given its value type.
1201 QualType RebuildDependentExtIntType(bool IsUnsigned, Expr *NumBitsExpr,
1202 SourceLocation Loc);
1203
1204 /// Build a new template name given a nested name specifier, a flag
1205 /// indicating whether the "template" keyword was provided, and the template
1206 /// that the template name refers to.
1207 ///
1208 /// By default, builds the new template name directly. Subclasses may override
1209 /// this routine to provide different behavior.
1210 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1211 bool TemplateKW,
1212 TemplateDecl *Template);
1213
1214 /// Build a new template name given a nested name specifier and the
1215 /// name that is referred to as a template.
1216 ///
1217 /// By default, performs semantic analysis to determine whether the name can
1218 /// be resolved to a specific template, then builds the appropriate kind of
1219 /// template name. Subclasses may override this routine to provide different
1220 /// behavior.
1221 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1222 SourceLocation TemplateKWLoc,
1223 const IdentifierInfo &Name,
1224 SourceLocation NameLoc, QualType ObjectType,
1225 NamedDecl *FirstQualifierInScope,
1226 bool AllowInjectedClassName);
1227
1228 /// Build a new template name given a nested name specifier and the
1229 /// overloaded operator name that is referred to as a template.
1230 ///
1231 /// By default, performs semantic analysis to determine whether the name can
1232 /// be resolved to a specific template, then builds the appropriate kind of
1233 /// template name. Subclasses may override this routine to provide different
1234 /// behavior.
1235 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1236 SourceLocation TemplateKWLoc,
1237 OverloadedOperatorKind Operator,
1238 SourceLocation NameLoc, QualType ObjectType,
1239 bool AllowInjectedClassName);
1240
1241 /// Build a new template name given a template template parameter pack
1242 /// and the
1243 ///
1244 /// By default, performs semantic analysis to determine whether the name can
1245 /// be resolved to a specific template, then builds the appropriate kind of
1246 /// template name. Subclasses may override this routine to provide different
1247 /// behavior.
1248 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1249 const TemplateArgument &ArgPack) {
1250 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1251 }
1252
1253 /// Build a new compound statement.
1254 ///
1255 /// By default, performs semantic analysis to build the new statement.
1256 /// Subclasses may override this routine to provide different behavior.
1257 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1258 MultiStmtArg Statements,
1259 SourceLocation RBraceLoc,
1260 bool IsStmtExpr) {
1261 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1262 IsStmtExpr);
1263 }
1264
1265 /// Build a new case statement.
1266 ///
1267 /// By default, performs semantic analysis to build the new statement.
1268 /// Subclasses may override this routine to provide different behavior.
1269 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1270 Expr *LHS,
1271 SourceLocation EllipsisLoc,
1272 Expr *RHS,
1273 SourceLocation ColonLoc) {
1274 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1275 ColonLoc);
1276 }
1277
1278 /// Attach the body to a new case statement.
1279 ///
1280 /// By default, performs semantic analysis to build the new statement.
1281 /// Subclasses may override this routine to provide different behavior.
1282 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1283 getSema().ActOnCaseStmtBody(S, Body);
1284 return S;
1285 }
1286
1287 /// Build a new default statement.
1288 ///
1289 /// By default, performs semantic analysis to build the new statement.
1290 /// Subclasses may override this routine to provide different behavior.
1291 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1292 SourceLocation ColonLoc,
1293 Stmt *SubStmt) {
1294 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1295 /*CurScope=*/nullptr);
1296 }
1297
1298 /// Build a new label statement.
1299 ///
1300 /// By default, performs semantic analysis to build the new statement.
1301 /// Subclasses may override this routine to provide different behavior.
1302 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1303 SourceLocation ColonLoc, Stmt *SubStmt) {
1304 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1305 }
1306
1307 /// Build a new label statement.
1308 ///
1309 /// By default, performs semantic analysis to build the new statement.
1310 /// Subclasses may override this routine to provide different behavior.
1311 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1312 ArrayRef<const Attr*> Attrs,
1313 Stmt *SubStmt) {
1314 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1315 }
1316
1317 /// Build a new "if" statement.
1318 ///
1319 /// By default, performs semantic analysis to build the new statement.
1320 /// Subclasses may override this routine to provide different behavior.
1321 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1322 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1323 SourceLocation ElseLoc, Stmt *Else) {
1324 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1325 ElseLoc, Else);
1326 }
1327
1328 /// Start building a new switch statement.
1329 ///
1330 /// By default, performs semantic analysis to build the new statement.
1331 /// Subclasses may override this routine to provide different behavior.
1332 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1333 Sema::ConditionResult Cond) {
1334 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1335 }
1336
1337 /// Attach the body to the switch statement.
1338 ///
1339 /// By default, performs semantic analysis to build the new statement.
1340 /// Subclasses may override this routine to provide different behavior.
1341 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1342 Stmt *Switch, Stmt *Body) {
1343 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1344 }
1345
1346 /// Build a new while statement.
1347 ///
1348 /// By default, performs semantic analysis to build the new statement.
1349 /// Subclasses may override this routine to provide different behavior.
1350 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1351 Sema::ConditionResult Cond,
1352 SourceLocation RParenLoc, Stmt *Body) {
1353 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1354 }
1355
1356 /// Build a new do-while statement.
1357 ///
1358 /// By default, performs semantic analysis to build the new statement.
1359 /// Subclasses may override this routine to provide different behavior.
1360 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1361 SourceLocation WhileLoc, SourceLocation LParenLoc,
1362 Expr *Cond, SourceLocation RParenLoc) {
1363 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1364 Cond, RParenLoc);
1365 }
1366
1367 /// Build a new for statement.
1368 ///
1369 /// By default, performs semantic analysis to build the new statement.
1370 /// Subclasses may override this routine to provide different behavior.
1371 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1372 Stmt *Init, Sema::ConditionResult Cond,
1373 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1374 Stmt *Body) {
1375 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1376 Inc, RParenLoc, Body);
1377 }
1378
1379 /// Build a new goto statement.
1380 ///
1381 /// By default, performs semantic analysis to build the new statement.
1382 /// Subclasses may override this routine to provide different behavior.
1383 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1384 LabelDecl *Label) {
1385 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1386 }
1387
1388 /// Build a new indirect goto statement.
1389 ///
1390 /// By default, performs semantic analysis to build the new statement.
1391 /// Subclasses may override this routine to provide different behavior.
1392 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1393 SourceLocation StarLoc,
1394 Expr *Target) {
1395 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1396 }
1397
1398 /// Build a new return statement.
1399 ///
1400 /// By default, performs semantic analysis to build the new statement.
1401 /// Subclasses may override this routine to provide different behavior.
1402 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1403 return getSema().BuildReturnStmt(ReturnLoc, Result);
1404 }
1405
1406 /// Build a new declaration statement.
1407 ///
1408 /// By default, performs semantic analysis to build the new statement.
1409 /// Subclasses may override this routine to provide different behavior.
1410 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1411 SourceLocation StartLoc, SourceLocation EndLoc) {
1412 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1413 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1414 }
1415
1416 /// Build a new inline asm statement.
1417 ///
1418 /// By default, performs semantic analysis to build the new statement.
1419 /// Subclasses may override this routine to provide different behavior.
1420 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1421 bool IsVolatile, unsigned NumOutputs,
1422 unsigned NumInputs, IdentifierInfo **Names,
1423 MultiExprArg Constraints, MultiExprArg Exprs,
1424 Expr *AsmString, MultiExprArg Clobbers,
1425 unsigned NumLabels,
1426 SourceLocation RParenLoc) {
1427 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1428 NumInputs, Names, Constraints, Exprs,
1429 AsmString, Clobbers, NumLabels, RParenLoc);
1430 }
1431
1432 /// Build a new MS style inline asm statement.
1433 ///
1434 /// By default, performs semantic analysis to build the new statement.
1435 /// Subclasses may override this routine to provide different behavior.
1436 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1437 ArrayRef<Token> AsmToks,
1438 StringRef AsmString,
1439 unsigned NumOutputs, unsigned NumInputs,
1440 ArrayRef<StringRef> Constraints,
1441 ArrayRef<StringRef> Clobbers,
1442 ArrayRef<Expr*> Exprs,
1443 SourceLocation EndLoc) {
1444 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1445 NumOutputs, NumInputs,
1446 Constraints, Clobbers, Exprs, EndLoc);
1447 }
1448
1449 /// Build a new co_return statement.
1450 ///
1451 /// By default, performs semantic analysis to build the new statement.
1452 /// Subclasses may override this routine to provide different behavior.
1453 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1454 bool IsImplicit) {
1455 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1456 }
1457
1458 /// Build a new co_await expression.
1459 ///
1460 /// By default, performs semantic analysis to build the new expression.
1461 /// Subclasses may override this routine to provide different behavior.
1462 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1463 bool IsImplicit) {
1464 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1465 }
1466
1467 /// Build a new co_await expression.
1468 ///
1469 /// By default, performs semantic analysis to build the new expression.
1470 /// Subclasses may override this routine to provide different behavior.
1471 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1472 Expr *Result,
1473 UnresolvedLookupExpr *Lookup) {
1474 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1475 }
1476
1477 /// Build a new co_yield expression.
1478 ///
1479 /// By default, performs semantic analysis to build the new expression.
1480 /// Subclasses may override this routine to provide different behavior.
1481 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1482 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1483 }
1484
1485 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1486 return getSema().BuildCoroutineBodyStmt(Args);
1487 }
1488
1489 /// Build a new Objective-C \@try statement.
1490 ///
1491 /// By default, performs semantic analysis to build the new statement.
1492 /// Subclasses may override this routine to provide different behavior.
1493 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1494 Stmt *TryBody,
1495 MultiStmtArg CatchStmts,
1496 Stmt *Finally) {
1497 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1498 Finally);
1499 }
1500
1501 /// Rebuild an Objective-C exception declaration.
1502 ///
1503 /// By default, performs semantic analysis to build the new declaration.
1504 /// Subclasses may override this routine to provide different behavior.
1505 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1506 TypeSourceInfo *TInfo, QualType T) {
1507 return getSema().BuildObjCExceptionDecl(TInfo, T,
1508 ExceptionDecl->getInnerLocStart(),
1509 ExceptionDecl->getLocation(),
1510 ExceptionDecl->getIdentifier());
1511 }
1512
1513 /// Build a new Objective-C \@catch statement.
1514 ///
1515 /// By default, performs semantic analysis to build the new statement.
1516 /// Subclasses may override this routine to provide different behavior.
1517 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1518 SourceLocation RParenLoc,
1519 VarDecl *Var,
1520 Stmt *Body) {
1521 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1522 Var, Body);
1523 }
1524
1525 /// Build a new Objective-C \@finally statement.
1526 ///
1527 /// By default, performs semantic analysis to build the new statement.
1528 /// Subclasses may override this routine to provide different behavior.
1529 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1530 Stmt *Body) {
1531 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1532 }
1533
1534 /// Build a new Objective-C \@throw statement.
1535 ///
1536 /// By default, performs semantic analysis to build the new statement.
1537 /// Subclasses may override this routine to provide different behavior.
1538 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1539 Expr *Operand) {
1540 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1541 }
1542
1543 /// Build a new OpenMP executable directive.
1544 ///
1545 /// By default, performs semantic analysis to build the new statement.
1546 /// Subclasses may override this routine to provide different behavior.
1547 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1548 DeclarationNameInfo DirName,
1549 OpenMPDirectiveKind CancelRegion,
1550 ArrayRef<OMPClause *> Clauses,
1551 Stmt *AStmt, SourceLocation StartLoc,
1552 SourceLocation EndLoc) {
1553 return getSema().ActOnOpenMPExecutableDirective(
1554 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1555 }
1556
1557 /// Build a new OpenMP 'if' clause.
1558 ///
1559 /// By default, performs semantic analysis to build the new OpenMP clause.
1560 /// Subclasses may override this routine to provide different behavior.
1561 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1562 Expr *Condition, SourceLocation StartLoc,
1563 SourceLocation LParenLoc,
1564 SourceLocation NameModifierLoc,
1565 SourceLocation ColonLoc,
1566 SourceLocation EndLoc) {
1567 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1568 LParenLoc, NameModifierLoc, ColonLoc,
1569 EndLoc);
1570 }
1571
1572 /// Build a new OpenMP 'final' clause.
1573 ///
1574 /// By default, performs semantic analysis to build the new OpenMP clause.
1575 /// Subclasses may override this routine to provide different behavior.
1576 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1577 SourceLocation LParenLoc,
1578 SourceLocation EndLoc) {
1579 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1580 EndLoc);
1581 }
1582
1583 /// Build a new OpenMP 'num_threads' clause.
1584 ///
1585 /// By default, performs semantic analysis to build the new OpenMP clause.
1586 /// Subclasses may override this routine to provide different behavior.
1587 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1588 SourceLocation StartLoc,
1589 SourceLocation LParenLoc,
1590 SourceLocation EndLoc) {
1591 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1592 LParenLoc, EndLoc);
1593 }
1594
1595 /// Build a new OpenMP 'safelen' clause.
1596 ///
1597 /// By default, performs semantic analysis to build the new OpenMP clause.
1598 /// Subclasses may override this routine to provide different behavior.
1599 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1600 SourceLocation LParenLoc,
1601 SourceLocation EndLoc) {
1602 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1603 }
1604
1605 /// Build a new OpenMP 'simdlen' clause.
1606 ///
1607 /// By default, performs semantic analysis to build the new OpenMP clause.
1608 /// Subclasses may override this routine to provide different behavior.
1609 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1610 SourceLocation LParenLoc,
1611 SourceLocation EndLoc) {
1612 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1613 }
1614
1615 /// Build a new OpenMP 'allocator' clause.
1616 ///
1617 /// By default, performs semantic analysis to build the new OpenMP clause.
1618 /// Subclasses may override this routine to provide different behavior.
1619 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1620 SourceLocation LParenLoc,
1621 SourceLocation EndLoc) {
1622 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1623 }
1624
1625 /// Build a new OpenMP 'collapse' clause.
1626 ///
1627 /// By default, performs semantic analysis to build the new OpenMP clause.
1628 /// Subclasses may override this routine to provide different behavior.
1629 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1630 SourceLocation LParenLoc,
1631 SourceLocation EndLoc) {
1632 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1633 EndLoc);
1634 }
1635
1636 /// Build a new OpenMP 'default' clause.
1637 ///
1638 /// By default, performs semantic analysis to build the new OpenMP clause.
1639 /// Subclasses may override this routine to provide different behavior.
1640 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1641 SourceLocation StartLoc,
1642 SourceLocation LParenLoc,
1643 SourceLocation EndLoc) {
1644 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1645 StartLoc, LParenLoc, EndLoc);
1646 }
1647
1648 /// Build a new OpenMP 'proc_bind' clause.
1649 ///
1650 /// By default, performs semantic analysis to build the new OpenMP clause.
1651 /// Subclasses may override this routine to provide different behavior.
1652 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1653 SourceLocation KindKwLoc,
1654 SourceLocation StartLoc,
1655 SourceLocation LParenLoc,
1656 SourceLocation EndLoc) {
1657 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1658 StartLoc, LParenLoc, EndLoc);
1659 }
1660
1661 /// Build a new OpenMP 'schedule' clause.
1662 ///
1663 /// By default, performs semantic analysis to build the new OpenMP clause.
1664 /// Subclasses may override this routine to provide different behavior.
1665 OMPClause *RebuildOMPScheduleClause(
1666 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1667 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1668 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1669 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1670 return getSema().ActOnOpenMPScheduleClause(
1671 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1672 CommaLoc, EndLoc);
1673 }
1674
1675 /// Build a new OpenMP 'ordered' clause.
1676 ///
1677 /// By default, performs semantic analysis to build the new OpenMP clause.
1678 /// Subclasses may override this routine to provide different behavior.
1679 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1680 SourceLocation EndLoc,
1681 SourceLocation LParenLoc, Expr *Num) {
1682 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1683 }
1684
1685 /// Build a new OpenMP 'private' clause.
1686 ///
1687 /// By default, performs semantic analysis to build the new OpenMP clause.
1688 /// Subclasses may override this routine to provide different behavior.
1689 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1690 SourceLocation StartLoc,
1691 SourceLocation LParenLoc,
1692 SourceLocation EndLoc) {
1693 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1694 EndLoc);
1695 }
1696
1697 /// Build a new OpenMP 'firstprivate' clause.
1698 ///
1699 /// By default, performs semantic analysis to build the new OpenMP clause.
1700 /// Subclasses may override this routine to provide different behavior.
1701 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1702 SourceLocation StartLoc,
1703 SourceLocation LParenLoc,
1704 SourceLocation EndLoc) {
1705 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1706 EndLoc);
1707 }
1708
1709 /// Build a new OpenMP 'lastprivate' clause.
1710 ///
1711 /// By default, performs semantic analysis to build the new OpenMP clause.
1712 /// Subclasses may override this routine to provide different behavior.
1713 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1714 OpenMPLastprivateModifier LPKind,
1715 SourceLocation LPKindLoc,
1716 SourceLocation ColonLoc,
1717 SourceLocation StartLoc,
1718 SourceLocation LParenLoc,
1719 SourceLocation EndLoc) {
1720 return getSema().ActOnOpenMPLastprivateClause(
1721 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1722 }
1723
1724 /// Build a new OpenMP 'shared' clause.
1725 ///
1726 /// By default, performs semantic analysis to build the new OpenMP clause.
1727 /// Subclasses may override this routine to provide different behavior.
1728 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1729 SourceLocation StartLoc,
1730 SourceLocation LParenLoc,
1731 SourceLocation EndLoc) {
1732 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1733 EndLoc);
1734 }
1735
1736 /// Build a new OpenMP 'reduction' clause.
1737 ///
1738 /// By default, performs semantic analysis to build the new statement.
1739 /// Subclasses may override this routine to provide different behavior.
1740 OMPClause *RebuildOMPReductionClause(
1741 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1742 SourceLocation StartLoc, SourceLocation LParenLoc,
1743 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1744 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1745 const DeclarationNameInfo &ReductionId,
1746 ArrayRef<Expr *> UnresolvedReductions) {
1747 return getSema().ActOnOpenMPReductionClause(
1748 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1749 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1750 }
1751
1752 /// Build a new OpenMP 'task_reduction' clause.
1753 ///
1754 /// By default, performs semantic analysis to build the new statement.
1755 /// Subclasses may override this routine to provide different behavior.
1756 OMPClause *RebuildOMPTaskReductionClause(
1757 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1758 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1759 CXXScopeSpec &ReductionIdScopeSpec,
1760 const DeclarationNameInfo &ReductionId,
1761 ArrayRef<Expr *> UnresolvedReductions) {
1762 return getSema().ActOnOpenMPTaskReductionClause(
1763 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1764 ReductionId, UnresolvedReductions);
1765 }
1766
1767 /// Build a new OpenMP 'in_reduction' clause.
1768 ///
1769 /// By default, performs semantic analysis to build the new statement.
1770 /// Subclasses may override this routine to provide different behavior.
1771 OMPClause *
1772 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1773 SourceLocation LParenLoc, SourceLocation ColonLoc,
1774 SourceLocation EndLoc,
1775 CXXScopeSpec &ReductionIdScopeSpec,
1776 const DeclarationNameInfo &ReductionId,
1777 ArrayRef<Expr *> UnresolvedReductions) {
1778 return getSema().ActOnOpenMPInReductionClause(
1779 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1780 ReductionId, UnresolvedReductions);
1781 }
1782
1783 /// Build a new OpenMP 'linear' clause.
1784 ///
1785 /// By default, performs semantic analysis to build the new OpenMP clause.
1786 /// Subclasses may override this routine to provide different behavior.
1787 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1788 SourceLocation StartLoc,
1789 SourceLocation LParenLoc,
1790 OpenMPLinearClauseKind Modifier,
1791 SourceLocation ModifierLoc,
1792 SourceLocation ColonLoc,
1793 SourceLocation EndLoc) {
1794 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1795 Modifier, ModifierLoc, ColonLoc,
1796 EndLoc);
1797 }
1798
1799 /// Build a new OpenMP 'aligned' clause.
1800 ///
1801 /// By default, performs semantic analysis to build the new OpenMP clause.
1802 /// Subclasses may override this routine to provide different behavior.
1803 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1804 SourceLocation StartLoc,
1805 SourceLocation LParenLoc,
1806 SourceLocation ColonLoc,
1807 SourceLocation EndLoc) {
1808 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1809 LParenLoc, ColonLoc, EndLoc);
1810 }
1811
1812 /// Build a new OpenMP 'copyin' clause.
1813 ///
1814 /// By default, performs semantic analysis to build the new OpenMP clause.
1815 /// Subclasses may override this routine to provide different behavior.
1816 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1817 SourceLocation StartLoc,
1818 SourceLocation LParenLoc,
1819 SourceLocation EndLoc) {
1820 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1821 EndLoc);
1822 }
1823
1824 /// Build a new OpenMP 'copyprivate' clause.
1825 ///
1826 /// By default, performs semantic analysis to build the new OpenMP clause.
1827 /// Subclasses may override this routine to provide different behavior.
1828 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1829 SourceLocation StartLoc,
1830 SourceLocation LParenLoc,
1831 SourceLocation EndLoc) {
1832 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1833 EndLoc);
1834 }
1835
1836 /// Build a new OpenMP 'flush' pseudo clause.
1837 ///
1838 /// By default, performs semantic analysis to build the new OpenMP clause.
1839 /// Subclasses may override this routine to provide different behavior.
1840 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1841 SourceLocation StartLoc,
1842 SourceLocation LParenLoc,
1843 SourceLocation EndLoc) {
1844 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1845 EndLoc);
1846 }
1847
1848 /// Build a new OpenMP 'depobj' pseudo clause.
1849 ///
1850 /// By default, performs semantic analysis to build the new OpenMP clause.
1851 /// Subclasses may override this routine to provide different behavior.
1852 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1853 SourceLocation LParenLoc,
1854 SourceLocation EndLoc) {
1855 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1856 EndLoc);
1857 }
1858
1859 /// Build a new OpenMP 'depend' pseudo clause.
1860 ///
1861 /// By default, performs semantic analysis to build the new OpenMP clause.
1862 /// Subclasses may override this routine to provide different behavior.
1863 OMPClause *
1864 RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1865 SourceLocation DepLoc, SourceLocation ColonLoc,
1866 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1867 SourceLocation LParenLoc, SourceLocation EndLoc) {
1868 return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1869 ColonLoc, VarList, StartLoc,
1870 LParenLoc, EndLoc);
1871 }
1872
1873 /// Build a new OpenMP 'device' clause.
1874 ///
1875 /// By default, performs semantic analysis to build the new statement.
1876 /// Subclasses may override this routine to provide different behavior.
1877 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1878 Expr *Device, SourceLocation StartLoc,
1879 SourceLocation LParenLoc,
1880 SourceLocation ModifierLoc,
1881 SourceLocation EndLoc) {
1882 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1883 LParenLoc, ModifierLoc, EndLoc);
1884 }
1885
1886 /// Build a new OpenMP 'map' clause.
1887 ///
1888 /// By default, performs semantic analysis to build the new OpenMP clause.
1889 /// Subclasses may override this routine to provide different behavior.
1890 OMPClause *RebuildOMPMapClause(
1891 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1892 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1893 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1894 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1895 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1896 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1897 return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1898 MapperIdScopeSpec, MapperId, MapType,
1899 IsMapTypeImplicit, MapLoc, ColonLoc,
1900 VarList, Locs, UnresolvedMappers);
1901 }
1902
1903 /// Build a new OpenMP 'allocate' clause.
1904 ///
1905 /// By default, performs semantic analysis to build the new OpenMP clause.
1906 /// Subclasses may override this routine to provide different behavior.
1907 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1908 SourceLocation StartLoc,
1909 SourceLocation LParenLoc,
1910 SourceLocation ColonLoc,
1911 SourceLocation EndLoc) {
1912 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1913 LParenLoc, ColonLoc, EndLoc);
1914 }
1915
1916 /// Build a new OpenMP 'num_teams' clause.
1917 ///
1918 /// By default, performs semantic analysis to build the new statement.
1919 /// Subclasses may override this routine to provide different behavior.
1920 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1921 SourceLocation LParenLoc,
1922 SourceLocation EndLoc) {
1923 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1924 EndLoc);
1925 }
1926
1927 /// Build a new OpenMP 'thread_limit' clause.
1928 ///
1929 /// By default, performs semantic analysis to build the new statement.
1930 /// Subclasses may override this routine to provide different behavior.
1931 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1932 SourceLocation StartLoc,
1933 SourceLocation LParenLoc,
1934 SourceLocation EndLoc) {
1935 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1936 LParenLoc, EndLoc);
1937 }
1938
1939 /// Build a new OpenMP 'priority' clause.
1940 ///
1941 /// By default, performs semantic analysis to build the new statement.
1942 /// Subclasses may override this routine to provide different behavior.
1943 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1944 SourceLocation LParenLoc,
1945 SourceLocation EndLoc) {
1946 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1947 EndLoc);
1948 }
1949
1950 /// Build a new OpenMP 'grainsize' clause.
1951 ///
1952 /// By default, performs semantic analysis to build the new statement.
1953 /// Subclasses may override this routine to provide different behavior.
1954 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1955 SourceLocation LParenLoc,
1956 SourceLocation EndLoc) {
1957 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1958 EndLoc);
1959 }
1960
1961 /// Build a new OpenMP 'num_tasks' clause.
1962 ///
1963 /// By default, performs semantic analysis to build the new statement.
1964 /// Subclasses may override this routine to provide different behavior.
1965 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1966 SourceLocation LParenLoc,
1967 SourceLocation EndLoc) {
1968 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1969 EndLoc);
1970 }
1971
1972 /// Build a new OpenMP 'hint' clause.
1973 ///
1974 /// By default, performs semantic analysis to build the new statement.
1975 /// Subclasses may override this routine to provide different behavior.
1976 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1977 SourceLocation LParenLoc,
1978 SourceLocation EndLoc) {
1979 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1980 }
1981
1982 /// Build a new OpenMP 'detach' clause.
1983 ///
1984 /// By default, performs semantic analysis to build the new statement.
1985 /// Subclasses may override this routine to provide different behavior.
1986 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
1987 SourceLocation LParenLoc,
1988 SourceLocation EndLoc) {
1989 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
1990 }
1991
1992 /// Build a new OpenMP 'dist_schedule' clause.
1993 ///
1994 /// By default, performs semantic analysis to build the new OpenMP clause.
1995 /// Subclasses may override this routine to provide different behavior.
1996 OMPClause *
1997 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1998 Expr *ChunkSize, SourceLocation StartLoc,
1999 SourceLocation LParenLoc, SourceLocation KindLoc,
2000 SourceLocation CommaLoc, SourceLocation EndLoc) {
2001 return getSema().ActOnOpenMPDistScheduleClause(
2002 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2003 }
2004
2005 /// Build a new OpenMP 'to' clause.
2006 ///
2007 /// By default, performs semantic analysis to build the new statement.
2008 /// Subclasses may override this routine to provide different behavior.
2009 OMPClause *
2010 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2011 ArrayRef<SourceLocation> MotionModifiersLoc,
2012 CXXScopeSpec &MapperIdScopeSpec,
2013 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2014 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2015 ArrayRef<Expr *> UnresolvedMappers) {
2016 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2017 MapperIdScopeSpec, MapperId, ColonLoc,
2018 VarList, Locs, UnresolvedMappers);
2019 }
2020
2021 /// Build a new OpenMP 'from' clause.
2022 ///
2023 /// By default, performs semantic analysis to build the new statement.
2024 /// Subclasses may override this routine to provide different behavior.
2025 OMPClause *
2026 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2027 ArrayRef<SourceLocation> MotionModifiersLoc,
2028 CXXScopeSpec &MapperIdScopeSpec,
2029 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2030 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2031 ArrayRef<Expr *> UnresolvedMappers) {
2032 return getSema().ActOnOpenMPFromClause(
2033 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2034 ColonLoc, VarList, Locs, UnresolvedMappers);
2035 }
2036
2037 /// Build a new OpenMP 'use_device_ptr' clause.
2038 ///
2039 /// By default, performs semantic analysis to build the new OpenMP clause.
2040 /// Subclasses may override this routine to provide different behavior.
2041 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2042 const OMPVarListLocTy &Locs) {
2043 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2044 }
2045
2046 /// Build a new OpenMP 'use_device_addr' clause.
2047 ///
2048 /// By default, performs semantic analysis to build the new OpenMP clause.
2049 /// Subclasses may override this routine to provide different behavior.
2050 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2051 const OMPVarListLocTy &Locs) {
2052 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2053 }
2054
2055 /// Build a new OpenMP 'is_device_ptr' clause.
2056 ///
2057 /// By default, performs semantic analysis to build the new OpenMP clause.
2058 /// Subclasses may override this routine to provide different behavior.
2059 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2060 const OMPVarListLocTy &Locs) {
2061 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2062 }
2063
2064 /// Build a new OpenMP 'defaultmap' clause.
2065 ///
2066 /// By default, performs semantic analysis to build the new OpenMP clause.
2067 /// Subclasses may override this routine to provide different behavior.
2068 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2069 OpenMPDefaultmapClauseKind Kind,
2070 SourceLocation StartLoc,
2071 SourceLocation LParenLoc,
2072 SourceLocation MLoc,
2073 SourceLocation KindLoc,
2074 SourceLocation EndLoc) {
2075 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2076 MLoc, KindLoc, EndLoc);
2077 }
2078
2079 /// Build a new OpenMP 'nontemporal' clause.
2080 ///
2081 /// By default, performs semantic analysis to build the new OpenMP clause.
2082 /// Subclasses may override this routine to provide different behavior.
2083 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2084 SourceLocation StartLoc,
2085 SourceLocation LParenLoc,
2086 SourceLocation EndLoc) {
2087 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2088 EndLoc);
2089 }
2090
2091 /// Build a new OpenMP 'inclusive' clause.
2092 ///
2093 /// By default, performs semantic analysis to build the new OpenMP clause.
2094 /// Subclasses may override this routine to provide different behavior.
2095 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2096 SourceLocation StartLoc,
2097 SourceLocation LParenLoc,
2098 SourceLocation EndLoc) {
2099 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2100 EndLoc);
2101 }
2102
2103 /// Build a new OpenMP 'exclusive' clause.
2104 ///
2105 /// By default, performs semantic analysis to build the new OpenMP clause.
2106 /// Subclasses may override this routine to provide different behavior.
2107 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2108 SourceLocation StartLoc,
2109 SourceLocation LParenLoc,
2110 SourceLocation EndLoc) {
2111 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2112 EndLoc);
2113 }
2114
2115 /// Build a new OpenMP 'uses_allocators' clause.
2116 ///
2117 /// By default, performs semantic analysis to build the new OpenMP clause.
2118 /// Subclasses may override this routine to provide different behavior.
2119 OMPClause *RebuildOMPUsesAllocatorsClause(
2120 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2121 SourceLocation LParenLoc, SourceLocation EndLoc) {
2122 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2123 Data);
2124 }
2125
2126 /// Build a new OpenMP 'affinity' clause.
2127 ///
2128 /// By default, performs semantic analysis to build the new OpenMP clause.
2129 /// Subclasses may override this routine to provide different behavior.
2130 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2131 SourceLocation LParenLoc,
2132 SourceLocation ColonLoc,
2133 SourceLocation EndLoc, Expr *Modifier,
2134 ArrayRef<Expr *> Locators) {
2135 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2136 EndLoc, Modifier, Locators);
2137 }
2138
2139 /// Build a new OpenMP 'order' clause.
2140 ///
2141 /// By default, performs semantic analysis to build the new OpenMP clause.
2142 /// Subclasses may override this routine to provide different behavior.
2143 OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2144 SourceLocation KindKwLoc,
2145 SourceLocation StartLoc,
2146 SourceLocation LParenLoc,
2147 SourceLocation EndLoc) {
2148 return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2149 LParenLoc, EndLoc);
2150 }
2151
2152 /// Rebuild the operand to an Objective-C \@synchronized statement.
2153 ///
2154 /// By default, performs semantic analysis to build the new statement.
2155 /// Subclasses may override this routine to provide different behavior.
2156 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2157 Expr *object) {
2158 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2159 }
2160
2161 /// Build a new Objective-C \@synchronized statement.
2162 ///
2163 /// By default, performs semantic analysis to build the new statement.
2164 /// Subclasses may override this routine to provide different behavior.
2165 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2166 Expr *Object, Stmt *Body) {
2167 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2168 }
2169
2170 /// Build a new Objective-C \@autoreleasepool statement.
2171 ///
2172 /// By default, performs semantic analysis to build the new statement.
2173 /// Subclasses may override this routine to provide different behavior.