Bug Summary

File:clang/lib/Sema/TreeTransform.h
Warning:line 5705, 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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/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/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/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-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -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 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/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/DiagnosticParse.h"
32#include "clang/Basic/OpenMPKinds.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Ownership.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaDiagnostic.h"
39#include "clang/Sema/SemaInternal.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <algorithm>
43
44using namespace llvm::omp;
45
46namespace clang {
47using namespace sema;
48
49/// A semantic tree transformation that allows one to transform one
50/// abstract syntax tree into another.
51///
52/// A new tree transformation is defined by creating a new subclass \c X of
53/// \c TreeTransform<X> and then overriding certain operations to provide
54/// behavior specific to that transformation. For example, template
55/// instantiation is implemented as a tree transformation where the
56/// transformation of TemplateTypeParmType nodes involves substituting the
57/// template arguments for their corresponding template parameters; a similar
58/// transformation is performed for non-type template parameters and
59/// template template parameters.
60///
61/// This tree-transformation template uses static polymorphism to allow
62/// subclasses to customize any of its operations. Thus, a subclass can
63/// override any of the transformation or rebuild operators by providing an
64/// operation with the same signature as the default implementation. The
65/// overriding function should not be virtual.
66///
67/// Semantic tree transformations are split into two stages, either of which
68/// can be replaced by a subclass. The "transform" step transforms an AST node
69/// or the parts of an AST node using the various transformation functions,
70/// then passes the pieces on to the "rebuild" step, which constructs a new AST
71/// node of the appropriate kind from the pieces. The default transformation
72/// routines recursively transform the operands to composite AST nodes (e.g.,
73/// the pointee type of a PointerType node) and, if any of those operand nodes
74/// were changed by the transformation, invokes the rebuild operation to create
75/// a new AST node.
76///
77/// Subclasses can customize the transformation at various levels. The
78/// most coarse-grained transformations involve replacing TransformType(),
79/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
80/// TransformTemplateName(), or TransformTemplateArgument() with entirely
81/// new implementations.
82///
83/// For more fine-grained transformations, subclasses can replace any of the
84/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
85/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
86/// replacing TransformTemplateTypeParmType() allows template instantiation
87/// to substitute template arguments for their corresponding template
88/// parameters. Additionally, subclasses can override the \c RebuildXXX
89/// functions to control how AST nodes are rebuilt when their operands change.
90/// By default, \c TreeTransform will invoke semantic analysis to rebuild
91/// AST nodes. However, certain other tree transformations (e.g, cloning) may
92/// be able to use more efficient rebuild steps.
93///
94/// There are a handful of other functions that can be overridden, allowing one
95/// to avoid traversing nodes that don't need any transformation
96/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
97/// operands have not changed (\c AlwaysRebuild()), and customize the
98/// default locations and entity names used for type-checking
99/// (\c getBaseLocation(), \c getBaseEntity()).
100template<typename Derived>
101class TreeTransform {
102 /// Private RAII object that helps us forget and then re-remember
103 /// the template argument corresponding to a partially-substituted parameter
104 /// pack.
105 class ForgetPartiallySubstitutedPackRAII {
106 Derived &Self;
107 TemplateArgument Old;
108
109 public:
110 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
111 Old = Self.ForgetPartiallySubstitutedPack();
112 }
113
114 ~ForgetPartiallySubstitutedPackRAII() {
115 Self.RememberPartiallySubstitutedPack(Old);
116 }
117 };
118
119protected:
120 Sema &SemaRef;
121
122 /// The set of local declarations that have been transformed, for
123 /// cases where we are forced to build new declarations within the transformer
124 /// rather than in the subclass (e.g., lambda closure types).
125 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
126
127public:
128 /// Initializes a new tree transformer.
129 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
130
131 /// Retrieves a reference to the derived class.
132 Derived &getDerived() { return static_cast<Derived&>(*this); }
133
134 /// Retrieves a reference to the derived class.
135 const Derived &getDerived() const {
136 return static_cast<const Derived&>(*this);
137 }
138
139 static inline ExprResult Owned(Expr *E) { return E; }
140 static inline StmtResult Owned(Stmt *S) { return S; }
141
142 /// Retrieves a reference to the semantic analysis object used for
143 /// this tree transform.
144 Sema &getSema() const { return SemaRef; }
145
146 /// Whether the transformation should always rebuild AST nodes, even
147 /// if none of the children have changed.
148 ///
149 /// Subclasses may override this function to specify when the transformation
150 /// should rebuild all AST nodes.
151 ///
152 /// We must always rebuild all AST nodes when performing variadic template
153 /// pack expansion, in order to avoid violating the AST invariant that each
154 /// statement node appears at most once in its containing declaration.
155 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
156
157 /// Whether the transformation is forming an expression or statement that
158 /// replaces the original. In this case, we'll reuse mangling numbers from
159 /// existing lambdas.
160 bool ReplacingOriginal() { return false; }
161
162 /// Wether CXXConstructExpr can be skipped when they are implicit.
163 /// They will be reconstructed when used if needed.
164 /// This is usefull when the user that cause rebuilding of the
165 /// CXXConstructExpr is outside of the expression at which the TreeTransform
166 /// started.
167 bool AllowSkippingCXXConstructExpr() { return true; }
168
169 /// Returns the location of the entity being transformed, if that
170 /// information was not available elsewhere in the AST.
171 ///
172 /// By default, returns no source-location information. Subclasses can
173 /// provide an alternative implementation that provides better location
174 /// information.
175 SourceLocation getBaseLocation() { return SourceLocation(); }
176
177 /// Returns the name of the entity being transformed, if that
178 /// information was not available elsewhere in the AST.
179 ///
180 /// By default, returns an empty name. Subclasses can provide an alternative
181 /// implementation with a more precise name.
182 DeclarationName getBaseEntity() { return DeclarationName(); }
183
184 /// Sets the "base" location and entity when that
185 /// information is known based on another transformation.
186 ///
187 /// By default, the source location and entity are ignored. Subclasses can
188 /// override this function to provide a customized implementation.
189 void setBase(SourceLocation Loc, DeclarationName Entity) { }
190
191 /// RAII object that temporarily sets the base location and entity
192 /// used for reporting diagnostics in types.
193 class TemporaryBase {
194 TreeTransform &Self;
195 SourceLocation OldLocation;
196 DeclarationName OldEntity;
197
198 public:
199 TemporaryBase(TreeTransform &Self, SourceLocation Location,
200 DeclarationName Entity) : Self(Self) {
201 OldLocation = Self.getDerived().getBaseLocation();
202 OldEntity = Self.getDerived().getBaseEntity();
203
204 if (Location.isValid())
205 Self.getDerived().setBase(Location, Entity);
206 }
207
208 ~TemporaryBase() {
209 Self.getDerived().setBase(OldLocation, OldEntity);
210 }
211 };
212
213 /// Determine whether the given type \p T has already been
214 /// transformed.
215 ///
216 /// Subclasses can provide an alternative implementation of this routine
217 /// to short-circuit evaluation when it is known that a given type will
218 /// not change. For example, template instantiation need not traverse
219 /// non-dependent types.
220 bool AlreadyTransformed(QualType T) {
221 return T.isNull();
222 }
223
224 /// Transform a template parameter depth level.
225 ///
226 /// During a transformation that transforms template parameters, this maps
227 /// an old template parameter depth to a new depth.
228 unsigned TransformTemplateDepth(unsigned Depth) {
229 return Depth;
230 }
231
232 /// Determine whether the given call argument should be dropped, e.g.,
233 /// because it is a default argument.
234 ///
235 /// Subclasses can provide an alternative implementation of this routine to
236 /// determine which kinds of call arguments get dropped. By default,
237 /// CXXDefaultArgument nodes are dropped (prior to transformation).
238 bool DropCallArgument(Expr *E) {
239 return E->isDefaultArgument();
240 }
241
242 /// Determine whether we should expand a pack expansion with the
243 /// given set of parameter packs into separate arguments by repeatedly
244 /// transforming the pattern.
245 ///
246 /// By default, the transformer never tries to expand pack expansions.
247 /// Subclasses can override this routine to provide different behavior.
248 ///
249 /// \param EllipsisLoc The location of the ellipsis that identifies the
250 /// pack expansion.
251 ///
252 /// \param PatternRange The source range that covers the entire pattern of
253 /// the pack expansion.
254 ///
255 /// \param Unexpanded The set of unexpanded parameter packs within the
256 /// pattern.
257 ///
258 /// \param ShouldExpand Will be set to \c true if the transformer should
259 /// expand the corresponding pack expansions into separate arguments. When
260 /// set, \c NumExpansions must also be set.
261 ///
262 /// \param RetainExpansion Whether the caller should add an unexpanded
263 /// pack expansion after all of the expanded arguments. This is used
264 /// when extending explicitly-specified template argument packs per
265 /// C++0x [temp.arg.explicit]p9.
266 ///
267 /// \param NumExpansions The number of separate arguments that will be in
268 /// the expanded form of the corresponding pack expansion. This is both an
269 /// input and an output parameter, which can be set by the caller if the
270 /// number of expansions is known a priori (e.g., due to a prior substitution)
271 /// and will be set by the callee when the number of expansions is known.
272 /// The callee must set this value when \c ShouldExpand is \c true; it may
273 /// set this value in other cases.
274 ///
275 /// \returns true if an error occurred (e.g., because the parameter packs
276 /// are to be instantiated with arguments of different lengths), false
277 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
278 /// must be set.
279 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
280 SourceRange PatternRange,
281 ArrayRef<UnexpandedParameterPack> Unexpanded,
282 bool &ShouldExpand,
283 bool &RetainExpansion,
284 Optional<unsigned> &NumExpansions) {
285 ShouldExpand = false;
286 return false;
287 }
288
289 /// "Forget" about the partially-substituted pack template argument,
290 /// when performing an instantiation that must preserve the parameter pack
291 /// use.
292 ///
293 /// This routine is meant to be overridden by the template instantiator.
294 TemplateArgument ForgetPartiallySubstitutedPack() {
295 return TemplateArgument();
296 }
297
298 /// "Remember" the partially-substituted pack template argument
299 /// after performing an instantiation that must preserve the parameter pack
300 /// use.
301 ///
302 /// This routine is meant to be overridden by the template instantiator.
303 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304
305 /// Note to the derived class when a function parameter pack is
306 /// being expanded.
307 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308
309 /// Transforms the given type into another type.
310 ///
311 /// By default, this routine transforms a type by creating a
312 /// TypeSourceInfo for it and delegating to the appropriate
313 /// function. This is expensive, but we don't mind, because
314 /// this method is deprecated anyway; all users should be
315 /// switched to storing TypeSourceInfos.
316 ///
317 /// \returns the transformed type.
318 QualType TransformType(QualType T);
319
320 /// Transforms the given type-with-location into a new
321 /// type-with-location.
322 ///
323 /// By default, this routine transforms a type by delegating to the
324 /// appropriate TransformXXXType to build a new type. Subclasses
325 /// may override this function (to take over all type
326 /// transformations) or some set of the TransformXXXType functions
327 /// to alter the transformation.
328 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329
330 /// Transform the given type-with-location into a new
331 /// type, collecting location information in the given builder
332 /// as necessary.
333 ///
334 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335
336 /// Transform a type that is permitted to produce a
337 /// DeducedTemplateSpecializationType.
338 ///
339 /// This is used in the (relatively rare) contexts where it is acceptable
340 /// for transformation to produce a class template type with deduced
341 /// template arguments.
342 /// @{
343 QualType TransformTypeWithDeducedTST(QualType T);
344 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345 /// @}
346
347 /// The reason why the value of a statement is not discarded, if any.
348 enum StmtDiscardKind {
349 SDK_Discarded,
350 SDK_NotDiscarded,
351 SDK_StmtExprResult,
352 };
353
354 /// Transform the given statement.
355 ///
356 /// By default, this routine transforms a statement by delegating to the
357 /// appropriate TransformXXXStmt function to transform a specific kind of
358 /// statement or the TransformExpr() function to transform an expression.
359 /// Subclasses may override this function to transform statements using some
360 /// other mechanism.
361 ///
362 /// \returns the transformed statement.
363 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364
365 /// Transform the given statement.
366 ///
367 /// By default, this routine transforms a statement by delegating to the
368 /// appropriate TransformOMPXXXClause function to transform a specific kind
369 /// of clause. Subclasses may override this function to transform statements
370 /// using some other mechanism.
371 ///
372 /// \returns the transformed OpenMP clause.
373 OMPClause *TransformOMPClause(OMPClause *S);
374
375 /// Transform the given attribute.
376 ///
377 /// By default, this routine transforms a statement by delegating to the
378 /// appropriate TransformXXXAttr function to transform a specific kind
379 /// of attribute. Subclasses may override this function to transform
380 /// attributed statements using some other mechanism.
381 ///
382 /// \returns the transformed attribute
383 const Attr *TransformAttr(const Attr *S);
384
385/// Transform the specified attribute.
386///
387/// Subclasses should override the transformation of attributes with a pragma
388/// spelling to transform expressions stored within the attribute.
389///
390/// \returns the transformed attribute.
391#define ATTR(X)
392#define PRAGMA_SPELLING_ATTR(X) \
393 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394#include "clang/Basic/AttrList.inc"
395
396 /// Transform the given expression.
397 ///
398 /// By default, this routine transforms an expression by delegating to the
399 /// appropriate TransformXXXExpr function to build a new expression.
400 /// Subclasses may override this function to transform expressions using some
401 /// other mechanism.
402 ///
403 /// \returns the transformed expression.
404 ExprResult TransformExpr(Expr *E);
405
406 /// Transform the given initializer.
407 ///
408 /// By default, this routine transforms an initializer by stripping off the
409 /// semantic nodes added by initialization, then passing the result to
410 /// TransformExpr or TransformExprs.
411 ///
412 /// \returns the transformed initializer.
413 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414
415 /// Transform the given list of expressions.
416 ///
417 /// This routine transforms a list of expressions by invoking
418 /// \c TransformExpr() for each subexpression. However, it also provides
419 /// support for variadic templates by expanding any pack expansions (if the
420 /// derived class permits such expansion) along the way. When pack expansions
421 /// are present, the number of outputs may not equal the number of inputs.
422 ///
423 /// \param Inputs The set of expressions to be transformed.
424 ///
425 /// \param NumInputs The number of expressions in \c Inputs.
426 ///
427 /// \param IsCall If \c true, then this transform is being performed on
428 /// function-call arguments, and any arguments that should be dropped, will
429 /// be.
430 ///
431 /// \param Outputs The transformed input expressions will be added to this
432 /// vector.
433 ///
434 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435 /// due to transformation.
436 ///
437 /// \returns true if an error occurred, false otherwise.
438 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439 SmallVectorImpl<Expr *> &Outputs,
440 bool *ArgChanged = nullptr);
441
442 /// Transform the given declaration, which is referenced from a type
443 /// or expression.
444 ///
445 /// By default, acts as the identity function on declarations, unless the
446 /// transformer has had to transform the declaration itself. Subclasses
447 /// may override this function to provide alternate behavior.
448 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449 llvm::DenseMap<Decl *, Decl *>::iterator Known
450 = TransformedLocalDecls.find(D);
451 if (Known != TransformedLocalDecls.end())
452 return Known->second;
453
454 return D;
455 }
456
457 /// Transform the specified condition.
458 ///
459 /// By default, this transforms the variable and expression and rebuilds
460 /// the condition.
461 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462 Expr *Expr,
463 Sema::ConditionKind Kind);
464
465 /// Transform the attributes associated with the given declaration and
466 /// place them on the new declaration.
467 ///
468 /// By default, this operation does nothing. Subclasses may override this
469 /// behavior to transform attributes.
470 void transformAttrs(Decl *Old, Decl *New) { }
471
472 /// Note that a local declaration has been transformed by this
473 /// transformer.
474 ///
475 /// Local declarations are typically transformed via a call to
476 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477 /// the transformer itself has to transform the declarations. This routine
478 /// can be overridden by a subclass that keeps track of such mappings.
479 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480 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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 481, __PRETTY_FUNCTION__))
481 "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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 481, __PRETTY_FUNCTION__))
;
482 TransformedLocalDecls[Old] = New.front();
483 }
484
485 /// Transform the definition of the given declaration.
486 ///
487 /// By default, invokes TransformDecl() to transform the declaration.
488 /// Subclasses may override this function to provide alternate behavior.
489 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490 return getDerived().TransformDecl(Loc, D);
491 }
492
493 /// Transform the given declaration, which was the first part of a
494 /// nested-name-specifier in a member access expression.
495 ///
496 /// This specific declaration transformation only applies to the first
497 /// identifier in a nested-name-specifier of a member access expression, e.g.,
498 /// the \c T in \c x->T::member
499 ///
500 /// By default, invokes TransformDecl() to transform the declaration.
501 /// Subclasses may override this function to provide alternate behavior.
502 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504 }
505
506 /// Transform the set of declarations in an OverloadExpr.
507 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508 LookupResult &R);
509
510 /// Transform the given nested-name-specifier with source-location
511 /// information.
512 ///
513 /// By default, transforms all of the types and declarations within the
514 /// nested-name-specifier. Subclasses may override this function to provide
515 /// alternate behavior.
516 NestedNameSpecifierLoc
517 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518 QualType ObjectType = QualType(),
519 NamedDecl *FirstQualifierInScope = nullptr);
520
521 /// Transform the given declaration name.
522 ///
523 /// By default, transforms the types of conversion function, constructor,
524 /// and destructor names and then (if needed) rebuilds the declaration name.
525 /// Identifiers and selectors are returned unmodified. Sublcasses may
526 /// override this function to provide alternate behavior.
527 DeclarationNameInfo
528 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529
530 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532 concepts::TypeRequirement *
533 TransformTypeRequirement(concepts::TypeRequirement *Req);
534 concepts::ExprRequirement *
535 TransformExprRequirement(concepts::ExprRequirement *Req);
536 concepts::NestedRequirement *
537 TransformNestedRequirement(concepts::NestedRequirement *Req);
538
539 /// Transform the given template name.
540 ///
541 /// \param SS The nested-name-specifier that qualifies the template
542 /// name. This nested-name-specifier must already have been transformed.
543 ///
544 /// \param Name The template name to transform.
545 ///
546 /// \param NameLoc The source location of the template name.
547 ///
548 /// \param ObjectType If we're translating a template name within a member
549 /// access expression, this is the type of the object whose member template
550 /// is being referenced.
551 ///
552 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553 /// also refers to a name within the current (lexical) scope, this is the
554 /// declaration it refers to.
555 ///
556 /// By default, transforms the template name by transforming the declarations
557 /// and nested-name-specifiers that occur within the template name.
558 /// Subclasses may override this function to provide alternate behavior.
559 TemplateName
560 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561 SourceLocation NameLoc,
562 QualType ObjectType = QualType(),
563 NamedDecl *FirstQualifierInScope = nullptr,
564 bool AllowInjectedClassName = false);
565
566 /// Transform the given template argument.
567 ///
568 /// By default, this operation transforms the type, expression, or
569 /// declaration stored within the template argument and constructs a
570 /// new template argument from the transformed result. Subclasses may
571 /// override this function to provide alternate behavior.
572 ///
573 /// Returns true if there was an error.
574 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575 TemplateArgumentLoc &Output,
576 bool Uneval = false);
577
578 /// Transform the given set of template arguments.
579 ///
580 /// By default, this operation transforms all of the template arguments
581 /// in the input set using \c TransformTemplateArgument(), and appends
582 /// the transformed arguments to the output list.
583 ///
584 /// Note that this overload of \c TransformTemplateArguments() is merely
585 /// a convenience function. Subclasses that wish to override this behavior
586 /// should override the iterator-based member template version.
587 ///
588 /// \param Inputs The set of template arguments to be transformed.
589 ///
590 /// \param NumInputs The number of template arguments in \p Inputs.
591 ///
592 /// \param Outputs The set of transformed template arguments output by this
593 /// routine.
594 ///
595 /// Returns true if an error occurred.
596 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597 unsigned NumInputs,
598 TemplateArgumentListInfo &Outputs,
599 bool Uneval = false) {
600 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601 Uneval);
602 }
603
604 /// Transform the given set of template arguments.
605 ///
606 /// By default, this operation transforms all of the template arguments
607 /// in the input set using \c TransformTemplateArgument(), and appends
608 /// the transformed arguments to the output list.
609 ///
610 /// \param First An iterator to the first template argument.
611 ///
612 /// \param Last An iterator one step past the last template argument.
613 ///
614 /// \param Outputs The set of transformed template arguments output by this
615 /// routine.
616 ///
617 /// Returns true if an error occurred.
618 template<typename InputIterator>
619 bool TransformTemplateArguments(InputIterator First,
620 InputIterator Last,
621 TemplateArgumentListInfo &Outputs,
622 bool Uneval = false);
623
624 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626 TemplateArgumentLoc &ArgLoc);
627
628 /// Fakes up a TypeSourceInfo for a type.
629 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630 return SemaRef.Context.getTrivialTypeSourceInfo(T,
631 getDerived().getBaseLocation());
632 }
633
634#define ABSTRACT_TYPELOC(CLASS, PARENT)
635#define TYPELOC(CLASS, PARENT) \
636 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637#include "clang/AST/TypeLocNodes.def"
638
639 template<typename Fn>
640 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
641 FunctionProtoTypeLoc TL,
642 CXXRecordDecl *ThisContext,
643 Qualifiers ThisTypeQuals,
644 Fn TransformExceptionSpec);
645
646 bool TransformExceptionSpec(SourceLocation Loc,
647 FunctionProtoType::ExceptionSpecInfo &ESI,
648 SmallVectorImpl<QualType> &Exceptions,
649 bool &Changed);
650
651 StmtResult TransformSEHHandler(Stmt *Handler);
652
653 QualType
654 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
655 TemplateSpecializationTypeLoc TL,
656 TemplateName Template);
657
658 QualType
659 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
660 DependentTemplateSpecializationTypeLoc TL,
661 TemplateName Template,
662 CXXScopeSpec &SS);
663
664 QualType TransformDependentTemplateSpecializationType(
665 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
666 NestedNameSpecifierLoc QualifierLoc);
667
668 /// Transforms the parameters of a function type into the
669 /// given vectors.
670 ///
671 /// The result vectors should be kept in sync; null entries in the
672 /// variables vector are acceptable.
673 ///
674 /// Return true on error.
675 bool TransformFunctionTypeParams(
676 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
677 const QualType *ParamTypes,
678 const FunctionProtoType::ExtParameterInfo *ParamInfos,
679 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
680 Sema::ExtParameterInfoBuilder &PInfos);
681
682 /// Transforms a single function-type parameter. Return null
683 /// on error.
684 ///
685 /// \param indexAdjustment - A number to add to the parameter's
686 /// scope index; can be negative
687 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
688 int indexAdjustment,
689 Optional<unsigned> NumExpansions,
690 bool ExpectParameterPack);
691
692 /// Transform the body of a lambda-expression.
693 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
694 /// Alternative implementation of TransformLambdaBody that skips transforming
695 /// the body.
696 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
697
698 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
699
700 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
701 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
702
703 TemplateParameterList *TransformTemplateParameterList(
704 TemplateParameterList *TPL) {
705 return TPL;
706 }
707
708 ExprResult TransformAddressOfOperand(Expr *E);
709
710 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
711 bool IsAddressOfOperand,
712 TypeSourceInfo **RecoveryTSI);
713
714 ExprResult TransformParenDependentScopeDeclRefExpr(
715 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
716 TypeSourceInfo **RecoveryTSI);
717
718 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
719
720// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
721// amount of stack usage with clang.
722#define STMT(Node, Parent) \
723 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
724 StmtResult Transform##Node(Node *S);
725#define VALUESTMT(Node, Parent) \
726 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
727 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
728#define EXPR(Node, Parent) \
729 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
730 ExprResult Transform##Node(Node *E);
731#define ABSTRACT_STMT(Stmt)
732#include "clang/AST/StmtNodes.inc"
733
734#define GEN_CLANG_CLAUSE_CLASS
735#define CLAUSE_CLASS(Enum, Str, Class) \
736 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
737 OMPClause *Transform##Class(Class *S);
738#include "llvm/Frontend/OpenMP/OMP.inc"
739
740 /// Build a new qualified type given its unqualified type and type location.
741 ///
742 /// By default, this routine adds type qualifiers only to types that can
743 /// have qualifiers, and silently suppresses those qualifiers that are not
744 /// permitted. Subclasses may override this routine to provide different
745 /// behavior.
746 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
747
748 /// Build a new pointer type given its pointee type.
749 ///
750 /// By default, performs semantic analysis when building the pointer type.
751 /// Subclasses may override this routine to provide different behavior.
752 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
753
754 /// Build a new block pointer type given its pointee type.
755 ///
756 /// By default, performs semantic analysis when building the block pointer
757 /// type. Subclasses may override this routine to provide different behavior.
758 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
759
760 /// Build a new reference type given the type it references.
761 ///
762 /// By default, performs semantic analysis when building the
763 /// reference type. Subclasses may override this routine to provide
764 /// different behavior.
765 ///
766 /// \param LValue whether the type was written with an lvalue sigil
767 /// or an rvalue sigil.
768 QualType RebuildReferenceType(QualType ReferentType,
769 bool LValue,
770 SourceLocation Sigil);
771
772 /// Build a new member pointer type given the pointee type and the
773 /// class type it refers into.
774 ///
775 /// By default, performs semantic analysis when building the member pointer
776 /// type. Subclasses may override this routine to provide different behavior.
777 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
778 SourceLocation Sigil);
779
780 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
781 SourceLocation ProtocolLAngleLoc,
782 ArrayRef<ObjCProtocolDecl *> Protocols,
783 ArrayRef<SourceLocation> ProtocolLocs,
784 SourceLocation ProtocolRAngleLoc);
785
786 /// Build an Objective-C object type.
787 ///
788 /// By default, performs semantic analysis when building the object type.
789 /// Subclasses may override this routine to provide different behavior.
790 QualType RebuildObjCObjectType(QualType BaseType,
791 SourceLocation Loc,
792 SourceLocation TypeArgsLAngleLoc,
793 ArrayRef<TypeSourceInfo *> TypeArgs,
794 SourceLocation TypeArgsRAngleLoc,
795 SourceLocation ProtocolLAngleLoc,
796 ArrayRef<ObjCProtocolDecl *> Protocols,
797 ArrayRef<SourceLocation> ProtocolLocs,
798 SourceLocation ProtocolRAngleLoc);
799
800 /// Build a new Objective-C object pointer type given the pointee type.
801 ///
802 /// By default, directly builds the pointer type, with no additional semantic
803 /// analysis.
804 QualType RebuildObjCObjectPointerType(QualType PointeeType,
805 SourceLocation Star);
806
807 /// Build a new array type given the element type, size
808 /// modifier, size of the array (if known), size expression, and index type
809 /// qualifiers.
810 ///
811 /// By default, performs semantic analysis when building the array type.
812 /// Subclasses may override this routine to provide different behavior.
813 /// Also by default, all of the other Rebuild*Array
814 QualType RebuildArrayType(QualType ElementType,
815 ArrayType::ArraySizeModifier SizeMod,
816 const llvm::APInt *Size,
817 Expr *SizeExpr,
818 unsigned IndexTypeQuals,
819 SourceRange BracketsRange);
820
821 /// Build a new constant array type given the element type, size
822 /// modifier, (known) size of the array, and index type qualifiers.
823 ///
824 /// By default, performs semantic analysis when building the array type.
825 /// Subclasses may override this routine to provide different behavior.
826 QualType RebuildConstantArrayType(QualType ElementType,
827 ArrayType::ArraySizeModifier SizeMod,
828 const llvm::APInt &Size,
829 Expr *SizeExpr,
830 unsigned IndexTypeQuals,
831 SourceRange BracketsRange);
832
833 /// Build a new incomplete array type given the element type, size
834 /// modifier, and index type qualifiers.
835 ///
836 /// By default, performs semantic analysis when building the array type.
837 /// Subclasses may override this routine to provide different behavior.
838 QualType RebuildIncompleteArrayType(QualType ElementType,
839 ArrayType::ArraySizeModifier SizeMod,
840 unsigned IndexTypeQuals,
841 SourceRange BracketsRange);
842
843 /// Build a new variable-length array type given the element type,
844 /// size modifier, size expression, and index type qualifiers.
845 ///
846 /// By default, performs semantic analysis when building the array type.
847 /// Subclasses may override this routine to provide different behavior.
848 QualType RebuildVariableArrayType(QualType ElementType,
849 ArrayType::ArraySizeModifier SizeMod,
850 Expr *SizeExpr,
851 unsigned IndexTypeQuals,
852 SourceRange BracketsRange);
853
854 /// Build a new dependent-sized array type given the element type,
855 /// size modifier, size expression, and index type qualifiers.
856 ///
857 /// By default, performs semantic analysis when building the array type.
858 /// Subclasses may override this routine to provide different behavior.
859 QualType RebuildDependentSizedArrayType(QualType ElementType,
860 ArrayType::ArraySizeModifier SizeMod,
861 Expr *SizeExpr,
862 unsigned IndexTypeQuals,
863 SourceRange BracketsRange);
864
865 /// Build a new vector type given the element type and
866 /// number of elements.
867 ///
868 /// By default, performs semantic analysis when building the vector type.
869 /// Subclasses may override this routine to provide different behavior.
870 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
871 VectorType::VectorKind VecKind);
872
873 /// Build a new potentially dependently-sized extended vector type
874 /// given the element type and number of elements.
875 ///
876 /// By default, performs semantic analysis when building the vector type.
877 /// Subclasses may override this routine to provide different behavior.
878 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
879 SourceLocation AttributeLoc,
880 VectorType::VectorKind);
881
882 /// Build a new extended vector type given the element type and
883 /// number of elements.
884 ///
885 /// By default, performs semantic analysis when building the vector type.
886 /// Subclasses may override this routine to provide different behavior.
887 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
888 SourceLocation AttributeLoc);
889
890 /// Build a new potentially dependently-sized extended vector type
891 /// given the element type and number of elements.
892 ///
893 /// By default, performs semantic analysis when building the vector type.
894 /// Subclasses may override this routine to provide different behavior.
895 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
896 Expr *SizeExpr,
897 SourceLocation AttributeLoc);
898
899 /// Build a new matrix type given the element type and dimensions.
900 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
901 unsigned NumColumns);
902
903 /// Build a new matrix type given the type and dependently-defined
904 /// dimensions.
905 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
906 Expr *ColumnExpr,
907 SourceLocation AttributeLoc);
908
909 /// Build a new DependentAddressSpaceType or return the pointee
910 /// type variable with the correct address space (retrieved from
911 /// AddrSpaceExpr) applied to it. The former will be returned in cases
912 /// where the address space remains dependent.
913 ///
914 /// By default, performs semantic analysis when building the type with address
915 /// space applied. Subclasses may override this routine to provide different
916 /// behavior.
917 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
918 Expr *AddrSpaceExpr,
919 SourceLocation AttributeLoc);
920
921 /// Build a new function type.
922 ///
923 /// By default, performs semantic analysis when building the function type.
924 /// Subclasses may override this routine to provide different behavior.
925 QualType RebuildFunctionProtoType(QualType T,
926 MutableArrayRef<QualType> ParamTypes,
927 const FunctionProtoType::ExtProtoInfo &EPI);
928
929 /// Build a new unprototyped function type.
930 QualType RebuildFunctionNoProtoType(QualType ResultType);
931
932 /// Rebuild an unresolved typename type, given the decl that
933 /// the UnresolvedUsingTypenameDecl was transformed to.
934 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
935
936 /// Build a new typedef type.
937 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
938 return SemaRef.Context.getTypeDeclType(Typedef);
939 }
940
941 /// Build a new MacroDefined type.
942 QualType RebuildMacroQualifiedType(QualType T,
943 const IdentifierInfo *MacroII) {
944 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
945 }
946
947 /// Build a new class/struct/union type.
948 QualType RebuildRecordType(RecordDecl *Record) {
949 return SemaRef.Context.getTypeDeclType(Record);
950 }
951
952 /// Build a new Enum type.
953 QualType RebuildEnumType(EnumDecl *Enum) {
954 return SemaRef.Context.getTypeDeclType(Enum);
955 }
956
957 /// Build a new typeof(expr) type.
958 ///
959 /// By default, performs semantic analysis when building the typeof type.
960 /// Subclasses may override this routine to provide different behavior.
961 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
962
963 /// Build a new typeof(type) type.
964 ///
965 /// By default, builds a new TypeOfType with the given underlying type.
966 QualType RebuildTypeOfType(QualType Underlying);
967
968 /// Build a new unary transform type.
969 QualType RebuildUnaryTransformType(QualType BaseType,
970 UnaryTransformType::UTTKind UKind,
971 SourceLocation Loc);
972
973 /// Build a new C++11 decltype type.
974 ///
975 /// By default, performs semantic analysis when building the decltype type.
976 /// Subclasses may override this routine to provide different behavior.
977 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
978
979 /// Build a new C++11 auto type.
980 ///
981 /// By default, builds a new AutoType with the given deduced type.
982 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
983 ConceptDecl *TypeConstraintConcept,
984 ArrayRef<TemplateArgument> TypeConstraintArgs) {
985 // Note, IsDependent is always false here: we implicitly convert an 'auto'
986 // which has been deduced to a dependent type into an undeduced 'auto', so
987 // that we'll retry deduction after the transformation.
988 return SemaRef.Context.getAutoType(Deduced, Keyword,
989 /*IsDependent*/ false, /*IsPack=*/false,
990 TypeConstraintConcept,
991 TypeConstraintArgs);
992 }
993
994 /// By default, builds a new DeducedTemplateSpecializationType with the given
995 /// deduced type.
996 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
997 QualType Deduced) {
998 return SemaRef.Context.getDeducedTemplateSpecializationType(
999 Template, Deduced, /*IsDependent*/ false);
1000 }
1001
1002 /// Build a new template specialization type.
1003 ///
1004 /// By default, performs semantic analysis when building the template
1005 /// specialization type. Subclasses may override this routine to provide
1006 /// different behavior.
1007 QualType RebuildTemplateSpecializationType(TemplateName Template,
1008 SourceLocation TemplateLoc,
1009 TemplateArgumentListInfo &Args);
1010
1011 /// Build a new parenthesized type.
1012 ///
1013 /// By default, builds a new ParenType type from the inner type.
1014 /// Subclasses may override this routine to provide different behavior.
1015 QualType RebuildParenType(QualType InnerType) {
1016 return SemaRef.BuildParenType(InnerType);
1017 }
1018
1019 /// Build a new qualified name type.
1020 ///
1021 /// By default, builds a new ElaboratedType type from the keyword,
1022 /// the nested-name-specifier and the named type.
1023 /// Subclasses may override this routine to provide different behavior.
1024 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1025 ElaboratedTypeKeyword Keyword,
1026 NestedNameSpecifierLoc QualifierLoc,
1027 QualType Named) {
1028 return SemaRef.Context.getElaboratedType(Keyword,
1029 QualifierLoc.getNestedNameSpecifier(),
1030 Named);
1031 }
1032
1033 /// Build a new typename type that refers to a template-id.
1034 ///
1035 /// By default, builds a new DependentNameType type from the
1036 /// nested-name-specifier and the given type. Subclasses may override
1037 /// this routine to provide different behavior.
1038 QualType RebuildDependentTemplateSpecializationType(
1039 ElaboratedTypeKeyword Keyword,
1040 NestedNameSpecifierLoc QualifierLoc,
1041 SourceLocation TemplateKWLoc,
1042 const IdentifierInfo *Name,
1043 SourceLocation NameLoc,
1044 TemplateArgumentListInfo &Args,
1045 bool AllowInjectedClassName) {
1046 // Rebuild the template name.
1047 // TODO: avoid TemplateName abstraction
1048 CXXScopeSpec SS;
1049 SS.Adopt(QualifierLoc);
1050 TemplateName InstName = getDerived().RebuildTemplateName(
1051 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1052 AllowInjectedClassName);
1053
1054 if (InstName.isNull())
1055 return QualType();
1056
1057 // If it's still dependent, make a dependent specialization.
1058 if (InstName.getAsDependentTemplateName())
1059 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1060 QualifierLoc.getNestedNameSpecifier(),
1061 Name,
1062 Args);
1063
1064 // Otherwise, make an elaborated type wrapping a non-dependent
1065 // specialization.
1066 QualType T =
1067 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1068 if (T.isNull()) return QualType();
1069
1070 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1071 return T;
1072
1073 return SemaRef.Context.getElaboratedType(Keyword,
1074 QualifierLoc.getNestedNameSpecifier(),
1075 T);
1076 }
1077
1078 /// Build a new typename type that refers to an identifier.
1079 ///
1080 /// By default, performs semantic analysis when building the typename type
1081 /// (or elaborated type). Subclasses may override this routine to provide
1082 /// different behavior.
1083 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1084 SourceLocation KeywordLoc,
1085 NestedNameSpecifierLoc QualifierLoc,
1086 const IdentifierInfo *Id,
1087 SourceLocation IdLoc,
1088 bool DeducedTSTContext) {
1089 CXXScopeSpec SS;
1090 SS.Adopt(QualifierLoc);
1091
1092 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1093 // If the name is still dependent, just build a new dependent name type.
1094 if (!SemaRef.computeDeclContext(SS))
1095 return SemaRef.Context.getDependentNameType(Keyword,
1096 QualifierLoc.getNestedNameSpecifier(),
1097 Id);
1098 }
1099
1100 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1101 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1102 *Id, IdLoc, DeducedTSTContext);
1103 }
1104
1105 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1106
1107 // We had a dependent elaborated-type-specifier that has been transformed
1108 // into a non-dependent elaborated-type-specifier. Find the tag we're
1109 // referring to.
1110 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1111 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1112 if (!DC)
1113 return QualType();
1114
1115 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1116 return QualType();
1117
1118 TagDecl *Tag = nullptr;
1119 SemaRef.LookupQualifiedName(Result, DC);
1120 switch (Result.getResultKind()) {
1121 case LookupResult::NotFound:
1122 case LookupResult::NotFoundInCurrentInstantiation:
1123 break;
1124
1125 case LookupResult::Found:
1126 Tag = Result.getAsSingle<TagDecl>();
1127 break;
1128
1129 case LookupResult::FoundOverloaded:
1130 case LookupResult::FoundUnresolvedValue:
1131 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 1131)
;
1132
1133 case LookupResult::Ambiguous:
1134 // Let the LookupResult structure handle ambiguities.
1135 return QualType();
1136 }
1137
1138 if (!Tag) {
1139 // Check where the name exists but isn't a tag type and use that to emit
1140 // better diagnostics.
1141 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1142 SemaRef.LookupQualifiedName(Result, DC);
1143 switch (Result.getResultKind()) {
1144 case LookupResult::Found:
1145 case LookupResult::FoundOverloaded:
1146 case LookupResult::FoundUnresolvedValue: {
1147 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1148 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1149 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1150 << NTK << Kind;
1151 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1152 break;
1153 }
1154 default:
1155 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1156 << Kind << Id << DC << QualifierLoc.getSourceRange();
1157 break;
1158 }
1159 return QualType();
1160 }
1161
1162 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1163 IdLoc, Id)) {
1164 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1165 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1166 return QualType();
1167 }
1168
1169 // Build the elaborated-type-specifier type.
1170 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1171 return SemaRef.Context.getElaboratedType(Keyword,
1172 QualifierLoc.getNestedNameSpecifier(),
1173 T);
1174 }
1175
1176 /// Build a new pack expansion type.
1177 ///
1178 /// By default, builds a new PackExpansionType type from the given pattern.
1179 /// Subclasses may override this routine to provide different behavior.
1180 QualType RebuildPackExpansionType(QualType Pattern,
1181 SourceRange PatternRange,
1182 SourceLocation EllipsisLoc,
1183 Optional<unsigned> NumExpansions) {
1184 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1185 NumExpansions);
1186 }
1187
1188 /// Build a new atomic type given its value type.
1189 ///
1190 /// By default, performs semantic analysis when building the atomic type.
1191 /// Subclasses may override this routine to provide different behavior.
1192 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1193
1194 /// Build a new pipe type given its value type.
1195 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1196 bool isReadPipe);
1197
1198 /// Build an extended int given its value type.
1199 QualType RebuildExtIntType(bool IsUnsigned, unsigned NumBits,
1200 SourceLocation Loc);
1201
1202 /// Build a dependent extended int given its value type.
1203 QualType RebuildDependentExtIntType(bool IsUnsigned, Expr *NumBitsExpr,
1204 SourceLocation Loc);
1205
1206 /// Build a new template name given a nested name specifier, a flag
1207 /// indicating whether the "template" keyword was provided, and the template
1208 /// that the template name refers to.
1209 ///
1210 /// By default, builds the new template name directly. Subclasses may override
1211 /// this routine to provide different behavior.
1212 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1213 bool TemplateKW,
1214 TemplateDecl *Template);
1215
1216 /// Build a new template name given a nested name specifier and the
1217 /// name that is referred to as a template.
1218 ///
1219 /// By default, performs semantic analysis to determine whether the name can
1220 /// be resolved to a specific template, then builds the appropriate kind of
1221 /// template name. Subclasses may override this routine to provide different
1222 /// behavior.
1223 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1224 SourceLocation TemplateKWLoc,
1225 const IdentifierInfo &Name,
1226 SourceLocation NameLoc, QualType ObjectType,
1227 NamedDecl *FirstQualifierInScope,
1228 bool AllowInjectedClassName);
1229
1230 /// Build a new template name given a nested name specifier and the
1231 /// overloaded operator name that is referred to as a template.
1232 ///
1233 /// By default, performs semantic analysis to determine whether the name can
1234 /// be resolved to a specific template, then builds the appropriate kind of
1235 /// template name. Subclasses may override this routine to provide different
1236 /// behavior.
1237 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1238 SourceLocation TemplateKWLoc,
1239 OverloadedOperatorKind Operator,
1240 SourceLocation NameLoc, QualType ObjectType,
1241 bool AllowInjectedClassName);
1242
1243 /// Build a new template name given a template template parameter pack
1244 /// and the
1245 ///
1246 /// By default, performs semantic analysis to determine whether the name can
1247 /// be resolved to a specific template, then builds the appropriate kind of
1248 /// template name. Subclasses may override this routine to provide different
1249 /// behavior.
1250 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1251 const TemplateArgument &ArgPack) {
1252 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1253 }
1254
1255 /// Build a new compound statement.
1256 ///
1257 /// By default, performs semantic analysis to build the new statement.
1258 /// Subclasses may override this routine to provide different behavior.
1259 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1260 MultiStmtArg Statements,
1261 SourceLocation RBraceLoc,
1262 bool IsStmtExpr) {
1263 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1264 IsStmtExpr);
1265 }
1266
1267 /// Build a new case statement.
1268 ///
1269 /// By default, performs semantic analysis to build the new statement.
1270 /// Subclasses may override this routine to provide different behavior.
1271 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1272 Expr *LHS,
1273 SourceLocation EllipsisLoc,
1274 Expr *RHS,
1275 SourceLocation ColonLoc) {
1276 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1277 ColonLoc);
1278 }
1279
1280 /// Attach the body to a new case statement.
1281 ///
1282 /// By default, performs semantic analysis to build the new statement.
1283 /// Subclasses may override this routine to provide different behavior.
1284 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1285 getSema().ActOnCaseStmtBody(S, Body);
1286 return S;
1287 }
1288
1289 /// Build a new default statement.
1290 ///
1291 /// By default, performs semantic analysis to build the new statement.
1292 /// Subclasses may override this routine to provide different behavior.
1293 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1294 SourceLocation ColonLoc,
1295 Stmt *SubStmt) {
1296 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1297 /*CurScope=*/nullptr);
1298 }
1299
1300 /// Build a new label statement.
1301 ///
1302 /// By default, performs semantic analysis to build the new statement.
1303 /// Subclasses may override this routine to provide different behavior.
1304 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1305 SourceLocation ColonLoc, Stmt *SubStmt) {
1306 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1307 }
1308
1309 /// Build a new attributed statement.
1310 ///
1311 /// By default, performs semantic analysis to build the new statement.
1312 /// Subclasses may override this routine to provide different behavior.
1313 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1314 ArrayRef<const Attr *> Attrs,
1315 Stmt *SubStmt) {
1316 return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1317 }
1318
1319 /// Build a new "if" statement.
1320 ///
1321 /// By default, performs semantic analysis to build the new statement.
1322 /// Subclasses may override this routine to provide different behavior.
1323 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1324 SourceLocation LParenLoc, Sema::ConditionResult Cond,
1325 SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1326 SourceLocation ElseLoc, Stmt *Else) {
1327 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, LParenLoc, Init, Cond,
1328 RParenLoc, Then, ElseLoc, Else);
1329 }
1330
1331 /// Start building a new switch statement.
1332 ///
1333 /// By default, performs semantic analysis to build the new statement.
1334 /// Subclasses may override this routine to provide different behavior.
1335 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1336 SourceLocation LParenLoc, Stmt *Init,
1337 Sema::ConditionResult Cond,
1338 SourceLocation RParenLoc) {
1339 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1340 RParenLoc);
1341 }
1342
1343 /// Attach the body to the switch statement.
1344 ///
1345 /// By default, performs semantic analysis to build the new statement.
1346 /// Subclasses may override this routine to provide different behavior.
1347 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1348 Stmt *Switch, Stmt *Body) {
1349 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1350 }
1351
1352 /// Build a new while statement.
1353 ///
1354 /// By default, performs semantic analysis to build the new statement.
1355 /// Subclasses may override this routine to provide different behavior.
1356 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1357 Sema::ConditionResult Cond,
1358 SourceLocation RParenLoc, Stmt *Body) {
1359 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1360 }
1361
1362 /// Build a new do-while statement.
1363 ///
1364 /// By default, performs semantic analysis to build the new statement.
1365 /// Subclasses may override this routine to provide different behavior.
1366 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1367 SourceLocation WhileLoc, SourceLocation LParenLoc,
1368 Expr *Cond, SourceLocation RParenLoc) {
1369 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1370 Cond, RParenLoc);
1371 }
1372
1373 /// Build a new for statement.
1374 ///
1375 /// By default, performs semantic analysis to build the new statement.
1376 /// Subclasses may override this routine to provide different behavior.
1377 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1378 Stmt *Init, Sema::ConditionResult Cond,
1379 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1380 Stmt *Body) {
1381 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1382 Inc, RParenLoc, Body);
1383 }
1384
1385 /// Build a new goto statement.
1386 ///
1387 /// By default, performs semantic analysis to build the new statement.
1388 /// Subclasses may override this routine to provide different behavior.
1389 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1390 LabelDecl *Label) {
1391 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1392 }
1393
1394 /// Build a new indirect goto statement.
1395 ///
1396 /// By default, performs semantic analysis to build the new statement.
1397 /// Subclasses may override this routine to provide different behavior.
1398 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1399 SourceLocation StarLoc,
1400 Expr *Target) {
1401 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1402 }
1403
1404 /// Build a new return statement.
1405 ///
1406 /// By default, performs semantic analysis to build the new statement.
1407 /// Subclasses may override this routine to provide different behavior.
1408 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1409 return getSema().BuildReturnStmt(ReturnLoc, Result);
1410 }
1411
1412 /// Build a new declaration statement.
1413 ///
1414 /// By default, performs semantic analysis to build the new statement.
1415 /// Subclasses may override this routine to provide different behavior.
1416 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1417 SourceLocation StartLoc, SourceLocation EndLoc) {
1418 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1419 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1420 }
1421
1422 /// Build a new inline asm statement.
1423 ///
1424 /// By default, performs semantic analysis to build the new statement.
1425 /// Subclasses may override this routine to provide different behavior.
1426 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1427 bool IsVolatile, unsigned NumOutputs,
1428 unsigned NumInputs, IdentifierInfo **Names,
1429 MultiExprArg Constraints, MultiExprArg Exprs,
1430 Expr *AsmString, MultiExprArg Clobbers,
1431 unsigned NumLabels,
1432 SourceLocation RParenLoc) {
1433 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1434 NumInputs, Names, Constraints, Exprs,
1435 AsmString, Clobbers, NumLabels, RParenLoc);
1436 }
1437
1438 /// Build a new MS style inline asm statement.
1439 ///
1440 /// By default, performs semantic analysis to build the new statement.
1441 /// Subclasses may override this routine to provide different behavior.
1442 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1443 ArrayRef<Token> AsmToks,
1444 StringRef AsmString,
1445 unsigned NumOutputs, unsigned NumInputs,
1446 ArrayRef<StringRef> Constraints,
1447 ArrayRef<StringRef> Clobbers,
1448 ArrayRef<Expr*> Exprs,
1449 SourceLocation EndLoc) {
1450 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1451 NumOutputs, NumInputs,
1452 Constraints, Clobbers, Exprs, EndLoc);
1453 }
1454
1455 /// Build a new co_return statement.
1456 ///
1457 /// By default, performs semantic analysis to build the new statement.
1458 /// Subclasses may override this routine to provide different behavior.
1459 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1460 bool IsImplicit) {
1461 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1462 }
1463
1464 /// Build a new co_await expression.
1465 ///
1466 /// By default, performs semantic analysis to build the new expression.
1467 /// Subclasses may override this routine to provide different behavior.
1468 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1469 bool IsImplicit) {
1470 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1471 }
1472
1473 /// Build a new co_await expression.
1474 ///
1475 /// By default, performs semantic analysis to build the new expression.
1476 /// Subclasses may override this routine to provide different behavior.
1477 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1478 Expr *Result,
1479 UnresolvedLookupExpr *Lookup) {
1480 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1481 }
1482
1483 /// Build a new co_yield expression.
1484 ///
1485 /// By default, performs semantic analysis to build the new expression.
1486 /// Subclasses may override this routine to provide different behavior.
1487 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1488 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1489 }
1490
1491 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1492 return getSema().BuildCoroutineBodyStmt(Args);
1493 }
1494
1495 /// Build a new Objective-C \@try statement.
1496 ///
1497 /// By default, performs semantic analysis to build the new statement.
1498 /// Subclasses may override this routine to provide different behavior.
1499 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1500 Stmt *TryBody,
1501 MultiStmtArg CatchStmts,
1502 Stmt *Finally) {
1503 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1504 Finally);
1505 }
1506
1507 /// Rebuild an Objective-C exception declaration.
1508 ///
1509 /// By default, performs semantic analysis to build the new declaration.
1510 /// Subclasses may override this routine to provide different behavior.
1511 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1512 TypeSourceInfo *TInfo, QualType T) {
1513 return getSema().BuildObjCExceptionDecl(TInfo, T,
1514 ExceptionDecl->getInnerLocStart(),
1515 ExceptionDecl->getLocation(),
1516 ExceptionDecl->getIdentifier());
1517 }
1518
1519 /// Build a new Objective-C \@catch statement.
1520 ///
1521 /// By default, performs semantic analysis to build the new statement.
1522 /// Subclasses may override this routine to provide different behavior.
1523 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1524 SourceLocation RParenLoc,
1525 VarDecl *Var,
1526 Stmt *Body) {
1527 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1528 Var, Body);
1529 }
1530
1531 /// Build a new Objective-C \@finally statement.
1532 ///
1533 /// By default, performs semantic analysis to build the new statement.
1534 /// Subclasses may override this routine to provide different behavior.
1535 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1536 Stmt *Body) {
1537 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1538 }
1539
1540 /// Build a new Objective-C \@throw statement.
1541 ///
1542 /// By default, performs semantic analysis to build the new statement.
1543 /// Subclasses may override this routine to provide different behavior.
1544 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1545 Expr *Operand) {
1546 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1547 }
1548
1549 /// Build a new OpenMP Canonical loop.
1550 ///
1551 /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1552 /// OMPCanonicalLoop.
1553 StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1554 return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1555 }
1556
1557 /// Build a new OpenMP executable directive.
1558 ///
1559 /// By default, performs semantic analysis to build the new statement.
1560 /// Subclasses may override this routine to provide different behavior.
1561 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1562 DeclarationNameInfo DirName,
1563 OpenMPDirectiveKind CancelRegion,
1564 ArrayRef<OMPClause *> Clauses,
1565 Stmt *AStmt, SourceLocation StartLoc,
1566 SourceLocation EndLoc) {
1567 return getSema().ActOnOpenMPExecutableDirective(
1568 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1569 }
1570
1571 /// Build a new OpenMP 'if' clause.
1572 ///
1573 /// By default, performs semantic analysis to build the new OpenMP clause.
1574 /// Subclasses may override this routine to provide different behavior.
1575 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1576 Expr *Condition, SourceLocation StartLoc,
1577 SourceLocation LParenLoc,
1578 SourceLocation NameModifierLoc,
1579 SourceLocation ColonLoc,
1580 SourceLocation EndLoc) {
1581 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1582 LParenLoc, NameModifierLoc, ColonLoc,
1583 EndLoc);
1584 }
1585
1586 /// Build a new OpenMP 'final' clause.
1587 ///
1588 /// By default, performs semantic analysis to build the new OpenMP clause.
1589 /// Subclasses may override this routine to provide different behavior.
1590 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1591 SourceLocation LParenLoc,
1592 SourceLocation EndLoc) {
1593 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1594 EndLoc);
1595 }
1596
1597 /// Build a new OpenMP 'num_threads' clause.
1598 ///
1599 /// By default, performs semantic analysis to build the new OpenMP clause.
1600 /// Subclasses may override this routine to provide different behavior.
1601 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1602 SourceLocation StartLoc,
1603 SourceLocation LParenLoc,
1604 SourceLocation EndLoc) {
1605 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1606 LParenLoc, EndLoc);
1607 }
1608
1609 /// Build a new OpenMP 'safelen' clause.
1610 ///
1611 /// By default, performs semantic analysis to build the new OpenMP clause.
1612 /// Subclasses may override this routine to provide different behavior.
1613 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1614 SourceLocation LParenLoc,
1615 SourceLocation EndLoc) {
1616 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1617 }
1618
1619 /// Build a new OpenMP 'simdlen' clause.
1620 ///
1621 /// By default, performs semantic analysis to build the new OpenMP clause.
1622 /// Subclasses may override this routine to provide different behavior.
1623 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1624 SourceLocation LParenLoc,
1625 SourceLocation EndLoc) {
1626 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1627 }
1628
1629 OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1630 SourceLocation StartLoc,
1631 SourceLocation LParenLoc,
1632 SourceLocation EndLoc) {
1633 return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1634 }
1635
1636 /// Build a new OpenMP 'allocator' 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 *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1641 SourceLocation LParenLoc,
1642 SourceLocation EndLoc) {
1643 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1644 }
1645
1646 /// Build a new OpenMP 'collapse' clause.
1647 ///
1648 /// By default, performs semantic analysis to build the new OpenMP clause.
1649 /// Subclasses may override this routine to provide different behavior.
1650 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1651 SourceLocation LParenLoc,
1652 SourceLocation EndLoc) {
1653 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1654 EndLoc);
1655 }
1656
1657 /// Build a new OpenMP 'default' clause.
1658 ///
1659 /// By default, performs semantic analysis to build the new OpenMP clause.
1660 /// Subclasses may override this routine to provide different behavior.
1661 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1662 SourceLocation StartLoc,
1663 SourceLocation LParenLoc,
1664 SourceLocation EndLoc) {
1665 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1666 StartLoc, LParenLoc, EndLoc);
1667 }
1668
1669 /// Build a new OpenMP 'proc_bind' clause.
1670 ///
1671 /// By default, performs semantic analysis to build the new OpenMP clause.
1672 /// Subclasses may override this routine to provide different behavior.
1673 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1674 SourceLocation KindKwLoc,
1675 SourceLocation StartLoc,
1676 SourceLocation LParenLoc,
1677 SourceLocation EndLoc) {
1678 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1679 StartLoc, LParenLoc, EndLoc);
1680 }
1681
1682 /// Build a new OpenMP 'schedule' clause.
1683 ///
1684 /// By default, performs semantic analysis to build the new OpenMP clause.
1685 /// Subclasses may override this routine to provide different behavior.
1686 OMPClause *RebuildOMPScheduleClause(
1687 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1688 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1689 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1690 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1691 return getSema().ActOnOpenMPScheduleClause(
1692 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1693 CommaLoc, EndLoc);
1694 }
1695
1696 /// Build a new OpenMP 'ordered' clause.
1697 ///
1698 /// By default, performs semantic analysis to build the new OpenMP clause.
1699 /// Subclasses may override this routine to provide different behavior.
1700 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1701 SourceLocation EndLoc,
1702 SourceLocation LParenLoc, Expr *Num) {
1703 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1704 }
1705
1706 /// Build a new OpenMP 'private' clause.
1707 ///
1708 /// By default, performs semantic analysis to build the new OpenMP clause.
1709 /// Subclasses may override this routine to provide different behavior.
1710 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1711 SourceLocation StartLoc,
1712 SourceLocation LParenLoc,
1713 SourceLocation EndLoc) {
1714 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1715 EndLoc);
1716 }
1717
1718 /// Build a new OpenMP 'firstprivate' clause.
1719 ///
1720 /// By default, performs semantic analysis to build the new OpenMP clause.
1721 /// Subclasses may override this routine to provide different behavior.
1722 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1723 SourceLocation StartLoc,
1724 SourceLocation LParenLoc,
1725 SourceLocation EndLoc) {
1726 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1727 EndLoc);
1728 }
1729
1730 /// Build a new OpenMP 'lastprivate' clause.
1731 ///
1732 /// By default, performs semantic analysis to build the new OpenMP clause.
1733 /// Subclasses may override this routine to provide different behavior.
1734 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1735 OpenMPLastprivateModifier LPKind,
1736 SourceLocation LPKindLoc,
1737 SourceLocation ColonLoc,
1738 SourceLocation StartLoc,
1739 SourceLocation LParenLoc,
1740 SourceLocation EndLoc) {
1741 return getSema().ActOnOpenMPLastprivateClause(
1742 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1743 }
1744
1745 /// Build a new OpenMP 'shared' clause.
1746 ///
1747 /// By default, performs semantic analysis to build the new OpenMP clause.
1748 /// Subclasses may override this routine to provide different behavior.
1749 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1750 SourceLocation StartLoc,
1751 SourceLocation LParenLoc,
1752 SourceLocation EndLoc) {
1753 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1754 EndLoc);
1755 }
1756
1757 /// Build a new OpenMP 'reduction' clause.
1758 ///
1759 /// By default, performs semantic analysis to build the new statement.
1760 /// Subclasses may override this routine to provide different behavior.
1761 OMPClause *RebuildOMPReductionClause(
1762 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1763 SourceLocation StartLoc, SourceLocation LParenLoc,
1764 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1765 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1766 const DeclarationNameInfo &ReductionId,
1767 ArrayRef<Expr *> UnresolvedReductions) {
1768 return getSema().ActOnOpenMPReductionClause(
1769 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1770 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1771 }
1772
1773 /// Build a new OpenMP 'task_reduction' clause.
1774 ///
1775 /// By default, performs semantic analysis to build the new statement.
1776 /// Subclasses may override this routine to provide different behavior.
1777 OMPClause *RebuildOMPTaskReductionClause(
1778 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1779 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1780 CXXScopeSpec &ReductionIdScopeSpec,
1781 const DeclarationNameInfo &ReductionId,
1782 ArrayRef<Expr *> UnresolvedReductions) {
1783 return getSema().ActOnOpenMPTaskReductionClause(
1784 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1785 ReductionId, UnresolvedReductions);
1786 }
1787
1788 /// Build a new OpenMP 'in_reduction' clause.
1789 ///
1790 /// By default, performs semantic analysis to build the new statement.
1791 /// Subclasses may override this routine to provide different behavior.
1792 OMPClause *
1793 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1794 SourceLocation LParenLoc, SourceLocation ColonLoc,
1795 SourceLocation EndLoc,
1796 CXXScopeSpec &ReductionIdScopeSpec,
1797 const DeclarationNameInfo &ReductionId,
1798 ArrayRef<Expr *> UnresolvedReductions) {
1799 return getSema().ActOnOpenMPInReductionClause(
1800 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1801 ReductionId, UnresolvedReductions);
1802 }
1803
1804 /// Build a new OpenMP 'linear' clause.
1805 ///
1806 /// By default, performs semantic analysis to build the new OpenMP clause.
1807 /// Subclasses may override this routine to provide different behavior.
1808 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1809 SourceLocation StartLoc,
1810 SourceLocation LParenLoc,
1811 OpenMPLinearClauseKind Modifier,
1812 SourceLocation ModifierLoc,
1813 SourceLocation ColonLoc,
1814 SourceLocation EndLoc) {
1815 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1816 Modifier, ModifierLoc, ColonLoc,
1817 EndLoc);
1818 }
1819
1820 /// Build a new OpenMP 'aligned' clause.
1821 ///
1822 /// By default, performs semantic analysis to build the new OpenMP clause.
1823 /// Subclasses may override this routine to provide different behavior.
1824 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1825 SourceLocation StartLoc,
1826 SourceLocation LParenLoc,
1827 SourceLocation ColonLoc,
1828 SourceLocation EndLoc) {
1829 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1830 LParenLoc, ColonLoc, EndLoc);
1831 }
1832
1833 /// Build a new OpenMP 'copyin' clause.
1834 ///
1835 /// By default, performs semantic analysis to build the new OpenMP clause.
1836 /// Subclasses may override this routine to provide different behavior.
1837 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1838 SourceLocation StartLoc,
1839 SourceLocation LParenLoc,
1840 SourceLocation EndLoc) {
1841 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1842 EndLoc);
1843 }
1844
1845 /// Build a new OpenMP 'copyprivate' clause.
1846 ///
1847 /// By default, performs semantic analysis to build the new OpenMP clause.
1848 /// Subclasses may override this routine to provide different behavior.
1849 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1850 SourceLocation StartLoc,
1851 SourceLocation LParenLoc,
1852 SourceLocation EndLoc) {
1853 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1854 EndLoc);
1855 }
1856
1857 /// Build a new OpenMP 'flush' pseudo clause.
1858 ///
1859 /// By default, performs semantic analysis to build the new OpenMP clause.
1860 /// Subclasses may override this routine to provide different behavior.
1861 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1862 SourceLocation StartLoc,
1863 SourceLocation LParenLoc,
1864 SourceLocation EndLoc) {
1865 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1866 EndLoc);
1867 }
1868
1869 /// Build a new OpenMP 'depobj' pseudo clause.
1870 ///
1871 /// By default, performs semantic analysis to build the new OpenMP clause.
1872 /// Subclasses may override this routine to provide different behavior.
1873 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1874 SourceLocation LParenLoc,
1875 SourceLocation EndLoc) {
1876 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1877 EndLoc);
1878 }
1879
1880 /// Build a new OpenMP 'depend' pseudo clause.
1881 ///
1882 /// By default, performs semantic analysis to build the new OpenMP clause.
1883 /// Subclasses may override this routine to provide different behavior.
1884 OMPClause *
1885 RebuildOMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
1886 SourceLocation DepLoc, SourceLocation ColonLoc,
1887 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1888 SourceLocation LParenLoc, SourceLocation EndLoc) {
1889 return getSema().ActOnOpenMPDependClause(DepModifier, DepKind, DepLoc,
1890 ColonLoc, VarList, StartLoc,
1891 LParenLoc, EndLoc);
1892 }
1893
1894 /// Build a new OpenMP 'device' clause.
1895 ///
1896 /// By default, performs semantic analysis to build the new statement.
1897 /// Subclasses may override this routine to provide different behavior.
1898 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1899 Expr *Device, SourceLocation StartLoc,
1900 SourceLocation LParenLoc,
1901 SourceLocation ModifierLoc,
1902 SourceLocation EndLoc) {
1903 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1904 LParenLoc, ModifierLoc, EndLoc);
1905 }
1906
1907 /// Build a new OpenMP 'map' clause.
1908 ///
1909 /// By default, performs semantic analysis to build the new OpenMP clause.
1910 /// Subclasses may override this routine to provide different behavior.
1911 OMPClause *RebuildOMPMapClause(
1912 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1913 ArrayRef<SourceLocation> MapTypeModifiersLoc,
1914 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1915 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1916 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1917 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1918 return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1919 MapperIdScopeSpec, MapperId, MapType,
1920 IsMapTypeImplicit, MapLoc, ColonLoc,
1921 VarList, Locs, UnresolvedMappers);
1922 }
1923
1924 /// Build a new OpenMP 'allocate' clause.
1925 ///
1926 /// By default, performs semantic analysis to build the new OpenMP clause.
1927 /// Subclasses may override this routine to provide different behavior.
1928 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1929 SourceLocation StartLoc,
1930 SourceLocation LParenLoc,
1931 SourceLocation ColonLoc,
1932 SourceLocation EndLoc) {
1933 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1934 LParenLoc, ColonLoc, EndLoc);
1935 }
1936
1937 /// Build a new OpenMP 'num_teams' clause.
1938 ///
1939 /// By default, performs semantic analysis to build the new statement.
1940 /// Subclasses may override this routine to provide different behavior.
1941 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1942 SourceLocation LParenLoc,
1943 SourceLocation EndLoc) {
1944 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1945 EndLoc);
1946 }
1947
1948 /// Build a new OpenMP 'thread_limit' clause.
1949 ///
1950 /// By default, performs semantic analysis to build the new statement.
1951 /// Subclasses may override this routine to provide different behavior.
1952 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1953 SourceLocation StartLoc,
1954 SourceLocation LParenLoc,
1955 SourceLocation EndLoc) {
1956 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1957 LParenLoc, EndLoc);
1958 }
1959
1960 /// Build a new OpenMP 'priority' clause.
1961 ///
1962 /// By default, performs semantic analysis to build the new statement.
1963 /// Subclasses may override this routine to provide different behavior.
1964 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1965 SourceLocation LParenLoc,
1966 SourceLocation EndLoc) {
1967 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1968 EndLoc);
1969 }
1970
1971 /// Build a new OpenMP 'grainsize' clause.
1972 ///
1973 /// By default, performs semantic analysis to build the new statement.
1974 /// Subclasses may override this routine to provide different behavior.
1975 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1976 SourceLocation LParenLoc,
1977 SourceLocation EndLoc) {
1978 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1979 EndLoc);
1980 }
1981
1982 /// Build a new OpenMP 'num_tasks' 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 *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1987 SourceLocation LParenLoc,
1988 SourceLocation EndLoc) {
1989 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1990 EndLoc);
1991 }
1992
1993 /// Build a new OpenMP 'hint' clause.
1994 ///
1995 /// By default, performs semantic analysis to build the new statement.
1996 /// Subclasses may override this routine to provide different behavior.
1997 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1998 SourceLocation LParenLoc,
1999 SourceLocation EndLoc) {
2000 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2001 }
2002
2003 /// Build a new OpenMP 'detach' clause.
2004 ///
2005 /// By default, performs semantic analysis to build the new statement.
2006 /// Subclasses may override this routine to provide different behavior.
2007 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2008 SourceLocation LParenLoc,
2009 SourceLocation EndLoc) {
2010 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2011 }
2012
2013 /// Build a new OpenMP 'dist_schedule' clause.
2014 ///
2015 /// By default, performs semantic analysis to build the new OpenMP clause.
2016 /// Subclasses may override this routine to provide different behavior.
2017 OMPClause *
2018 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2019 Expr *ChunkSize, SourceLocation StartLoc,
2020 SourceLocation LParenLoc, SourceLocation KindLoc,
2021 SourceLocation CommaLoc, SourceLocation EndLoc) {
2022 return getSema().ActOnOpenMPDistScheduleClause(
2023 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2024 }
2025
2026 /// Build a new OpenMP 'to' clause.
2027 ///
2028 /// By default, performs semantic analysis to build the new statement.
2029 /// Subclasses may override this routine to provide different behavior.
2030 OMPClause *
2031 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2032 ArrayRef<SourceLocation> MotionModifiersLoc,
2033 CXXScopeSpec &MapperIdScopeSpec,
2034 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2035 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2036 ArrayRef<Expr *> UnresolvedMappers) {
2037 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2038 MapperIdScopeSpec, MapperId, ColonLoc,
2039 VarList, Locs, UnresolvedMappers);
2040 }
2041
2042 /// Build a new OpenMP 'from' clause.
2043 ///
2044 /// By default, performs semantic analysis to build the new statement.
2045 /// Subclasses may override this routine to provide different behavior.
2046 OMPClause *
2047 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2048 ArrayRef<SourceLocation> MotionModifiersLoc,
2049 CXXScopeSpec &MapperIdScopeSpec,
2050 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2051 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2052 ArrayRef<Expr *> UnresolvedMappers) {
2053 return getSema().ActOnOpenMPFromClause(
2054 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2055 ColonLoc, VarList, Locs, UnresolvedMappers);
2056 }
2057
2058 /// Build a new OpenMP 'use_device_ptr' clause.
2059 ///
2060 /// By default, performs semantic analysis to build the new OpenMP clause.
2061 /// Subclasses may override this routine to provide different behavior.
2062 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2063 const OMPVarListLocTy &Locs) {
2064 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2065 }
2066
2067 /// Build a new OpenMP 'use_device_addr' clause.
2068 ///
2069 /// By default, performs semantic analysis to build the new OpenMP clause.
2070 /// Subclasses may override this routine to provide different behavior.
2071 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2072 const OMPVarListLocTy &Locs) {
2073 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2074 }
2075
2076 /// Build a new OpenMP 'is_device_ptr' clause.
2077 ///
2078 /// By default, performs semantic analysis to build the new OpenMP clause.
2079 /// Subclasses may override this routine to provide different behavior.
2080 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2081 const OMPVarListLocTy &Locs) {
2082 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2083 }
2084
2085 /// Build a new OpenMP 'defaultmap' clause.
2086 ///
2087 /// By default, performs semantic analysis to build the new OpenMP clause.
2088 /// Subclasses may override this routine to provide different behavior.
2089 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2090 OpenMPDefaultmapClauseKind Kind,
2091 SourceLocation StartLoc,
2092 SourceLocation LParenLoc,
2093 SourceLocation MLoc,
2094 SourceLocation KindLoc,
2095 SourceLocation EndLoc) {
2096 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2097 MLoc, KindLoc, EndLoc);
2098 }
2099
2100 /// Build a new OpenMP 'nontemporal' clause.
2101 ///
2102 /// By default, performs semantic analysis to build the new OpenMP clause.
2103 /// Subclasses may override this routine to provide different behavior.
2104 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2105 SourceLocation StartLoc,
2106 SourceLocation LParenLoc,
2107 SourceLocation EndLoc) {
2108 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2109 EndLoc);
2110 }
2111
2112 /// Build a new OpenMP 'inclusive' clause.
2113 ///
2114 /// By default, performs semantic analysis to build the new OpenMP clause.
2115 /// Subclasses may override this routine to provide different behavior.
2116 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2117 SourceLocation StartLoc,
2118 SourceLocation LParenLoc,
2119 SourceLocation EndLoc) {
2120 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2121 EndLoc);
2122 }
2123
2124 /// Build a new OpenMP 'exclusive' clause.
2125 ///
2126 /// By default, performs semantic analysis to build the new OpenMP clause.
2127 /// Subclasses may override this routine to provide different behavior.
2128 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2129 SourceLocation StartLoc,
2130 SourceLocation LParenLoc,
2131 SourceLocation EndLoc) {
2132 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2133 EndLoc);
2134 }
2135
2136 /// Build a new OpenMP 'uses_allocators' clause.
2137 ///
2138 /// By default, performs semantic analysis to build the new OpenMP clause.
2139 /// Subclasses may override this routine to provide different behavior.
2140 OMPClause *RebuildOMPUsesAllocatorsClause(
2141 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2142 SourceLocation LParenLoc, SourceLocation EndLoc) {
2143 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2144 Data);
2145 }
2146
2147 /// Build a new OpenMP 'affinity' clause.
2148 ///
2149 /// By default, performs semantic analysis to build the new OpenMP clause.
2150 /// Subclasses may override this routine to provide different behavior.
2151 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2152 SourceLocation LParenLoc,
2153 SourceLocation ColonLoc,
2154 SourceLocation EndLoc, Expr *Modifier,
2155 ArrayRef<Expr *> Locators) {
2156 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2157 EndLoc, Modifier, Locators);
2158 }
2159
2160 /// Build a new OpenMP 'order' clause.
2161 ///
2162 /// By default, performs semantic analysis to build the new OpenMP clause.
2163 /// Subclasses may override this routine to provide different behavior.
2164 OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2165 SourceLocation KindKwLoc,
2166 SourceLocation StartLoc,
2167 SourceLocation LParenLoc,
2168 SourceLocation EndLoc) {
2169 return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2170 LParenLoc, EndLoc);
2171 }
2172
2173 /// Build a new OpenMP 'init' clause.
2174 ///
2175 /// By default, performs semantic analysis to build the new OpenMP clause.
2176 /// Subclasses may override this routine to provide different behavior.
2177 OMPClause *RebuildOMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
2178 bool IsTarget, bool IsTargetSync,
2179 SourceLocation StartLoc,
2180 SourceLocation LParenLoc,
2181 SourceLocation VarLoc,
2182 SourceLocation EndLoc) {
2183 return getSema().ActOnOpenMPInitClause(InteropVar, PrefExprs, IsTarget,
2184 IsTargetSync, StartLoc, LParenLoc,
2185 VarLoc, EndLoc);
2186 }
2187
2188 /// Build a new OpenMP 'use' clause.
2189 ///
2190 /// By default, performs semantic analysis to build the new OpenMP clause.
2191 /// Subclasses may override this routine to provide different behavior.
2192 OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2193 SourceLocation LParenLoc,
2194 SourceLocation VarLoc, SourceLocation EndLoc) {
2195 return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2196 VarLoc, EndLoc);
2197 }
2198
2199 /// Build a new OpenMP 'destroy' clause.
2200 ///
2201 /// By default, performs semantic analysis to build the new OpenMP clause.
2202 /// Subclasses may override this routine to provide different behavior.
2203 OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2204 SourceLocation LParenLoc,
2205 SourceLocation VarLoc,
2206 SourceLocation EndLoc) {
2207 return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2208 VarLoc, EndLoc);
2209 }
2210
2211 /// Build a new OpenMP 'novariants' clause.
2212 ///
2213 /// By default, performs semantic analysis to build the new OpenMP clause.
2214 /// Subclasses may override this routine to provide different behavior.
2215 OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2216 SourceLocation StartLoc,
2217 SourceLocation LParenLoc,
2218 SourceLocation EndLoc) {
2219 return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2220 EndLoc);
2221 }
2222
2223 /// Build a new OpenMP 'nocontext' clause.
2224 ///
2225 /// By default, performs semantic analysis to build the new OpenMP clause.
2226 /// Subclasses may override this routine to provide different behavior.
2227 OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2228 SourceLocation LParenLoc,
2229 SourceLocation EndLoc) {
2230 return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2231 EndLoc);
2232 }
2233
2234 /// Build a new OpenMP 'filter' clause.
2235 ///
2236 /// By default, performs semantic analysis to build the new OpenMP clause.
2237 /// Subclasses may override this routine to provide different behavior.
2238 OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2239 SourceLocation LParenLoc,
2240 SourceLocation EndLoc) {
2241 return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2242 EndLoc);
2243 }
2244
2245 /// Rebuild the operand to an Objective-C \@synchronized statement.
2246 ///
2247 /// By default, performs semantic analysis to build the new statement.
2248 /// Subclasses may override this routine to provide different behavior.
2249 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2250 Expr *object) {
2251 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2252 }
2253
2254 /// Build a new Objective-C \@synchronized statement.
2255 ///
2256 /// By default, performs semantic analysis to build the new statement.
2257 /// Subclasses may override this routine to provide different behavior.
2258 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2259 Expr *Object, Stmt *Body) {
2260 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2261 }
2262
2263 /// Build a new Objective-C \@autoreleasepool statement.
2264 ///
2265 /// By default, performs semantic analysis to build the new statement.
2266 /// Subclasses may override this routine to provide different behavior.
2267 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2268 Stmt *Body) {
2269 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2270 }
2271
2272 /// Build a new Objective-C fast enumeration statement.
2273 ///
2274 /// By default, performs semantic analysis to build the new statement.
2275 /// Subclasses may override this routine to provide different behavior.
2276 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2277 Stmt *Element,
2278 Expr *Collection,
2279 SourceLocation RParenLoc,
2280 Stmt *Body) {
2281 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2282 Element,
2283 Collection,
2284 RParenLoc);
2285 if (ForEachStmt.isInvalid())
2286 return StmtError();
2287
2288 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2289 }
2290
2291 /// Build a new C++ exception declaration.
2292 ///
2293 /// By default, performs semantic analysis to build the new decaration.
2294 /// Subclasses may override this routine to provide different behavior.
2295 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2296 TypeSourceInfo *Declarator,
2297 SourceLocation StartLoc,
2298 SourceLocation IdLoc,
2299 IdentifierInfo *Id) {
2300 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2301 StartLoc, IdLoc, Id);
2302 if (Var)
2303 getSema().CurContext->addDecl(Var);
2304 return Var;
2305 }
2306
2307 /// Build a new C++ catch statement.
2308 ///
2309 /// By default, performs semantic analysis to build the new statement.
2310 /// Subclasses may override this routine to provide different behavior.
2311 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2312 VarDecl *ExceptionDecl,
2313 Stmt *Handler) {
2314 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2315 Handler));
2316 }
2317
2318 /// Build a new C++ try statement.
2319 ///
2320 /// By default, performs semantic analysis to build the new statement.
2321 /// Subclasses may override this routine to provide different behavior.
2322 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2323 ArrayRef<Stmt *> Handlers) {
2324 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2325 }
2326
2327 /// Build a new C++0x range-based for statement.
2328 ///
2329 /// By default, performs semantic analysis to build the new statement.
2330 /// Subclasses may override this routine to provide different behavior.
2331 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2332 SourceLocation CoawaitLoc, Stmt *Init,
2333 SourceLocation ColonLoc, Stmt *Range,
2334 Stmt *Begin, Stmt *End, Expr *Cond,
2335 Expr *Inc, Stmt *LoopVar,
2336 SourceLocation RParenLoc) {
2337 // If we've just learned that the range is actually an Objective-C
2338 // collection, treat this as an Objective-C fast enumeration loop.
2339 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2340 if (RangeStmt->isSingleDecl()) {
2341 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2342 if (RangeVar->isInvalidDecl())
2343 return StmtError();
2344
2345 Expr *RangeExpr = RangeVar->getInit();
2346 if (!RangeExpr->isTypeDependent() &&
2347 RangeExpr->getType()->isObjCObjectPointerType()) {
2348 // FIXME: Support init-statements in Objective-C++20 ranged for
2349 // statement.
2350 if (Init) {
2351 return SemaRef.Diag(Init->getBeginLoc(),
2352 diag::err_objc_for_range_init_stmt)
2353 << Init->getSourceRange();
2354 }
2355 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2356 RangeExpr, RParenLoc);
2357 }
2358 }
2359 }
2360 }
2361
2362 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2363 Range, Begin, End, Cond, Inc, LoopVar,
2364 RParenLoc, Sema::BFRK_Rebuild);
2365 }
2366
2367 /// Build a new C++0x range-based for statement.
2368 ///
2369 /// By default, performs semantic analysis to build the new statement.
2370 /// Subclasses may override this routine to provide different behavior.
2371 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2372 bool IsIfExists,
2373 NestedNameSpecifierLoc QualifierLoc,
2374 DeclarationNameInfo NameInfo,
2375 Stmt *Nested) {
2376 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2377 QualifierLoc, NameInfo, Nested);
2378 }
2379
2380 /// Attach body to a C++0x range-based for statement.
2381 ///
2382 /// By default, performs semantic analysis to finish the new statement.
2383 /// Subclasses may override this routine to provide different behavior.
2384 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2385 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2386 }
2387
2388 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2389 Stmt *TryBlock, Stmt *Handler) {
2390 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2391 }
2392
2393 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2394 Stmt *Block) {
2395 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2396 }
2397
2398 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2399 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2400 }
2401
2402 /// Build a new predefined expression.
2403 ///
2404 /// By default, performs semantic analysis to build the new expression.
2405 /// Subclasses may override this routine to provide different behavior.
2406 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2407 PredefinedExpr::IdentKind IK) {
2408 return getSema().BuildPredefinedExpr(Loc, IK);
2409 }
2410
2411 /// Build a new expression that references a declaration.
2412 ///
2413 /// By default, performs semantic analysis to build the new expression.
2414 /// Subclasses may override this routine to provide different behavior.
2415 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2416 LookupResult &R,
2417 bool RequiresADL) {
2418 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2419 }
2420
2421
2422 /// Build a new expression that references a declaration.
2423 ///
2424 /// By default, performs semantic analysis to build the new expression.
2425 /// Subclasses may override this routine to provide different behavior.
2426 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2427 ValueDecl *VD,
2428 const DeclarationNameInfo &NameInfo,
2429 NamedDecl *Found,
2430 TemplateArgumentListInfo *TemplateArgs) {
2431 CXXScopeSpec SS;
2432 SS.Adopt(QualifierLoc);
2433 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2434 TemplateArgs);
2435 }
2436
2437 /// Build a new expression in parentheses.
2438 ///
2439 /// By default, performs semantic analysis to build the new expression.
2440 /// Subclasses may override this routine to provide different behavior.
2441 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2442 SourceLocation RParen) {
2443 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2444 }
2445
2446 /// Build a new pseudo-destructor expression.
2447 ///
2448 /// By default, performs semantic analysis to build the new expression.
2449 /// Subclasses may override this routine to provide different behavior.
2450 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2451 SourceLocation OperatorLoc,
2452 bool isArrow,
2453 CXXScopeSpec &SS,
2454 TypeSourceInfo *ScopeType,
2455 SourceLocation CCLoc,
2456 SourceLocation TildeLoc,
2457 PseudoDestructorTypeStorage Destroyed);
2458
2459 /// Build a new unary operator expression.
2460 ///
2461 /// By default, performs semantic analysis to build the new expression.
2462 /// Subclasses may override this routine to provide different behavior.
2463 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2464 UnaryOperatorKind Opc,
2465 Expr *SubExpr) {
2466 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2467 }
2468
2469 /// Build a new builtin offsetof expression.
2470 ///
2471 /// By default, performs semantic analysis to build the new expression.
2472 /// Subclasses may override this routine to provide different behavior.
2473 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2474 TypeSourceInfo *Type,
2475 ArrayRef<Sema::OffsetOfComponent> Components,
2476 SourceLocation RParenLoc) {
2477 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2478 RParenLoc);
2479 }
2480
2481 /// Build a new sizeof, alignof or vec_step expression with a
2482 /// type argument.
2483 ///
2484 /// By default, performs semantic analysis to build the new expression.
2485 /// Subclasses may override this routine to provide different behavior.
2486 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2487 SourceLocation OpLoc,
2488 UnaryExprOrTypeTrait ExprKind,
2489 SourceRange R) {
2490 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2491 }
2492
2493 /// Build a new sizeof, alignof or vec step expression with an
2494 /// expression argument.
2495 ///
2496 /// By default, performs semantic analysis to build the new expression.
2497 /// Subclasses may override this routine to provide different behavior.
2498 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2499 UnaryExprOrTypeTrait ExprKind,
2500 SourceRange R) {
2501 ExprResult Result
2502 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2503 if (Result.isInvalid())
2504 return ExprError();
2505
2506 return Result;
2507 }
2508
2509 /// Build a new array subscript expression.
2510 ///
2511 /// By default, performs semantic analysis to build the new expression.
2512 /// Subclasses may override this routine to provide different behavior.
2513 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2514 SourceLocation LBracketLoc,
2515 Expr *RHS,
2516 SourceLocation RBracketLoc) {
2517 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2518 LBracketLoc, RHS,
2519 RBracketLoc);
2520 }
2521
2522 /// Build a new matrix subscript expression.
2523 ///
2524 /// By default, performs semantic analysis to build the new expression.
2525 /// Subclasses may override this routine to provide different behavior.
2526 ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2527 Expr *ColumnIdx,
2528 SourceLocation RBracketLoc) {
2529 return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2530 RBracketLoc);
2531 }
2532
2533 /// Build a new array section expression.
2534 ///
2535 /// By default, performs semantic analysis to build the new expression.
2536 /// Subclasses may override this routine to provide different behavior.
2537 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2538 Expr *LowerBound,
2539 SourceLocation ColonLocFirst,
2540 SourceLocation ColonLocSecond,
2541 Expr *Length, Expr *Stride,
2542 SourceLocation RBracketLoc) {
2543 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2544 ColonLocFirst, ColonLocSecond,
2545 Length, Stride, RBracketLoc);
2546 }
2547
2548 /// Build a new array shaping expression.
2549 ///
2550 /// By default, performs semantic analysis to build the new expression.
2551 /// Subclasses may override this routine to provide different behavior.
2552 ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2553 SourceLocation RParenLoc,
2554 ArrayRef<Expr *> Dims,
2555 ArrayRef<SourceRange> BracketsRanges) {
2556 return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2557 BracketsRanges);
2558 }
2559
2560 /// Build a new iterator expression.
2561 ///
2562 /// By default, performs semantic analysis to build the new expression.
2563 /// Subclasses may override this routine to provide different behavior.
2564 ExprResult RebuildOMPIteratorExpr(
2565 SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2566 ArrayRef<Sema::OMPIteratorData> Data) {
2567 return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2568 LLoc, RLoc, Data);
2569 }
2570
2571 /// Build a new call expression.
2572 ///
2573 /// By default, performs semantic analysis to build the new expression.
2574 /// Subclasses may override this routine to provide different behavior.
2575 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2576 MultiExprArg Args,
2577 SourceLocation RParenLoc,
2578 Expr *ExecConfig = nullptr) {
2579 return getSema().ActOnCallExpr(
2580 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2581 }
2582
2583 /// Build a new member access expression.
2584 ///
2585 /// By default, performs semantic analysis to build the new expression.
2586 /// Subclasses may override this routine to provide different behavior.
2587 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2588 bool isArrow,
2589 NestedNameSpecifierLoc QualifierLoc,
2590 SourceLocation TemplateKWLoc,
2591 const DeclarationNameInfo &MemberNameInfo,
2592 ValueDecl *Member,
2593 NamedDecl *FoundDecl,
2594 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2595 NamedDecl *FirstQualifierInScope) {
2596 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2597 isArrow);
2598 if (!Member->getDeclName()) {
2599 // We have a reference to an unnamed field. This is always the
2600 // base of an anonymous struct/union member access, i.e. the
2601 // field is always of record type.
2602 assert(Member->getType()->isRecordType() &&((Member->getType()->isRecordType() && "unnamed member not of record type?"
) ? static_cast<void> (0) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 2603, __PRETTY_FUNCTION__))
2603 "unnamed member not of record type?")((Member->getType()->isRecordType() && "unnamed member not of record type?"
) ? static_cast<void> (0) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 2603, __PRETTY_FUNCTION__))
;
2604
2605 BaseResult =
2606 getSema().PerformObjectMemberConversion(BaseResult.get(),
2607 QualifierLoc.getNestedNameSpecifier(),
2608 FoundDecl, Member);
2609 if (BaseResult.isInvalid())
2610 return ExprError();
2611 Base = BaseResult.get();
2612
2613 CXXScopeSpec EmptySS;
2614 return getSema().BuildFieldReferenceExpr(
2615 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2616 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2617 }
2618
2619 CXXScopeSpec SS;
2620 SS.Adopt(QualifierLoc);
2621
2622 Base = BaseResult.get();
2623 QualType BaseType = Base->getType();
2624
2625 if (isArrow && !BaseType->isPointerType())
2626 return ExprError();
2627
2628 // FIXME: this involves duplicating earlier analysis in a lot of
2629 // cases; we should avoid this when possible.
2630 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2631 R.addDecl(FoundDecl);
2632 R.resolveKind();
2633
2634 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2635 SS, TemplateKWLoc,
2636 FirstQualifierInScope,
2637 R, ExplicitTemplateArgs,
2638 /*S*/nullptr);
2639 }
2640
2641 /// Build a new binary operator expression.
2642 ///
2643 /// By default, performs semantic analysis to build the new expression.
2644 /// Subclasses may override this routine to provide different behavior.
2645 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2646 BinaryOperatorKind Opc,
2647 Expr *LHS, Expr *RHS) {
2648 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2649 }
2650
2651 /// Build a new rewritten operator expression.
2652 ///
2653 /// By default, performs semantic analysis to build the new expression.
2654 /// Subclasses may override this routine to provide different behavior.
2655 ExprResult RebuildCXXRewrittenBinaryOperator(
2656 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2657 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2658 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2659 RHS, /*RequiresADL*/false);
2660 }
2661
2662 /// Build a new conditional operator expression.
2663 ///
2664 /// By default, performs semantic analysis to build the new expression.
2665 /// Subclasses may override this routine to provide different behavior.
2666 ExprResult RebuildConditionalOperator(Expr *Cond,
2667 SourceLocation QuestionLoc,
2668 Expr *LHS,
2669 SourceLocation ColonLoc,
2670 Expr *RHS) {
2671 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2672 LHS, RHS);
2673 }
2674
2675 /// Build a new C-style cast expression.
2676 ///
2677 /// By default, performs semantic analysis to build the new expression.
2678 /// Subclasses may override this routine to provide different behavior.
2679 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2680 TypeSourceInfo *TInfo,
2681 SourceLocation RParenLoc,
2682 Expr *SubExpr) {
2683 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2684 SubExpr);
2685 }
2686
2687 /// Build a new compound literal expression.
2688 ///
2689 /// By default, performs semantic analysis to build the new expression.
2690 /// Subclasses may override this routine to provide different behavior.
2691 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2692 TypeSourceInfo *TInfo,
2693 SourceLocation RParenLoc,
2694 Expr *Init) {
2695 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2696 Init);
2697 }
2698
2699 /// Build a new extended vector element access expression.
2700 ///
2701 /// By default, performs semantic analysis to build the new expression.
2702 /// Subclasses may override this routine to provide different behavior.
2703 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2704 SourceLocation OpLoc,
2705 SourceLocation AccessorLoc,
2706 IdentifierInfo &Accessor) {
2707
2708 CXXScopeSpec SS;
2709 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2710 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2711 OpLoc, /*IsArrow*/ false,
2712 SS, SourceLocation(),
2713 /*FirstQualifierInScope*/ nullptr,
2714 NameInfo,
2715 /* TemplateArgs */ nullptr,
2716 /*S*/ nullptr);
2717 }
2718
2719 /// Build a new initializer list expression.
2720 ///
2721 /// By default, performs semantic analysis to build the new expression.
2722 /// Subclasses may override this routine to provide different behavior.
2723 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2724 MultiExprArg Inits,
2725 SourceLocation RBraceLoc) {
2726 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2727 }
2728
2729 /// Build a new designated initializer expression.
2730 ///
2731 /// By default, performs semantic analysis to build the new expression.
2732 /// Subclasses may override this routine to provide different behavior.
2733 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2734 MultiExprArg ArrayExprs,
2735 SourceLocation EqualOrColonLoc,
2736 bool GNUSyntax,
2737 Expr *Init) {
2738 ExprResult Result
2739 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2740 Init);
2741 if (Result.isInvalid())
2742 return ExprError();
2743
2744 return Result;
2745 }
2746
2747 /// Build a new value-initialized expression.
2748 ///
2749 /// By default, builds the implicit value initialization without performing
2750 /// any semantic analysis. Subclasses may override this routine to provide
2751 /// different behavior.
2752 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2753 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2754 }
2755
2756 /// Build a new \c va_arg expression.
2757 ///
2758 /// By default, performs semantic analysis to build the new expression.
2759 /// Subclasses may override this routine to provide different behavior.
2760 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2761 Expr *SubExpr, TypeSourceInfo *TInfo,
2762 SourceLocation RParenLoc) {
2763 return getSema().BuildVAArgExpr(BuiltinLoc,
2764 SubExpr, TInfo,
2765 RParenLoc);
2766 }
2767
2768 /// Build a new expression list in parentheses.
2769 ///
2770 /// By default, performs semantic analysis to build the new expression.
2771 /// Subclasses may override this routine to provide different behavior.
2772 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2773 MultiExprArg SubExprs,
2774 SourceLocation RParenLoc) {
2775 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2776 }
2777
2778 /// Build a new address-of-label expression.
2779 ///
2780 /// By default, performs semantic analysis, using the name of the label
2781 /// rather than attempting to map the label statement itself.
2782 /// Subclasses may override this routine to provide different behavior.
2783 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2784 SourceLocation LabelLoc, LabelDecl *Label) {
2785 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2786 }
2787
2788 /// Build a new GNU statement expression.
2789 ///
2790 /// By default, performs semantic analysis to build the new expression.
2791 /// Subclasses may override this routine to provide different behavior.
2792 ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2793 SourceLocation RParenLoc, unsigned TemplateDepth) {
2794 return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2795 TemplateDepth);
2796 }
2797
2798 /// Build a new __builtin_choose_expr expression.
2799 ///
2800 /// By default, performs semantic analysis to build the new expression.
2801 /// Subclasses may override this routine to provide different behavior.
2802 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2803 Expr *Cond, Expr *LHS, Expr *RHS,
2804 SourceLocation RParenLoc) {
2805 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2806 Cond, LHS, RHS,
2807 RParenLoc);
2808 }
2809
2810 /// Build a new generic selection expression.
2811 ///
2812 /// By default, performs semantic analysis to build the new expression.
2813 /// Subclasses may override this routine to provide different behavior.
2814 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2815 SourceLocation DefaultLoc,
2816 SourceLocation RParenLoc,
2817 Expr *ControllingExpr,
2818 ArrayRef<TypeSourceInfo *> Types,
2819 ArrayRef<Expr *> Exprs) {
2820 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2821 ControllingExpr, Types, Exprs);
2822 }
2823
2824 /// Build a new overloaded operator call expression.
2825 ///
2826 /// By default, performs semantic analysis to build the new expression.
2827 /// The semantic analysis provides the behavior of template instantiation,
2828 /// copying with transformations that turn what looks like an overloaded
2829 /// operator call into a use of a builtin operator, performing
2830 /// argument-dependent lookup, etc. Subclasses may override this routine to
2831 /// provide different behavior.
2832 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2833 SourceLocation OpLoc,
2834 Expr *Callee,
2835 Expr *First,
2836 Expr *Second);
2837
2838 /// Build a new C++ "named" cast expression, such as static_cast or
2839 /// reinterpret_cast.
2840 ///
2841 /// By default, this routine dispatches to one of the more-specific routines
2842 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2843 /// Subclasses may override this routine to provide different behavior.
2844 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2845 Stmt::StmtClass Class,
2846 SourceLocation LAngleLoc,
2847 TypeSourceInfo *TInfo,
2848 SourceLocation RAngleLoc,
2849 SourceLocation LParenLoc,
2850 Expr *SubExpr,
2851 SourceLocation RParenLoc) {
2852 switch (Class) {
2853 case Stmt::CXXStaticCastExprClass:
2854 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2855 RAngleLoc, LParenLoc,
2856 SubExpr, RParenLoc);
2857
2858 case Stmt::CXXDynamicCastExprClass:
2859 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2860 RAngleLoc, LParenLoc,
2861 SubExpr, RParenLoc);
2862
2863 case Stmt::CXXReinterpretCastExprClass:
2864 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2865 RAngleLoc, LParenLoc,
2866 SubExpr,
2867 RParenLoc);
2868
2869 case Stmt::CXXConstCastExprClass:
2870 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2871 RAngleLoc, LParenLoc,
2872 SubExpr, RParenLoc);
2873
2874 case Stmt::CXXAddrspaceCastExprClass:
2875 return getDerived().RebuildCXXAddrspaceCastExpr(
2876 OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
2877
2878 default:
2879 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 2879)
;
2880 }
2881 }
2882
2883 /// Build a new C++ static_cast expression.
2884 ///
2885 /// By default, performs semantic analysis to build the new expression.
2886 /// Subclasses may override this routine to provide different behavior.
2887 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2888 SourceLocation LAngleLoc,
2889 TypeSourceInfo *TInfo,
2890 SourceLocation RAngleLoc,
2891 SourceLocation LParenLoc,
2892 Expr *SubExpr,
2893 SourceLocation RParenLoc) {
2894 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2895 TInfo, SubExpr,
2896 SourceRange(LAngleLoc, RAngleLoc),
2897 SourceRange(LParenLoc, RParenLoc));
2898 }
2899
2900 /// Build a new C++ dynamic_cast expression.
2901 ///
2902 /// By default, performs semantic analysis to build the new expression.
2903 /// Subclasses may override this routine to provide different behavior.
2904 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2905 SourceLocation LAngleLoc,
2906 TypeSourceInfo *TInfo,
2907 SourceLocation RAngleLoc,
2908 SourceLocation LParenLoc,
2909 Expr *SubExpr,
2910 SourceLocation RParenLoc) {
2911 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2912 TInfo, SubExpr,
2913 SourceRange(LAngleLoc, RAngleLoc),
2914 SourceRange(LParenLoc, RParenLoc));
2915 }
2916
2917 /// Build a new C++ reinterpret_cast expression.
2918 ///
2919 /// By default, performs semantic analysis to build the new expression.
2920 /// Subclasses may override this routine to provide different behavior.
2921 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2922 SourceLocation LAngleLoc,
2923 TypeSourceInfo *TInfo,
2924 SourceLocation RAngleLoc,
2925 SourceLocation LParenLoc,
2926 Expr *SubExpr,
2927 SourceLocation RParenLoc) {
2928 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2929 TInfo, SubExpr,
2930 SourceRange(LAngleLoc, RAngleLoc),
2931 SourceRange(LParenLoc, RParenLoc));
2932 }
2933
2934 /// Build a new C++ const_cast expression.
2935 ///
2936 /// By default, performs semantic analysis to build the new expression.
2937 /// Subclasses may override this routine to provide different behavior.
2938 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2939 SourceLocation LAngleLoc,
2940 TypeSourceInfo *TInfo,
2941 SourceLocation RAngleLoc,
2942 SourceLocation LParenLoc,
2943 Expr *SubExpr,
2944 SourceLocation RParenLoc) {
2945 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2946 TInfo, SubExpr,
2947 SourceRange(LAngleLoc, RAngleLoc),
2948 SourceRange(LParenLoc, RParenLoc));
2949 }
2950
2951 ExprResult
2952 RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
2953 TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
2954 SourceLocation LParenLoc, Expr *SubExpr,
2955 SourceLocation RParenLoc) {
2956 return getSema().BuildCXXNamedCast(
2957 OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
2958 SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
2959 }
2960
2961 /// Build a new C++ functional-style cast expression.
2962 ///
2963 /// By default, performs semantic analysis to build the new expression.
2964 /// Subclasses may override this routine to provide different behavior.
2965 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2966 SourceLocation LParenLoc,
2967 Expr *Sub,
2968 SourceLocation RParenLoc,
2969 bool ListInitialization) {
2970 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2971 MultiExprArg(&Sub, 1), RParenLoc,
2972 ListInitialization);
2973 }
2974
2975 /// Build a new C++ __builtin_bit_cast expression.
2976 ///
2977 /// By default, performs semantic analysis to build the new expression.
2978 /// Subclasses may override this routine to provide different behavior.
2979 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2980 TypeSourceInfo *TSI, Expr *Sub,
2981 SourceLocation RParenLoc) {
2982 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2983 }
2984
2985 /// Build a new C++ typeid(type) expression.
2986 ///
2987 /// By default, performs semantic analysis to build the new expression.
2988 /// Subclasses may override this routine to provide different behavior.
2989 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2990 SourceLocation TypeidLoc,
2991 TypeSourceInfo *Operand,
2992 SourceLocation RParenLoc) {
2993 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2994 RParenLoc);
2995 }
2996
2997
2998 /// Build a new C++ typeid(expr) expression.
2999 ///
3000 /// By default, performs semantic analysis to build the new expression.
3001 /// Subclasses may override this routine to provide different behavior.
3002 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3003 SourceLocation TypeidLoc,
3004 Expr *Operand,
3005 SourceLocation RParenLoc) {
3006 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3007 RParenLoc);
3008 }
3009
3010 /// Build a new C++ __uuidof(type) expression.
3011 ///
3012 /// By default, performs semantic analysis to build the new expression.
3013 /// Subclasses may override this routine to provide different behavior.
3014 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3015 TypeSourceInfo *Operand,
3016 SourceLocation RParenLoc) {
3017 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3018 }
3019
3020 /// Build a new C++ __uuidof(expr) expression.
3021 ///
3022 /// By default, performs semantic analysis to build the new expression.
3023 /// Subclasses may override this routine to provide different behavior.
3024 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3025 Expr *Operand, SourceLocation RParenLoc) {
3026 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3027 }
3028
3029 /// Build a new C++ "this" expression.
3030 ///
3031 /// By default, builds a new "this" expression without performing any
3032 /// semantic analysis. Subclasses may override this routine to provide
3033 /// different behavior.
3034 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3035 QualType ThisType,
3036 bool isImplicit) {
3037 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3038 }
3039
3040 /// Build a new C++ throw expression.
3041 ///
3042 /// By default, performs semantic analysis to build the new expression.
3043 /// Subclasses may override this routine to provide different behavior.
3044 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3045 bool IsThrownVariableInScope) {
3046 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3047 }
3048
3049 /// Build a new C++ default-argument expression.
3050 ///
3051 /// By default, builds a new default-argument expression, which does not
3052 /// require any semantic analysis. Subclasses may override this routine to
3053 /// provide different behavior.
3054 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
3055 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3056 getSema().CurContext);
3057 }
3058
3059 /// Build a new C++11 default-initialization expression.
3060 ///
3061 /// By default, builds a new default field initialization expression, which
3062 /// does not require any semantic analysis. Subclasses may override this
3063 /// routine to provide different behavior.
3064 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3065 FieldDecl *Field) {
3066 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
3067 getSema().CurContext);
3068 }
3069
3070 /// Build a new C++ zero-initialization expression.
3071 ///
3072 /// By default, performs semantic analysis to build the new expression.
3073 /// Subclasses may override this routine to provide different behavior.
3074 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3075 SourceLocation LParenLoc,
3076 SourceLocation RParenLoc) {
3077 return getSema().BuildCXXTypeConstructExpr(
3078 TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
3079 }
3080
3081 /// Build a new C++ "new" expression.
3082 ///
3083 /// By default, performs semantic analysis to build the new expression.
3084 /// Subclasses may override this routine to provide different behavior.
3085 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
3086 bool UseGlobal,
3087 SourceLocation PlacementLParen,
3088 MultiExprArg PlacementArgs,
3089 SourceLocation PlacementRParen,
3090 SourceRange TypeIdParens,
3091 QualType AllocatedType,
3092 TypeSourceInfo *AllocatedTypeInfo,
3093 Optional<Expr *> ArraySize,
3094 SourceRange DirectInitRange,
3095 Expr *Initializer) {
3096 return getSema().BuildCXXNew(StartLoc, UseGlobal,
3097 PlacementLParen,
3098 PlacementArgs,
3099 PlacementRParen,
3100 TypeIdParens,
3101 AllocatedType,
3102 AllocatedTypeInfo,
3103 ArraySize,
3104 DirectInitRange,
3105 Initializer);
3106 }
3107
3108 /// Build a new C++ "delete" expression.
3109 ///
3110 /// By default, performs semantic analysis to build the new expression.
3111 /// Subclasses may override this routine to provide different behavior.
3112 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3113 bool IsGlobalDelete,
3114 bool IsArrayForm,
3115 Expr *Operand) {
3116 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3117 Operand);
3118 }
3119
3120 /// Build a new type trait expression.
3121 ///
3122 /// By default, performs semantic analysis to build the new expression.
3123 /// Subclasses may override this routine to provide different behavior.
3124 ExprResult RebuildTypeTrait(TypeTrait Trait,
3125 SourceLocation StartLoc,
3126 ArrayRef<TypeSourceInfo *> Args,
3127 SourceLocation RParenLoc) {
3128 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3129 }
3130
3131 /// Build a new array type trait expression.
3132 ///
3133 /// By default, performs semantic analysis to build the new expression.
3134 /// Subclasses may override this routine to provide different behavior.
3135 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3136 SourceLocation StartLoc,
3137 TypeSourceInfo *TSInfo,
3138 Expr *DimExpr,
3139 SourceLocation RParenLoc) {
3140 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3141 }
3142
3143 /// Build a new expression trait expression.
3144 ///
3145 /// By default, performs semantic analysis to build the new expression.
3146 /// Subclasses may override this routine to provide different behavior.
3147 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3148 SourceLocation StartLoc,
3149 Expr *Queried,
3150 SourceLocation RParenLoc) {
3151 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3152 }
3153
3154 /// Build a new (previously unresolved) declaration reference
3155 /// expression.
3156 ///
3157 /// By default, performs semantic analysis to build the new expression.
3158 /// Subclasses may override this routine to provide different behavior.
3159 ExprResult RebuildDependentScopeDeclRefExpr(
3160 NestedNameSpecifierLoc QualifierLoc,
3161 SourceLocation TemplateKWLoc,
3162 const DeclarationNameInfo &NameInfo,
3163 const TemplateArgumentListInfo *TemplateArgs,
3164 bool IsAddressOfOperand,
3165 TypeSourceInfo **RecoveryTSI) {
3166 CXXScopeSpec SS;
3167 SS.Adopt(QualifierLoc);
3168
3169 if (TemplateArgs || TemplateKWLoc.isValid())
3170 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3171 TemplateArgs);
3172
3173 return getSema().BuildQualifiedDeclarationNameExpr(
3174 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3175 }
3176
3177 /// Build a new template-id expression.
3178 ///
3179 /// By default, performs semantic analysis to build the new expression.
3180 /// Subclasses may override this routine to provide different behavior.
3181 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3182 SourceLocation TemplateKWLoc,
3183 LookupResult &R,
3184 bool RequiresADL,
3185 const TemplateArgumentListInfo *TemplateArgs) {
3186 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3187 TemplateArgs);
3188 }
3189
3190 /// Build a new object-construction expression.
3191 ///
3192 /// By default, performs semantic analysis to build the new expression.
3193 /// Subclasses may override this routine to provide different behavior.
3194 ExprResult RebuildCXXConstructExpr(QualType T,
3195 SourceLocation Loc,
3196 CXXConstructorDecl *Constructor,
3197 bool IsElidable,
3198 MultiExprArg Args,
3199 bool HadMultipleCandidates,
3200 bool ListInitialization,
3201 bool StdInitListInitialization,
3202 bool RequiresZeroInit,
3203 CXXConstructExpr::ConstructionKind ConstructKind,
3204 SourceRange ParenRange) {
3205 // Reconstruct the constructor we originally found, which might be
3206 // different if this is a call to an inherited constructor.
3207 CXXConstructorDecl *FoundCtor = Constructor;
3208 if (Constructor->isInheritingConstructor())
3209 FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3210
3211 SmallVector<Expr *, 8> ConvertedArgs;
3212 if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3213 ConvertedArgs))
3214 return ExprError();
3215
3216 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3217 IsElidable,
3218 ConvertedArgs,
3219 HadMultipleCandidates,
3220 ListInitialization,
3221 StdInitListInitialization,
3222 RequiresZeroInit, ConstructKind,
3223 ParenRange);
3224 }
3225
3226 /// Build a new implicit construction via inherited constructor
3227 /// expression.
3228 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3229 CXXConstructorDecl *Constructor,
3230 bool ConstructsVBase,
3231 bool InheritedFromVBase) {
3232 return new (getSema().Context) CXXInheritedCtorInitExpr(
3233 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3234 }
3235
3236 /// Build a new object-construction expression.
3237 ///
3238 /// By default, performs semantic analysis to build the new expression.
3239 /// Subclasses may override this routine to provide different behavior.
3240 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3241 SourceLocation LParenOrBraceLoc,
3242 MultiExprArg Args,
3243 SourceLocation RParenOrBraceLoc,
3244 bool ListInitialization) {
3245 return getSema().BuildCXXTypeConstructExpr(
3246 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3247 }
3248
3249 /// Build a new object-construction expression.
3250 ///
3251 /// By default, performs semantic analysis to build the new expression.
3252 /// Subclasses may override this routine to provide different behavior.
3253 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3254 SourceLocation LParenLoc,
3255 MultiExprArg Args,
3256 SourceLocation RParenLoc,
3257 bool ListInitialization) {
3258 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3259 RParenLoc, ListInitialization);
3260 }
3261
3262 /// Build a new member reference expression.
3263 ///
3264 /// By default, performs semantic analysis to build the new expression.
3265 /// Subclasses may override this routine to provide different behavior.
3266 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3267 QualType BaseType,
3268 bool IsArrow,
3269 SourceLocation OperatorLoc,
3270 NestedNameSpecifierLoc QualifierLoc,
3271 SourceLocation TemplateKWLoc,
3272 NamedDecl *FirstQualifierInScope,
3273 const DeclarationNameInfo &MemberNameInfo,
3274 const TemplateArgumentListInfo *TemplateArgs) {
3275 CXXScopeSpec SS;
3276 SS.Adopt(QualifierLoc);
3277
3278 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3279 OperatorLoc, IsArrow,
3280 SS, TemplateKWLoc,
3281 FirstQualifierInScope,
3282 MemberNameInfo,
3283 TemplateArgs, /*S*/nullptr);
3284 }
3285
3286 /// Build a new member reference expression.
3287 ///
3288 /// By default, performs semantic analysis to build the new expression.
3289 /// Subclasses may override this routine to provide different behavior.
3290 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3291 SourceLocation OperatorLoc,
3292 bool IsArrow,
3293 NestedNameSpecifierLoc QualifierLoc,
3294 SourceLocation TemplateKWLoc,
3295 NamedDecl *FirstQualifierInScope,
3296 LookupResult &R,
3297 const TemplateArgumentListInfo *TemplateArgs) {
3298 CXXScopeSpec SS;
3299 SS.Adopt(QualifierLoc);
3300
3301 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3302 OperatorLoc, IsArrow,
3303 SS, TemplateKWLoc,
3304 FirstQualifierInScope,
3305 R, TemplateArgs, /*S*/nullptr);
3306 }
3307
3308 /// Build a new noexcept expression.
3309 ///
3310 /// By default, performs semantic analysis to build the new expression.
3311 /// Subclasses may override this routine to provide different behavior.
3312 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3313 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3314 }
3315
3316 /// Build a new expression to compute the length of a parameter pack.
3317 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3318 NamedDecl *Pack,
3319 SourceLocation PackLoc,
3320 SourceLocation RParenLoc,
3321 Optional<unsigned> Length,
3322 ArrayRef<TemplateArgument> PartialArgs) {
3323 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3324 RParenLoc, Length, PartialArgs);
3325 }
3326
3327 /// Build a new expression representing a call to a source location
3328 /// builtin.
3329 ///
3330 /// By default, performs semantic analysis to build the new expression.
3331 /// Subclasses may override this routine to provide different behavior.
3332 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3333 SourceLocation BuiltinLoc,
3334 SourceLocation RPLoc,
3335 DeclContext *ParentContext) {
3336 return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3337 }
3338
3339 /// Build a new Objective-C boxed expression.
3340 ///
3341 /// By default, performs semantic analysis to build the new expression.
3342 /// Subclasses may override this routine to provide different behavior.
3343 ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3344 SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3345 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3346 TemplateArgumentListInfo *TALI) {
3347 CXXScopeSpec SS;
3348 SS.Adopt(NNS);
3349 ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3350 ConceptNameInfo,
3351 FoundDecl,
3352 NamedConcept, TALI);
3353 if (Result.isInvalid())
3354 return ExprError();
3355 return Result;
3356 }
3357
3358 /// \brief Build a new requires expression.
3359 ///
3360 /// By default, performs semantic analysis to build the new expression.
3361 /// Subclasses may override this routine to provide different behavior.
3362 ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3363 RequiresExprBodyDecl *Body,
3364 ArrayRef<ParmVarDecl *> LocalParameters,
3365 ArrayRef<concepts::Requirement *> Requirements,
3366 SourceLocation ClosingBraceLoc) {
3367 return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3368 LocalParameters, Requirements, ClosingBraceLoc);
3369 }
3370
3371 concepts::TypeRequirement *
3372 RebuildTypeRequirement(
3373 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3374 return SemaRef.BuildTypeRequirement(SubstDiag);
3375 }
3376
3377 concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3378 return SemaRef.BuildTypeRequirement(T);
3379 }
3380
3381 concepts::ExprRequirement *
3382 RebuildExprRequirement(
3383 concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3384 SourceLocation NoexceptLoc,
3385 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3386 return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3387 std::move(Ret));
3388 }
3389
3390 concepts::ExprRequirement *
3391 RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3392 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3393 return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3394 std::move(Ret));
3395 }
3396
3397 concepts::NestedRequirement *
3398 RebuildNestedRequirement(
3399 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3400 return SemaRef.BuildNestedRequirement(SubstDiag);
3401 }
3402
3403 concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3404 return SemaRef.BuildNestedRequirement(Constraint);
3405 }
3406
3407 /// \brief Build a new Objective-C boxed expression.
3408 ///
3409 /// By default, performs semantic analysis to build the new expression.
3410 /// Subclasses may override this routine to provide different behavior.
3411 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3412 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3413 }
3414
3415 /// Build a new Objective-C array literal.
3416 ///
3417 /// By default, performs semantic analysis to build the new expression.
3418 /// Subclasses may override this routine to provide different behavior.
3419 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3420 Expr **Elements, unsigned NumElements) {
3421 return getSema().BuildObjCArrayLiteral(Range,
3422 MultiExprArg(Elements, NumElements));
3423 }
3424
3425 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3426 Expr *Base, Expr *Key,
3427 ObjCMethodDecl *getterMethod,
3428 ObjCMethodDecl *setterMethod) {
3429 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3430 getterMethod, setterMethod);
3431 }
3432
3433 /// Build a new Objective-C dictionary literal.
3434 ///
3435 /// By default, performs semantic analysis to build the new expression.
3436 /// Subclasses may override this routine to provide different behavior.
3437 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3438 MutableArrayRef<ObjCDictionaryElement> Elements) {
3439 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3440 }
3441
3442 /// Build a new Objective-C \@encode expression.
3443 ///
3444 /// By default, performs semantic analysis to build the new expression.
3445 /// Subclasses may override this routine to provide different behavior.
3446 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3447 TypeSourceInfo *EncodeTypeInfo,
3448 SourceLocation RParenLoc) {
3449 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3450 }
3451
3452 /// Build a new Objective-C class message.
3453 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3454 Selector Sel,
3455 ArrayRef<SourceLocation> SelectorLocs,
3456 ObjCMethodDecl *Method,
3457 SourceLocation LBracLoc,
3458 MultiExprArg Args,
3459 SourceLocation RBracLoc) {
3460 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3461 ReceiverTypeInfo->getType(),
3462 /*SuperLoc=*/SourceLocation(),
3463 Sel, Method, LBracLoc, SelectorLocs,
3464 RBracLoc, Args);
3465 }
3466
3467 /// Build a new Objective-C instance message.
3468 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3469 Selector Sel,
3470 ArrayRef<SourceLocation> SelectorLocs,
3471 ObjCMethodDecl *Method,
3472 SourceLocation LBracLoc,
3473 MultiExprArg Args,
3474 SourceLocation RBracLoc) {
3475 return SemaRef.BuildInstanceMessage(Receiver,
3476 Receiver->getType(),
3477 /*SuperLoc=*/SourceLocation(),
3478 Sel, Method, LBracLoc, SelectorLocs,
3479 RBracLoc, Args);
3480 }
3481
3482 /// Build a new Objective-C instance/class message to 'super'.
3483 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3484 Selector Sel,
3485 ArrayRef<SourceLocation> SelectorLocs,
3486 QualType SuperType,
3487 ObjCMethodDecl *Method,
3488 SourceLocation LBracLoc,
3489 MultiExprArg Args,
3490 SourceLocation RBracLoc) {
3491 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3492 SuperType,
3493 SuperLoc,
3494 Sel, Method, LBracLoc, SelectorLocs,
3495 RBracLoc, Args)
3496 : SemaRef.BuildClassMessage(nullptr,
3497 SuperType,
3498 SuperLoc,
3499 Sel, Method, LBracLoc, SelectorLocs,
3500 RBracLoc, Args);
3501
3502
3503 }
3504
3505 /// Build a new Objective-C ivar reference expression.
3506 ///
3507 /// By default, performs semantic analysis to build the new expression.
3508 /// Subclasses may override this routine to provide different behavior.
3509 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3510 SourceLocation IvarLoc,
3511 bool IsArrow, bool IsFreeIvar) {
3512 CXXScopeSpec SS;
3513 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3514 ExprResult Result = getSema().BuildMemberReferenceExpr(
3515 BaseArg, BaseArg->getType(),
3516 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3517 /*FirstQualifierInScope=*/nullptr, NameInfo,
3518 /*TemplateArgs=*/nullptr,
3519 /*S=*/nullptr);
3520 if (IsFreeIvar && Result.isUsable())
3521 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3522 return Result;
3523 }
3524
3525 /// Build a new Objective-C property reference expression.
3526 ///
3527 /// By default, performs semantic analysis to build the new expression.
3528 /// Subclasses may override this routine to provide different behavior.
3529 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3530 ObjCPropertyDecl *Property,
3531 SourceLocation PropertyLoc) {
3532 CXXScopeSpec SS;
3533 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3534 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3535 /*FIXME:*/PropertyLoc,
3536 /*IsArrow=*/false,
3537 SS, SourceLocation(),
3538 /*FirstQualifierInScope=*/nullptr,
3539 NameInfo,
3540 /*TemplateArgs=*/nullptr,
3541 /*S=*/nullptr);
3542 }
3543
3544 /// Build a new Objective-C property reference expression.
3545 ///
3546 /// By default, performs semantic analysis to build the new expression.
3547 /// Subclasses may override this routine to provide different behavior.
3548 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3549 ObjCMethodDecl *Getter,
3550 ObjCMethodDecl *Setter,
3551 SourceLocation PropertyLoc) {
3552 // Since these expressions can only be value-dependent, we do not
3553 // need to perform semantic analysis again.
3554 return Owned(
3555 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3556 VK_LValue, OK_ObjCProperty,
3557 PropertyLoc, Base));
3558 }
3559
3560 /// Build a new Objective-C "isa" expression.
3561 ///
3562 /// By default, performs semantic analysis to build the new expression.
3563 /// Subclasses may override this routine to provide different behavior.
3564 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3565 SourceLocation OpLoc, bool IsArrow) {
3566 CXXScopeSpec SS;
3567 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3568 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3569 OpLoc, IsArrow,
3570 SS, SourceLocation(),
3571 /*FirstQualifierInScope=*/nullptr,
3572 NameInfo,
3573 /*TemplateArgs=*/nullptr,
3574 /*S=*/nullptr);
3575 }
3576
3577 /// Build a new shuffle vector expression.
3578 ///
3579 /// By default, performs semantic analysis to build the new expression.
3580 /// Subclasses may override this routine to provide different behavior.
3581 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3582 MultiExprArg SubExprs,
3583 SourceLocation RParenLoc) {
3584 // Find the declaration for __builtin_shufflevector
3585 const IdentifierInfo &Name
3586 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3587 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3588 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3589 assert(!Lookup.empty() && "No __builtin_shufflevector?")((!Lookup.empty() && "No __builtin_shufflevector?") ?
static_cast<void> (0) : __assert_fail ("!Lookup.empty() && \"No __builtin_shufflevector?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 3589, __PRETTY_FUNCTION__))
;
3590
3591 // Build a reference to the __builtin_shufflevector builtin
3592 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3593 Expr *Callee = new (SemaRef.Context)
3594 DeclRefExpr(SemaRef.Context, Builtin, false,
3595 SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3596 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3597 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3598 CK_BuiltinFnToFnPtr).get();
3599
3600 // Build the CallExpr
3601 ExprResult TheCall = CallExpr::Create(
3602 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3603 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3604 FPOptionsOverride());
3605
3606 // Type-check the __builtin_shufflevector expression.
3607 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3608 }
3609
3610 /// Build a new convert vector expression.
3611 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3612 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3613 SourceLocation RParenLoc) {
3614 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3615 BuiltinLoc, RParenLoc);
3616 }
3617
3618 /// Build a new template argument pack expansion.
3619 ///
3620 /// By default, performs semantic analysis to build a new pack expansion
3621 /// for a template argument. Subclasses may override this routine to provide
3622 /// different behavior.
3623 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3624 SourceLocation EllipsisLoc,
3625 Optional<unsigned> NumExpansions) {
3626 switch (Pattern.getArgument().getKind()) {
3627 case TemplateArgument::Expression: {
3628 ExprResult Result
3629 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3630 EllipsisLoc, NumExpansions);
3631 if (Result.isInvalid())
3632 return TemplateArgumentLoc();
3633
3634 return TemplateArgumentLoc(Result.get(), Result.get());
3635 }
3636
3637 case TemplateArgument::Template:
3638 return TemplateArgumentLoc(
3639 SemaRef.Context,
3640 TemplateArgument(Pattern.getArgument().getAsTemplate(),
3641 NumExpansions),
3642 Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3643 EllipsisLoc);
3644
3645 case TemplateArgument::Null:
3646 case TemplateArgument::Integral:
3647 case TemplateArgument::Declaration:
3648 case TemplateArgument::Pack:
3649 case TemplateArgument::TemplateExpansion:
3650 case TemplateArgument::NullPtr:
3651 llvm_unreachable("Pack expansion pattern has no parameter packs")::llvm::llvm_unreachable_internal("Pack expansion pattern has no parameter packs"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 3651)
;
3652
3653 case TemplateArgument::Type:
3654 if (TypeSourceInfo *Expansion
3655 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3656 EllipsisLoc,
3657 NumExpansions))
3658 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3659 Expansion);
3660 break;
3661 }
3662
3663 return TemplateArgumentLoc();
3664 }
3665
3666 /// Build a new expression pack expansion.
3667 ///
3668 /// By default, performs semantic analysis to build a new pack expansion
3669 /// for an expression. Subclasses may override this routine to provide
3670 /// different behavior.
3671 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3672 Optional<unsigned> NumExpansions) {
3673 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3674 }
3675
3676 /// Build a new C++1z fold-expression.
3677 ///
3678 /// By default, performs semantic analysis in order to build a new fold
3679 /// expression.
3680 ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3681 SourceLocation LParenLoc, Expr *LHS,
3682 BinaryOperatorKind Operator,
3683 SourceLocation EllipsisLoc, Expr *RHS,
3684 SourceLocation RParenLoc,
3685 Optional<unsigned> NumExpansions) {
3686 return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3687 EllipsisLoc, RHS, RParenLoc,
3688 NumExpansions);
3689 }
3690
3691 /// Build an empty C++1z fold-expression with the given operator.
3692 ///
3693 /// By default, produces the fallback value for the fold-expression, or
3694 /// produce an error if there is no fallback value.
3695 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3696 BinaryOperatorKind Operator) {
3697 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3698 }
3699
3700 /// Build a new atomic operation expression.
3701 ///
3702 /// By default, performs semantic analysis to build the new expression.
3703 /// Subclasses may override this routine to provide different behavior.
3704 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3705 AtomicExpr::AtomicOp Op,
3706 SourceLocation RParenLoc) {
3707 // Use this for all of the locations, since we don't know the difference
3708 // between the call and the expr at this point.
3709 SourceRange Range{BuiltinLoc, RParenLoc};
3710 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3711 Sema::AtomicArgumentOrder::AST);
3712 }
3713
3714 ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3715 ArrayRef<Expr *> SubExprs, QualType Type) {
3716 return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3717 }
3718
3719private:
3720 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3721 QualType ObjectType,
3722 NamedDecl *FirstQualifierInScope,
3723 CXXScopeSpec &SS);
3724
3725 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3726 QualType ObjectType,
3727 NamedDecl *FirstQualifierInScope,
3728 CXXScopeSpec &SS);
3729
3730 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3731 NamedDecl *FirstQualifierInScope,
3732 CXXScopeSpec &SS);
3733
3734 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3735 DependentNameTypeLoc TL,
3736 bool DeducibleTSTContext);
3737};
3738
3739template <typename Derived>
3740StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3741 if (!S)
3742 return S;
3743
3744 switch (S->getStmtClass()) {
3745 case Stmt::NoStmtClass: break;
3746
3747 // Transform individual statement nodes
3748 // Pass SDK into statements that can produce a value
3749#define STMT(Node, Parent) \
3750 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3751#define VALUESTMT(Node, Parent) \
3752 case Stmt::Node##Class: \
3753 return getDerived().Transform##Node(cast<Node>(S), SDK);
3754#define ABSTRACT_STMT(Node)
3755#define EXPR(Node, Parent)
3756#include "clang/AST/StmtNodes.inc"
3757
3758 // Transform expressions by calling TransformExpr.
3759#define STMT(Node, Parent)
3760#define ABSTRACT_STMT(Stmt)
3761#define EXPR(Node, Parent) case Stmt::Node##Class:
3762#include "clang/AST/StmtNodes.inc"
3763 {
3764 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3765
3766 if (SDK == SDK_StmtExprResult)
3767 E = getSema().ActOnStmtExprResult(E);
3768 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3769 }
3770 }
3771
3772 return S;
3773}
3774
3775template<typename Derived>
3776OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3777 if (!S)
3778 return S;
3779
3780 switch (S->getClauseKind()) {
3781 default: break;
3782 // Transform individual clause nodes
3783#define GEN_CLANG_CLAUSE_CLASS
3784#define CLAUSE_CLASS(Enum, Str, Class) \
3785 case Enum: \
3786 return getDerived().Transform##Class(cast<Class>(S));
3787#include "llvm/Frontend/OpenMP/OMP.inc"
3788 }
3789
3790 return S;
3791}
3792
3793
3794template<typename Derived>
3795ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3796 if (!E)
3797 return E;
3798
3799 switch (E->getStmtClass()) {
3800 case Stmt::NoStmtClass: break;
3801#define STMT(Node, Parent) case Stmt::Node##Class: break;
3802#define ABSTRACT_STMT(Stmt)
3803#define EXPR(Node, Parent) \
3804 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3805#include "clang/AST/StmtNodes.inc"
3806 }
3807
3808 return E;
3809}
3810
3811template<typename Derived>
3812ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3813 bool NotCopyInit) {
3814 // Initializers are instantiated like expressions, except that various outer
3815 // layers are stripped.
3816 if (!Init)
3817 return Init;
3818
3819 if (auto *FE = dyn_cast<FullExpr>(Init))
3820 Init = FE->getSubExpr();
3821
3822 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3823 Init = AIL->getCommonExpr();
3824
3825 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3826 Init = MTE->getSubExpr();
3827
3828 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3829 Init = Binder->getSubExpr();
3830
3831 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3832 Init = ICE->getSubExprAsWritten();
3833
3834 if (CXXStdInitializerListExpr *ILE =
3835 dyn_cast<CXXStdInitializerListExpr>(Init))
3836 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3837
3838 // If this is copy-initialization, we only need to reconstruct
3839 // InitListExprs. Other forms of copy-initialization will be a no-op if
3840 // the initializer is already the right type.
3841 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3842 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3843 return getDerived().TransformExpr(Init);
3844
3845 // Revert value-initialization back to empty parens.
3846 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3847 SourceRange Parens = VIE->getSourceRange();
3848 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3849 Parens.getEnd());
3850 }
3851
3852 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3853 if (isa<ImplicitValueInitExpr>(Init))
3854 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3855 SourceLocation());
3856
3857 // Revert initialization by constructor back to a parenthesized or braced list
3858 // of expressions. Any other form of initializer can just be reused directly.
3859 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3860 return getDerived().TransformExpr(Init);
3861
3862 // If the initialization implicitly converted an initializer list to a
3863 // std::initializer_list object, unwrap the std::initializer_list too.
3864 if (Construct && Construct->isStdInitListInitialization())
3865 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3866
3867 // Enter a list-init context if this was list initialization.
3868 EnterExpressionEvaluationContext Context(
3869 getSema(), EnterExpressionEvaluationContext::InitList,
3870 Construct->isListInitialization());
3871
3872 SmallVector<Expr*, 8> NewArgs;
3873 bool ArgChanged = false;
3874 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3875 /*IsCall*/true, NewArgs, &ArgChanged))
3876 return ExprError();
3877
3878 // If this was list initialization, revert to syntactic list form.
3879 if (Construct->isListInitialization())
3880 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3881 Construct->getEndLoc());
3882
3883 // Build a ParenListExpr to represent anything else.
3884 SourceRange Parens = Construct->getParenOrBraceRange();
3885 if (Parens.isInvalid()) {
3886 // This was a variable declaration's initialization for which no initializer
3887 // was specified.
3888 assert(NewArgs.empty() &&((NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? static_cast<void> (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 3889, __PRETTY_FUNCTION__))
3889 "no parens or braces but have direct init with arguments?")((NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? static_cast<void> (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 3889, __PRETTY_FUNCTION__))
;
3890 return ExprEmpty();
3891 }
3892 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3893 Parens.getEnd());
3894}
3895
3896template<typename Derived>
3897bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3898 unsigned NumInputs,
3899 bool IsCall,
3900 SmallVectorImpl<Expr *> &Outputs,
3901 bool *ArgChanged) {
3902 for (unsigned I = 0; I != NumInputs; ++I) {
3903 // If requested, drop call arguments that need to be dropped.
3904 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3905 if (ArgChanged)
3906 *ArgChanged = true;
3907
3908 break;
3909 }
3910
3911 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3912 Expr *Pattern = Expansion->getPattern();
3913
3914 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3915 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3916 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 3916, __PRETTY_FUNCTION__))
;
3917
3918 // Determine whether the set of unexpanded parameter packs can and should
3919 // be expanded.
3920 bool Expand = true;
3921 bool RetainExpansion = false;
3922 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3923 Optional<unsigned> NumExpansions = OrigNumExpansions;
3924 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3925 Pattern->getSourceRange(),
3926 Unexpanded,
3927 Expand, RetainExpansion,
3928 NumExpansions))
3929 return true;
3930
3931 if (!Expand) {
3932 // The transform has determined that we should perform a simple
3933 // transformation on the pack expansion, producing another pack
3934 // expansion.
3935 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3936 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3937 if (OutPattern.isInvalid())
3938 return true;
3939
3940 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3941 Expansion->getEllipsisLoc(),
3942 NumExpansions);
3943 if (Out.isInvalid())
3944 return true;
3945
3946 if (ArgChanged)
3947 *ArgChanged = true;
3948 Outputs.push_back(Out.get());
3949 continue;
3950 }
3951
3952 // Record right away that the argument was changed. This needs
3953 // to happen even if the array expands to nothing.
3954 if (ArgChanged) *ArgChanged = true;
3955
3956 // The transform has determined that we should perform an elementwise
3957 // expansion of the pattern. Do so.
3958 for (unsigned I = 0; I != *NumExpansions; ++I) {
3959 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3960 ExprResult Out = getDerived().TransformExpr(Pattern);
3961 if (Out.isInvalid())
3962 return true;
3963
3964 if (Out.get()->containsUnexpandedParameterPack()) {
3965 Out = getDerived().RebuildPackExpansion(
3966 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3967 if (Out.isInvalid())
3968 return true;
3969 }
3970
3971 Outputs.push_back(Out.get());
3972 }
3973
3974 // If we're supposed to retain a pack expansion, do so by temporarily
3975 // forgetting the partially-substituted parameter pack.
3976 if (RetainExpansion) {
3977 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3978
3979 ExprResult Out = getDerived().TransformExpr(Pattern);
3980 if (Out.isInvalid())
3981 return true;
3982
3983 Out = getDerived().RebuildPackExpansion(
3984 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3985 if (Out.isInvalid())
3986 return true;
3987
3988 Outputs.push_back(Out.get());
3989 }
3990
3991 continue;
3992 }
3993
3994 ExprResult Result =
3995 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3996 : getDerived().TransformExpr(Inputs[I]);
3997 if (Result.isInvalid())
3998 return true;
3999
4000 if (Result.get() != Inputs[I] && ArgChanged)
4001 *ArgChanged = true;
4002
4003 Outputs.push_back(Result.get());
4004 }
4005
4006 return false;
4007}
4008
4009template <typename Derived>
4010Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4011 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4012 if (Var) {
4013 VarDecl *ConditionVar = cast_or_null<VarDecl>(
4014 getDerived().TransformDefinition(Var->getLocation(), Var));
4015
4016 if (!ConditionVar)
4017 return Sema::ConditionError();
4018
4019 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4020 }
4021
4022 if (Expr) {
4023 ExprResult CondExpr = getDerived().TransformExpr(Expr);
4024
4025 if (CondExpr.isInvalid())
4026 return Sema::ConditionError();
4027
4028 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
4029 }
4030
4031 return Sema::ConditionResult();
4032}
4033
4034template<typename Derived>
4035NestedNameSpecifierLoc
4036TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4037 NestedNameSpecifierLoc NNS,
4038 QualType ObjectType,
4039 NamedDecl *FirstQualifierInScope) {
4040 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4041 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4042 Qualifier = Qualifier.getPrefix())
4043 Qualifiers.push_back(Qualifier);
4044
4045 CXXScopeSpec SS;
4046 while (!Qualifiers.empty()) {
4047 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4048 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4049
4050 switch (QNNS->getKind()) {
4051 case NestedNameSpecifier::Identifier: {
4052 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4053 Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
4054 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4055 SS, FirstQualifierInScope, false))
4056 return NestedNameSpecifierLoc();
4057 }
4058 break;
4059
4060 case NestedNameSpecifier::Namespace: {
4061 NamespaceDecl *NS
4062 = cast_or_null<NamespaceDecl>(
4063 getDerived().TransformDecl(
4064 Q.getLocalBeginLoc(),
4065 QNNS->getAsNamespace()));
4066 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4067 break;
4068 }
4069
4070 case NestedNameSpecifier::NamespaceAlias: {
4071 NamespaceAliasDecl *Alias
4072 = cast_or_null<NamespaceAliasDecl>(
4073 getDerived().TransformDecl(Q.getLocalBeginLoc(),
4074 QNNS->getAsNamespaceAlias()));
4075 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4076 Q.getLocalEndLoc());
4077 break;
4078 }
4079
4080 case NestedNameSpecifier::Global:
4081 // There is no meaningful transformation that one could perform on the
4082 // global scope.
4083 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4084 break;
4085
4086 case NestedNameSpecifier::Super: {
4087 CXXRecordDecl *RD =
4088 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4089 SourceLocation(), QNNS->getAsRecordDecl()));
4090 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4091 break;
4092 }
4093
4094 case NestedNameSpecifier::TypeSpecWithTemplate:
4095 case NestedNameSpecifier::TypeSpec: {
4096 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4097 FirstQualifierInScope, SS);
4098
4099 if (!TL)
4100 return NestedNameSpecifierLoc();
4101
4102 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
4103 (SemaRef.getLangOpts().CPlusPlus11 &&
4104 TL.getType()->isEnumeralType())) {
4105 assert(!TL.getType().hasLocalQualifiers() &&((!TL.getType().hasLocalQualifiers() && "Can't get cv-qualifiers here"
) ? static_cast<void> (0) : __assert_fail ("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4106, __PRETTY_FUNCTION__))
4106 "Can't get cv-qualifiers here")((!TL.getType().hasLocalQualifiers() && "Can't get cv-qualifiers here"
) ? static_cast<void> (0) : __assert_fail ("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4106, __PRETTY_FUNCTION__))
;
4107 if (TL.getType()->isEnumeralType())
4108 SemaRef.Diag(TL.getBeginLoc(),
4109 diag::warn_cxx98_compat_enum_nested_name_spec);
4110 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
4111 Q.getLocalEndLoc());
4112 break;
4113 }
4114 // If the nested-name-specifier is an invalid type def, don't emit an
4115 // error because a previous error should have already been emitted.
4116 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
4117 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4118 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4119 << TL.getType() << SS.getRange();
4120 }
4121 return NestedNameSpecifierLoc();
4122 }
4123 }
4124
4125 // The qualifier-in-scope and object type only apply to the leftmost entity.
4126 FirstQualifierInScope = nullptr;
4127 ObjectType = QualType();
4128 }
4129
4130 // Don't rebuild the nested-name-specifier if we don't have to.
4131 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4132 !getDerived().AlwaysRebuild())
4133 return NNS;
4134
4135 // If we can re-use the source-location data from the original
4136 // nested-name-specifier, do so.
4137 if (SS.location_size() == NNS.getDataLength() &&
4138 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4139 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4140
4141 // Allocate new nested-name-specifier location information.
4142 return SS.getWithLocInContext(SemaRef.Context);
4143}
4144
4145template<typename Derived>
4146DeclarationNameInfo
4147TreeTransform<Derived>
4148::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4149 DeclarationName Name = NameInfo.getName();
4150 if (!Name)
4151 return DeclarationNameInfo();
4152
4153 switch (Name.getNameKind()) {
4154 case DeclarationName::Identifier:
4155 case DeclarationName::ObjCZeroArgSelector:
4156 case DeclarationName::ObjCOneArgSelector:
4157 case DeclarationName::ObjCMultiArgSelector:
4158 case DeclarationName::CXXOperatorName:
4159 case DeclarationName::CXXLiteralOperatorName:
4160 case DeclarationName::CXXUsingDirective:
4161 return NameInfo;
4162
4163 case DeclarationName::CXXDeductionGuideName: {
4164 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4165 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4166 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4167 if (!NewTemplate)
4168 return DeclarationNameInfo();
4169
4170 DeclarationNameInfo NewNameInfo(NameInfo);
4171 NewNameInfo.setName(
4172 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4173 return NewNameInfo;
4174 }
4175
4176 case DeclarationName::CXXConstructorName:
4177 case DeclarationName::CXXDestructorName:
4178 case DeclarationName::CXXConversionFunctionName: {
4179 TypeSourceInfo *NewTInfo;
4180 CanQualType NewCanTy;
4181 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4182 NewTInfo = getDerived().TransformType(OldTInfo);
4183 if (!NewTInfo)
4184 return DeclarationNameInfo();
4185 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4186 }
4187 else {
4188 NewTInfo = nullptr;
4189 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4190 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4191 if (NewT.isNull())
4192 return DeclarationNameInfo();
4193 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4194 }
4195
4196 DeclarationName NewName
4197 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4198 NewCanTy);
4199 DeclarationNameInfo NewNameInfo(NameInfo);
4200 NewNameInfo.setName(NewName);
4201 NewNameInfo.setNamedTypeInfo(NewTInfo);
4202 return NewNameInfo;
4203 }
4204 }
4205
4206 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4206)
;
4207}
4208
4209template<typename Derived>
4210TemplateName
4211TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4212 TemplateName Name,
4213 SourceLocation NameLoc,
4214 QualType ObjectType,
4215 NamedDecl *FirstQualifierInScope,
4216 bool AllowInjectedClassName) {
4217 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4218 TemplateDecl *Template = QTN->getTemplateDecl();
4219 assert(Template && "qualified template name must refer to a template")((Template && "qualified template name must refer to a template"
) ? static_cast<void> (0) : __assert_fail ("Template && \"qualified template name must refer to a template\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4219, __PRETTY_FUNCTION__))
;
4220
4221 TemplateDecl *TransTemplate
4222 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4223 Template));
4224 if (!TransTemplate)
4225 return TemplateName();
4226
4227 if (!getDerived().AlwaysRebuild() &&
4228 SS.getScopeRep() == QTN->getQualifier() &&
4229 TransTemplate == Template)
4230 return Name;
4231
4232 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4233 TransTemplate);
4234 }
4235
4236 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4237 if (SS.getScopeRep()) {
4238 // These apply to the scope specifier, not the template.
4239 ObjectType = QualType();
4240 FirstQualifierInScope = nullptr;
4241 }
4242
4243 if (!getDerived().AlwaysRebuild() &&
4244 SS.getScopeRep() == DTN->getQualifier() &&
4245 ObjectType.isNull())
4246 return Name;
4247
4248 // FIXME: Preserve the location of the "template" keyword.
4249 SourceLocation TemplateKWLoc = NameLoc;
4250
4251 if (DTN->isIdentifier()) {
4252 return getDerived().RebuildTemplateName(SS,
4253 TemplateKWLoc,
4254 *DTN->getIdentifier(),
4255 NameLoc,
4256 ObjectType,
4257 FirstQualifierInScope,
4258 AllowInjectedClassName);
4259 }
4260
4261 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4262 DTN->getOperator(), NameLoc,
4263 ObjectType, AllowInjectedClassName);
4264 }
4265
4266 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4267 TemplateDecl *TransTemplate
4268 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4269 Template));
4270 if (!TransTemplate)
4271 return TemplateName();
4272
4273 if (!getDerived().AlwaysRebuild() &&
4274 TransTemplate == Template)
4275 return Name;
4276
4277 return TemplateName(TransTemplate);
4278 }
4279
4280 if (SubstTemplateTemplateParmPackStorage *SubstPack
4281 = Name.getAsSubstTemplateTemplateParmPack()) {
4282 TemplateTemplateParmDecl *TransParam
4283 = cast_or_null<TemplateTemplateParmDecl>(
4284 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4285 if (!TransParam)
4286 return TemplateName();
4287
4288 if (!getDerived().AlwaysRebuild() &&
4289 TransParam == SubstPack->getParameterPack())
4290 return Name;
4291
4292 return getDerived().RebuildTemplateName(TransParam,
4293 SubstPack->getArgumentPack());
4294 }
4295
4296 // These should be getting filtered out before they reach the AST.
4297 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4297)
;
4298}
4299
4300template<typename Derived>
4301void TreeTransform<Derived>::InventTemplateArgumentLoc(
4302 const TemplateArgument &Arg,
4303 TemplateArgumentLoc &Output) {
4304 Output = getSema().getTrivialTemplateArgumentLoc(
4305 Arg, QualType(), getDerived().getBaseLocation());
4306}
4307
4308template<typename Derived>
4309bool TreeTransform<Derived>::TransformTemplateArgument(
4310 const TemplateArgumentLoc &Input,
4311 TemplateArgumentLoc &Output, bool Uneval) {
4312 const TemplateArgument &Arg = Input.getArgument();
4313 switch (Arg.getKind()) {
4314 case TemplateArgument::Null:
4315 case TemplateArgument::Pack:
4316 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4316)
;
4317
4318 case TemplateArgument::Integral:
4319 case TemplateArgument::NullPtr:
4320 case TemplateArgument::Declaration: {
4321 // Transform a resolved template argument straight to a resolved template
4322 // argument. We get here when substituting into an already-substituted
4323 // template type argument during concept satisfaction checking.
4324 QualType T = Arg.getNonTypeTemplateArgumentType();
4325 QualType NewT = getDerived().TransformType(T);
4326 if (NewT.isNull())
4327 return true;
4328
4329 ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4330 ? Arg.getAsDecl()
4331 : nullptr;
4332 ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4333 getDerived().getBaseLocation(), D))
4334 : nullptr;
4335 if (D && !NewD)
4336 return true;
4337
4338 if (NewT == T && D == NewD)
4339 Output = Input;
4340 else if (Arg.getKind() == TemplateArgument::Integral)
4341 Output = TemplateArgumentLoc(
4342 TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4343 TemplateArgumentLocInfo());
4344 else if (Arg.getKind() == TemplateArgument::NullPtr)
4345 Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4346 TemplateArgumentLocInfo());
4347 else
4348 Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4349 TemplateArgumentLocInfo());
4350
4351 return false;
4352 }
4353
4354 case TemplateArgument::Type: {
4355 TypeSourceInfo *DI = Input.getTypeSourceInfo();
4356 if (!DI)
4357 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4358
4359 DI = getDerived().TransformType(DI);
4360 if (!DI) return true;
4361
4362 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4363 return false;
4364 }
4365
4366 case TemplateArgument::Template: {
4367 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4368 if (QualifierLoc) {
4369 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4370 if (!QualifierLoc)
4371 return true;
4372 }
4373
4374 CXXScopeSpec SS;
4375 SS.Adopt(QualifierLoc);
4376 TemplateName Template
4377 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4378 Input.getTemplateNameLoc());
4379 if (Template.isNull())
4380 return true;
4381
4382 Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4383 QualifierLoc, Input.getTemplateNameLoc());
4384 return false;
4385 }
4386
4387 case TemplateArgument::TemplateExpansion:
4388 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4388)
;
4389
4390 case TemplateArgument::Expression: {
4391 // Template argument expressions are constant expressions.
4392 EnterExpressionEvaluationContext Unevaluated(
4393 getSema(),
4394 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4395 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4396 /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4397 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4398
4399 Expr *InputExpr = Input.getSourceExpression();
4400 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4401
4402 ExprResult E = getDerived().TransformExpr(InputExpr);
4403 E = SemaRef.ActOnConstantExpression(E);
4404 if (E.isInvalid()) return true;
4405 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4406 return false;
4407 }
4408 }
4409
4410 // Work around bogus GCC warning
4411 return true;
4412}
4413
4414/// Iterator adaptor that invents template argument location information
4415/// for each of the template arguments in its underlying iterator.
4416template<typename Derived, typename InputIterator>
4417class TemplateArgumentLocInventIterator {
4418 TreeTransform<Derived> &Self;
4419 InputIterator Iter;
4420
4421public:
4422 typedef TemplateArgumentLoc value_type;
4423 typedef TemplateArgumentLoc reference;
4424 typedef typename std::iterator_traits<InputIterator>::difference_type
4425 difference_type;
4426 typedef std::input_iterator_tag iterator_category;
4427
4428 class pointer {
4429 TemplateArgumentLoc Arg;
4430
4431 public:
4432 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4433
4434 const TemplateArgumentLoc *operator->() const { return &Arg; }
4435 };
4436
4437 TemplateArgumentLocInventIterator() { }
4438
4439 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4440 InputIterator Iter)
4441 : Self(Self), Iter(Iter) { }
4442
4443 TemplateArgumentLocInventIterator &operator++() {
4444 ++Iter;
4445 return *this;
4446 }
4447
4448 TemplateArgumentLocInventIterator operator++(int) {
4449 TemplateArgumentLocInventIterator Old(*this);
4450 ++(*this);
4451 return Old;
4452 }
4453
4454 reference operator*() const {
4455 TemplateArgumentLoc Result;
4456 Self.InventTemplateArgumentLoc(*Iter, Result);
4457 return Result;
4458 }
4459
4460 pointer operator->() const { return pointer(**this); }
4461
4462 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4463 const TemplateArgumentLocInventIterator &Y) {
4464 return X.Iter == Y.Iter;
4465 }
4466
4467 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4468 const TemplateArgumentLocInventIterator &Y) {
4469 return X.Iter != Y.Iter;
4470 }
4471};
4472
4473template<typename Derived>
4474template<typename InputIterator>
4475bool TreeTransform<Derived>::TransformTemplateArguments(
4476 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4477 bool Uneval) {
4478 for (; First != Last; ++First) {
4479 TemplateArgumentLoc Out;
4480 TemplateArgumentLoc In = *First;
4481
4482 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4483 // Unpack argument packs, which we translate them into separate
4484 // arguments.
4485 // FIXME: We could do much better if we could guarantee that the
4486 // TemplateArgumentLocInfo for the pack expansion would be usable for
4487 // all of the template arguments in the argument pack.
4488 typedef TemplateArgumentLocInventIterator<Derived,
4489 TemplateArgument::pack_iterator>
4490 PackLocIterator;
4491 if (TransformTemplateArguments(PackLocIterator(*this,
4492 In.getArgument().pack_begin()),
4493 PackLocIterator(*this,
4494 In.getArgument().pack_end()),
4495 Outputs, Uneval))
4496 return true;
4497
4498 continue;
4499 }
4500
4501 if (In.getArgument().isPackExpansion()) {
4502 // We have a pack expansion, for which we will be substituting into
4503 // the pattern.
4504 SourceLocation Ellipsis;
4505 Optional<unsigned> OrigNumExpansions;
4506 TemplateArgumentLoc Pattern
4507 = getSema().getTemplateArgumentPackExpansionPattern(
4508 In, Ellipsis, OrigNumExpansions);
4509
4510 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4511 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4512 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4512, __PRETTY_FUNCTION__))
;
4513
4514 // Determine whether the set of unexpanded parameter packs can and should
4515 // be expanded.
4516 bool Expand = true;
4517 bool RetainExpansion = false;
4518 Optional<unsigned> NumExpansions = OrigNumExpansions;
4519 if (getDerived().TryExpandParameterPacks(Ellipsis,
4520 Pattern.getSourceRange(),
4521 Unexpanded,
4522 Expand,
4523 RetainExpansion,
4524 NumExpansions))
4525 return true;
4526
4527 if (!Expand) {
4528 // The transform has determined that we should perform a simple
4529 // transformation on the pack expansion, producing another pack
4530 // expansion.
4531 TemplateArgumentLoc OutPattern;
4532 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4533 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4534 return true;
4535
4536 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4537 NumExpansions);
4538 if (Out.getArgument().isNull())
4539 return true;
4540
4541 Outputs.addArgument(Out);
4542 continue;
4543 }
4544
4545 // The transform has determined that we should perform an elementwise
4546 // expansion of the pattern. Do so.
4547 for (unsigned I = 0; I != *NumExpansions; ++I) {
4548 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4549
4550 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4551 return true;
4552
4553 if (Out.getArgument().containsUnexpandedParameterPack()) {
4554 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4555 OrigNumExpansions);
4556 if (Out.getArgument().isNull())
4557 return true;
4558 }
4559
4560 Outputs.addArgument(Out);
4561 }
4562
4563 // If we're supposed to retain a pack expansion, do so by temporarily
4564 // forgetting the partially-substituted parameter pack.
4565 if (RetainExpansion) {
4566 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4567
4568 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4569 return true;
4570
4571 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4572 OrigNumExpansions);
4573 if (Out.getArgument().isNull())
4574 return true;
4575
4576 Outputs.addArgument(Out);
4577 }
4578
4579 continue;
4580 }
4581
4582 // The simple case:
4583 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4584 return true;
4585
4586 Outputs.addArgument(Out);
4587 }
4588
4589 return false;
4590
4591}
4592
4593//===----------------------------------------------------------------------===//
4594// Type transformation
4595//===----------------------------------------------------------------------===//
4596
4597template<typename Derived>
4598QualType TreeTransform<Derived>::TransformType(QualType T) {
4599 if (getDerived().AlreadyTransformed(T))
4600 return T;
4601
4602 // Temporary workaround. All of these transformations should
4603 // eventually turn into transformations on TypeLocs.
4604 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4605 getDerived().getBaseLocation());
4606
4607 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4608
4609 if (!NewDI)
4610 return QualType();
4611
4612 return NewDI->getType();
4613}
4614
4615template<typename Derived>
4616TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4617 // Refine the base location to the type's location.
4618 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4619 getDerived().getBaseEntity());
4620 if (getDerived().AlreadyTransformed(DI->getType()))
4621 return DI;
4622
4623 TypeLocBuilder TLB;
4624
4625 TypeLoc TL = DI->getTypeLoc();
4626 TLB.reserve(TL.getFullDataSize());
4627
4628 QualType Result = getDerived().TransformType(TLB, TL);
4629 if (Result.isNull())
4630 return nullptr;
4631
4632 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4633}
4634
4635template<typename Derived>
4636QualType
4637TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4638 switch (T.getTypeLocClass()) {
4639#define ABSTRACT_TYPELOC(CLASS, PARENT)
4640#define TYPELOC(CLASS, PARENT) \
4641 case TypeLoc::CLASS: \
4642 return getDerived().Transform##CLASS##Type(TLB, \
4643 T.castAs<CLASS##TypeLoc>());
4644#include "clang/AST/TypeLocNodes.def"
4645 }
4646
4647 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4647)
;
4648}
4649
4650template<typename Derived>
4651QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4652 if (!isa<DependentNameType>(T))
4653 return TransformType(T);
4654
4655 if (getDerived().AlreadyTransformed(T))
4656 return T;
4657 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4658 getDerived().getBaseLocation());
4659 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4660 return NewDI ? NewDI->getType() : QualType();
4661}
4662
4663template<typename Derived>
4664TypeSourceInfo *
4665TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4666 if (!isa<DependentNameType>(DI->getType()))
4667 return TransformType(DI);
4668
4669 // Refine the base location to the type's location.
4670 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4671 getDerived().getBaseEntity());
4672 if (getDerived().AlreadyTransformed(DI->getType()))
4673 return DI;
4674
4675 TypeLocBuilder TLB;
4676
4677 TypeLoc TL = DI->getTypeLoc();
4678 TLB.reserve(TL.getFullDataSize());
4679
4680 auto QTL = TL.getAs<QualifiedTypeLoc>();
4681 if (QTL)
4682 TL = QTL.getUnqualifiedLoc();
4683
4684 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4685
4686 QualType Result = getDerived().TransformDependentNameType(
4687 TLB, DNTL, /*DeducedTSTContext*/true);
4688 if (Result.isNull())
4689 return nullptr;
4690
4691 if (QTL) {
4692 Result = getDerived().RebuildQualifiedType(Result, QTL);
4693 if (Result.isNull())
4694 return nullptr;
4695 TLB.TypeWasModifiedSafely(Result);
4696 }
4697
4698 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4699}
4700
4701template<typename Derived>
4702QualType
4703TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4704 QualifiedTypeLoc T) {
4705 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4706 if (Result.isNull())
4707 return QualType();
4708
4709 Result = getDerived().RebuildQualifiedType(Result, T);
4710
4711 if (Result.isNull())
4712 return QualType();
4713
4714 // RebuildQualifiedType might have updated the type, but not in a way
4715 // that invalidates the TypeLoc. (There's no location information for
4716 // qualifiers.)
4717 TLB.TypeWasModifiedSafely(Result);
4718
4719 return Result;
4720}
4721
4722template <typename Derived>
4723QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4724 QualifiedTypeLoc TL) {
4725
4726 SourceLocation Loc = TL.getBeginLoc();
4727 Qualifiers Quals = TL.getType().getLocalQualifiers();
4728
4729 if (((T.getAddressSpace() != LangAS::Default &&
4730 Quals.getAddressSpace() != LangAS::Default)) &&
4731 T.getAddressSpace() != Quals.getAddressSpace()) {
4732 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4733 << TL.getType() << T;
4734 return QualType();
4735 }
4736
4737 // C++ [dcl.fct]p7:
4738 // [When] adding cv-qualifications on top of the function type [...] the
4739 // cv-qualifiers are ignored.
4740 if (T->isFunctionType()) {
4741 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4742 Quals.getAddressSpace());
4743 return T;
4744 }
4745
4746 // C++ [dcl.ref]p1:
4747 // when the cv-qualifiers are introduced through the use of a typedef-name
4748 // or decltype-specifier [...] the cv-qualifiers are ignored.
4749 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4750 // applied to a reference type.
4751 if (T->isReferenceType()) {
4752 // The only qualifier that applies to a reference type is restrict.
4753 if (!Quals.hasRestrict())
4754 return T;
4755 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4756 }
4757
4758 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4759 // resulting type.
4760 if (Quals.hasObjCLifetime()) {
4761 if (!T->isObjCLifetimeType() && !T->isDependentType())
4762 Quals.removeObjCLifetime();
4763 else if (T.getObjCLifetime()) {
4764 // Objective-C ARC:
4765 // A lifetime qualifier applied to a substituted template parameter
4766 // overrides the lifetime qualifier from the template argument.
4767 const AutoType *AutoTy;
4768 if (const SubstTemplateTypeParmType *SubstTypeParam
4769 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4770 QualType Replacement = SubstTypeParam->getReplacementType();
4771 Qualifiers Qs = Replacement.getQualifiers();
4772 Qs.removeObjCLifetime();
4773 Replacement = SemaRef.Context.getQualifiedType(
4774 Replacement.getUnqualifiedType(), Qs);
4775 T = SemaRef.Context.getSubstTemplateTypeParmType(
4776 SubstTypeParam->getReplacedParameter(), Replacement);
4777 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4778 // 'auto' types behave the same way as template parameters.
4779 QualType Deduced = AutoTy->getDeducedType();
4780 Qualifiers Qs = Deduced.getQualifiers();
4781 Qs.removeObjCLifetime();
4782 Deduced =
4783 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4784 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4785 AutoTy->isDependentType(),
4786 /*isPack=*/false,
4787 AutoTy->getTypeConstraintConcept(),
4788 AutoTy->getTypeConstraintArguments());
4789 } else {
4790 // Otherwise, complain about the addition of a qualifier to an
4791 // already-qualified type.
4792 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4793 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4794 Quals.removeObjCLifetime();
4795 }
4796 }
4797 }
4798
4799 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4800}
4801
4802template<typename Derived>
4803TypeLoc
4804TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4805 QualType ObjectType,
4806 NamedDecl *UnqualLookup,
4807 CXXScopeSpec &SS) {
4808 if (getDerived().AlreadyTransformed(TL.getType()))
4809 return TL;
4810
4811 TypeSourceInfo *TSI =
4812 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4813 if (TSI)
4814 return TSI->getTypeLoc();
4815 return TypeLoc();
4816}
4817
4818template<typename Derived>
4819TypeSourceInfo *
4820TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4821 QualType ObjectType,
4822 NamedDecl *UnqualLookup,
4823 CXXScopeSpec &SS) {
4824 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4825 return TSInfo;
4826
4827 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4828 UnqualLookup, SS);
4829}
4830
4831template <typename Derived>
4832TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4833 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4834 CXXScopeSpec &SS) {
4835 QualType T = TL.getType();
4836 assert(!getDerived().AlreadyTransformed(T))((!getDerived().AlreadyTransformed(T)) ? static_cast<void>
(0) : __assert_fail ("!getDerived().AlreadyTransformed(T)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 4836, __PRETTY_FUNCTION__))
;
4837
4838 TypeLocBuilder TLB;
4839 QualType Result;
4840
4841 if (isa<TemplateSpecializationType>(T)) {
4842 TemplateSpecializationTypeLoc SpecTL =
4843 TL.castAs<TemplateSpecializationTypeLoc>();
4844
4845 TemplateName Template = getDerived().TransformTemplateName(
4846 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4847 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4848 if (Template.isNull())
4849 return nullptr;
4850
4851 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4852 Template);
4853 } else if (isa<DependentTemplateSpecializationType>(T)) {
4854 DependentTemplateSpecializationTypeLoc SpecTL =
4855 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4856
4857 TemplateName Template
4858 = getDerived().RebuildTemplateName(SS,
4859 SpecTL.getTemplateKeywordLoc(),
4860 *SpecTL.getTypePtr()->getIdentifier(),
4861 SpecTL.getTemplateNameLoc(),
4862 ObjectType, UnqualLookup,
4863 /*AllowInjectedClassName*/true);
4864 if (Template.isNull())
4865 return nullptr;
4866
4867 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4868 SpecTL,
4869 Template,
4870 SS);
4871 } else {
4872 // Nothing special needs to be done for these.
4873 Result = getDerived().TransformType(TLB, TL);
4874 }
4875
4876 if (Result.isNull())
4877 return nullptr;
4878
4879 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4880}
4881
4882template <class TyLoc> static inline
4883QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4884 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4885 NewT.setNameLoc(T.getNameLoc());
4886 return T.getType();
4887}
4888
4889template<typename Derived>
4890QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4891 BuiltinTypeLoc T) {
4892 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4893 NewT.setBuiltinLoc(T.getBuiltinLoc());
4894 if (T.needsExtraLocalData())
4895 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4896 return T.getType();
4897}
4898
4899template<typename Derived>
4900QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4901 ComplexTypeLoc T) {
4902 // FIXME: recurse?
4903 return TransformTypeSpecType(TLB, T);
4904}
4905
4906template <typename Derived>
4907QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4908 AdjustedTypeLoc TL) {
4909 // Adjustments applied during transformation are handled elsewhere.
4910 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4911}
4912
4913template<typename Derived>
4914QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4915 DecayedTypeLoc TL) {
4916 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4917 if (OriginalType.isNull())
4918 return QualType();
4919
4920 QualType Result = TL.getType();
4921 if (getDerived().AlwaysRebuild() ||
4922 OriginalType != TL.getOriginalLoc().getType())
4923 Result = SemaRef.Context.getDecayedType(OriginalType);
4924 TLB.push<DecayedTypeLoc>(Result);
4925 // Nothing to set for DecayedTypeLoc.
4926 return Result;
4927}
4928
4929template<typename Derived>
4930QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4931 PointerTypeLoc TL) {
4932 QualType PointeeType
4933 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4934 if (PointeeType.isNull())
4935 return QualType();
4936
4937 QualType Result = TL.getType();
4938 if (PointeeType->getAs<ObjCObjectType>()) {
4939 // A dependent pointer type 'T *' has is being transformed such
4940 // that an Objective-C class type is being replaced for 'T'. The
4941 // resulting pointer type is an ObjCObjectPointerType, not a
4942 // PointerType.
4943 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4944
4945 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4946 NewT.setStarLoc(TL.getStarLoc());
4947 return Result;
4948 }
4949
4950 if (getDerived().AlwaysRebuild() ||
4951 PointeeType != TL.getPointeeLoc().getType()) {
4952 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4953 if (Result.isNull())
4954 return QualType();
4955 }
4956
4957 // Objective-C ARC can add lifetime qualifiers to the type that we're
4958 // pointing to.
4959 TLB.TypeWasModifiedSafely(Result->getPointeeType());
4960
4961 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4962 NewT.setSigilLoc(TL.getSigilLoc());
4963 return Result;
4964}
4965
4966template<typename Derived>
4967QualType
4968TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4969 BlockPointerTypeLoc TL) {
4970 QualType PointeeType
4971 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4972 if (PointeeType.isNull())
4973 return QualType();
4974
4975 QualType Result = TL.getType();
4976 if (getDerived().AlwaysRebuild() ||
4977 PointeeType != TL.getPointeeLoc().getType()) {
4978 Result = getDerived().RebuildBlockPointerType(PointeeType,
4979 TL.getSigilLoc());
4980 if (Result.isNull())
4981 return QualType();
4982 }
4983
4984 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4985 NewT.setSigilLoc(TL.getSigilLoc());
4986 return Result;
4987}
4988
4989/// Transforms a reference type. Note that somewhat paradoxically we
4990/// don't care whether the type itself is an l-value type or an r-value
4991/// type; we only care if the type was *written* as an l-value type
4992/// or an r-value type.
4993template<typename Derived>
4994QualType
4995TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4996 ReferenceTypeLoc TL) {
4997 const ReferenceType *T = TL.getTypePtr();
4998
4999 // Note that this works with the pointee-as-written.
5000 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5001 if (PointeeType.isNull())
5002 return QualType();
5003
5004 QualType Result = TL.getType();
5005 if (getDerived().AlwaysRebuild() ||
5006 PointeeType != T->getPointeeTypeAsWritten()) {
5007 Result = getDerived().RebuildReferenceType(PointeeType,
5008 T->isSpelledAsLValue(),
5009 TL.getSigilLoc());
5010 if (Result.isNull())
5011 return QualType();
5012 }
5013
5014 // Objective-C ARC can add lifetime qualifiers to the type that we're
5015 // referring to.
5016 TLB.TypeWasModifiedSafely(
5017 Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5018
5019 // r-value references can be rebuilt as l-value references.
5020 ReferenceTypeLoc NewTL;
5021 if (isa<LValueReferenceType>(Result))
5022 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5023 else
5024 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5025 NewTL.setSigilLoc(TL.getSigilLoc());
5026
5027 return Result;
5028}
5029
5030template<typename Derived>
5031QualType
5032TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5033 LValueReferenceTypeLoc TL) {
5034 return TransformReferenceType(TLB, TL);
5035}
5036
5037template<typename Derived>
5038QualType
5039TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5040 RValueReferenceTypeLoc TL) {
5041 return TransformReferenceType(TLB, TL);
5042}
5043
5044template<typename Derived>
5045QualType
5046TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5047 MemberPointerTypeLoc TL) {
5048 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5049 if (PointeeType.isNull())
5050 return QualType();
5051
5052 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5053 TypeSourceInfo *NewClsTInfo = nullptr;
5054 if (OldClsTInfo) {
5055 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5056 if (!NewClsTInfo)
5057 return QualType();
5058 }
5059
5060 const MemberPointerType *T = TL.getTypePtr();
5061 QualType OldClsType = QualType(T->getClass(), 0);
5062 QualType NewClsType;
5063 if (NewClsTInfo)
5064 NewClsType = NewClsTInfo->getType();
5065 else {
5066 NewClsType = getDerived().TransformType(OldClsType);
5067 if (NewClsType.isNull())
5068 return QualType();
5069 }
5070
5071 QualType Result = TL.getType();
5072 if (getDerived().AlwaysRebuild() ||
5073 PointeeType != T->getPointeeType() ||
5074 NewClsType != OldClsType) {
5075 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5076 TL.getStarLoc());
5077 if (Result.isNull())
5078 return QualType();
5079 }
5080
5081 // If we had to adjust the pointee type when building a member pointer, make
5082 // sure to push TypeLoc info for it.
5083 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5084 if (MPT && PointeeType != MPT->getPointeeType()) {
5085 assert(isa<AdjustedType>(MPT->getPointeeType()))((isa<AdjustedType>(MPT->getPointeeType())) ? static_cast
<void> (0) : __assert_fail ("isa<AdjustedType>(MPT->getPointeeType())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5085, __PRETTY_FUNCTION__))
;
5086 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5087 }
5088
5089 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5090 NewTL.setSigilLoc(TL.getSigilLoc());
5091 NewTL.setClassTInfo(NewClsTInfo);
5092
5093 return Result;
5094}
5095
5096template<typename Derived>
5097QualType
5098TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5099 ConstantArrayTypeLoc TL) {
5100 const ConstantArrayType *T = TL.getTypePtr();
5101 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5102 if (ElementType.isNull())
5103 return QualType();
5104
5105 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5106 Expr *OldSize = TL.getSizeExpr();
5107 if (!OldSize)
5108 OldSize = const_cast<Expr*>(T->getSizeExpr());
5109 Expr *NewSize = nullptr;
5110 if (OldSize) {
5111 EnterExpressionEvaluationContext Unevaluated(
5112 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5113 NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5114 NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5115 }
5116
5117 QualType Result = TL.getType();
5118 if (getDerived().AlwaysRebuild() ||
5119 ElementType != T->getElementType() ||
5120 (T->getSizeExpr() && NewSize != OldSize)) {
5121 Result = getDerived().RebuildConstantArrayType(ElementType,
5122 T->getSizeModifier(),
5123 T->getSize(), NewSize,
5124 T->getIndexTypeCVRQualifiers(),
5125 TL.getBracketsRange());
5126 if (Result.isNull())
5127 return QualType();
5128 }
5129
5130 // We might have either a ConstantArrayType or a VariableArrayType now:
5131 // a ConstantArrayType is allowed to have an element type which is a
5132 // VariableArrayType if the type is dependent. Fortunately, all array
5133 // types have the same location layout.
5134 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5135 NewTL.setLBracketLoc(TL.getLBracketLoc());
5136 NewTL.setRBracketLoc(TL.getRBracketLoc());
5137 NewTL.setSizeExpr(NewSize);
5138
5139 return Result;
5140}
5141
5142template<typename Derived>
5143QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5144 TypeLocBuilder &TLB,
5145 IncompleteArrayTypeLoc TL) {
5146 const IncompleteArrayType *T = TL.getTypePtr();
5147 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5148 if (ElementType.isNull())
5149 return QualType();
5150
5151 QualType Result = TL.getType();
5152 if (getDerived().AlwaysRebuild() ||
5153 ElementType != T->getElementType()) {
5154 Result = getDerived().RebuildIncompleteArrayType(ElementType,
5155 T->getSizeModifier(),
5156 T->getIndexTypeCVRQualifiers(),
5157 TL.getBracketsRange());
5158 if (Result.isNull())
5159 return QualType();
5160 }
5161
5162 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5163 NewTL.setLBracketLoc(TL.getLBracketLoc());
5164 NewTL.setRBracketLoc(TL.getRBracketLoc());
5165 NewTL.setSizeExpr(nullptr);
5166
5167 return Result;
5168}
5169
5170template<typename Derived>
5171QualType
5172TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5173 VariableArrayTypeLoc TL) {
5174 const VariableArrayType *T = TL.getTypePtr();
5175 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5176 if (ElementType.isNull())
5177 return QualType();
5178
5179 ExprResult SizeResult;
5180 {
5181 EnterExpressionEvaluationContext Context(
5182 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5183 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5184 }
5185 if (SizeResult.isInvalid())
5186 return QualType();
5187 SizeResult =
5188 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5189 if (SizeResult.isInvalid())
5190 return QualType();
5191
5192 Expr *Size = SizeResult.get();
5193
5194 QualType Result = TL.getType();
5195 if (getDerived().AlwaysRebuild() ||
5196 ElementType != T->getElementType() ||
5197 Size != T->getSizeExpr()) {
5198 Result = getDerived().RebuildVariableArrayType(ElementType,
5199 T->getSizeModifier(),
5200 Size,
5201 T->getIndexTypeCVRQualifiers(),
5202 TL.getBracketsRange());
5203 if (Result.isNull())
5204 return QualType();
5205 }
5206
5207 // We might have constant size array now, but fortunately it has the same
5208 // location layout.
5209 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5210 NewTL.setLBracketLoc(TL.getLBracketLoc());
5211 NewTL.setRBracketLoc(TL.getRBracketLoc());
5212 NewTL.setSizeExpr(Size);
5213
5214 return Result;
5215}
5216
5217template<typename Derived>
5218QualType
5219TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5220 DependentSizedArrayTypeLoc TL) {
5221 const DependentSizedArrayType *T = TL.getTypePtr();
5222 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5223 if (ElementType.isNull())
5224 return QualType();
5225
5226 // Array bounds are constant expressions.
5227 EnterExpressionEvaluationContext Unevaluated(
5228 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5229
5230 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5231 Expr *origSize = TL.getSizeExpr();
5232 if (!origSize) origSize = T->getSizeExpr();
5233
5234 ExprResult sizeResult
5235 = getDerived().TransformExpr(origSize);
5236 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5237 if (sizeResult.isInvalid())
5238 return QualType();
5239
5240 Expr *size = sizeResult.get();
5241
5242 QualType Result = TL.getType();
5243 if (getDerived().AlwaysRebuild() ||
5244 ElementType != T->getElementType() ||
5245 size != origSize) {
5246 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5247 T->getSizeModifier(),
5248 size,
5249 T->getIndexTypeCVRQualifiers(),
5250 TL.getBracketsRange());
5251 if (Result.isNull())
5252 return QualType();
5253 }
5254
5255 // We might have any sort of array type now, but fortunately they
5256 // all have the same location layout.
5257 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5258 NewTL.setLBracketLoc(TL.getLBracketLoc());
5259 NewTL.setRBracketLoc(TL.getRBracketLoc());
5260 NewTL.setSizeExpr(size);
5261
5262 return Result;
5263}
5264
5265template <typename Derived>
5266QualType TreeTransform<Derived>::TransformDependentVectorType(
5267 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5268 const DependentVectorType *T = TL.getTypePtr();
5269 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5270 if (ElementType.isNull())
5271 return QualType();
5272
5273 EnterExpressionEvaluationContext Unevaluated(
5274 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5275
5276 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5277 Size = SemaRef.ActOnConstantExpression(Size);
5278 if (Size.isInvalid())
5279 return QualType();
5280
5281 QualType Result = TL.getType();
5282 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5283 Size.get() != T->getSizeExpr()) {
5284 Result = getDerived().RebuildDependentVectorType(
5285 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5286 if (Result.isNull())
5287 return QualType();
5288 }
5289
5290 // Result might be dependent or not.
5291 if (isa<DependentVectorType>(Result)) {
5292 DependentVectorTypeLoc NewTL =
5293 TLB.push<DependentVectorTypeLoc>(Result);
5294 NewTL.setNameLoc(TL.getNameLoc());
5295 } else {
5296 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5297 NewTL.setNameLoc(TL.getNameLoc());
5298 }
5299
5300 return Result;
5301}
5302
5303template<typename Derived>
5304QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5305 TypeLocBuilder &TLB,
5306 DependentSizedExtVectorTypeLoc TL) {
5307 const DependentSizedExtVectorType *T = TL.getTypePtr();
5308
5309 // FIXME: ext vector locs should be nested
5310 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5311 if (ElementType.isNull())
5312 return QualType();
5313
5314 // Vector sizes are constant expressions.
5315 EnterExpressionEvaluationContext Unevaluated(
5316 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5317
5318 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5319 Size = SemaRef.ActOnConstantExpression(Size);
5320 if (Size.isInvalid())
5321 return QualType();
5322
5323 QualType Result = TL.getType();
5324 if (getDerived().AlwaysRebuild() ||
5325 ElementType != T->getElementType() ||
5326 Size.get() != T->getSizeExpr()) {
5327 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5328 Size.get(),
5329 T->getAttributeLoc());
5330 if (Result.isNull())
5331 return QualType();
5332 }
5333
5334 // Result might be dependent or not.
5335 if (isa<DependentSizedExtVectorType>(Result)) {
5336 DependentSizedExtVectorTypeLoc NewTL
5337 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5338 NewTL.setNameLoc(TL.getNameLoc());
5339 } else {
5340 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5341 NewTL.setNameLoc(TL.getNameLoc());
5342 }
5343
5344 return Result;
5345}
5346
5347template <typename Derived>
5348QualType
5349TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5350 ConstantMatrixTypeLoc TL) {
5351 const ConstantMatrixType *T = TL.getTypePtr();
5352 QualType ElementType = getDerived().TransformType(T->getElementType());
5353 if (ElementType.isNull())
5354 return QualType();
5355
5356 QualType Result = TL.getType();
5357 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5358 Result = getDerived().RebuildConstantMatrixType(
5359 ElementType, T->getNumRows(), T->getNumColumns());
5360 if (Result.isNull())
5361 return QualType();
5362 }
5363
5364 ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5365 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5366 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5367 NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5368 NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5369
5370 return Result;
5371}
5372
5373template <typename Derived>
5374QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5375 TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5376 const DependentSizedMatrixType *T = TL.getTypePtr();
5377
5378 QualType ElementType = getDerived().TransformType(T->getElementType());
5379 if (ElementType.isNull()) {
5380 return QualType();
5381 }
5382
5383 // Matrix dimensions are constant expressions.
5384 EnterExpressionEvaluationContext Unevaluated(
5385 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5386
5387 Expr *origRows = TL.getAttrRowOperand();
5388 if (!origRows)
5389 origRows = T->getRowExpr();
5390 Expr *origColumns = TL.getAttrColumnOperand();
5391 if (!origColumns)
5392 origColumns = T->getColumnExpr();
5393
5394 ExprResult rowResult = getDerived().TransformExpr(origRows);
5395 rowResult = SemaRef.ActOnConstantExpression(rowResult);
5396 if (rowResult.isInvalid())
5397 return QualType();
5398
5399 ExprResult columnResult = getDerived().TransformExpr(origColumns);
5400 columnResult = SemaRef.ActOnConstantExpression(columnResult);
5401 if (columnResult.isInvalid())
5402 return QualType();
5403
5404 Expr *rows = rowResult.get();
5405 Expr *columns = columnResult.get();
5406
5407 QualType Result = TL.getType();
5408 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5409 rows != origRows || columns != origColumns) {
5410 Result = getDerived().RebuildDependentSizedMatrixType(
5411 ElementType, rows, columns, T->getAttributeLoc());
5412
5413 if (Result.isNull())
5414 return QualType();
5415 }
5416
5417 // We might have any sort of matrix type now, but fortunately they
5418 // all have the same location layout.
5419 MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5420 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5421 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5422 NewTL.setAttrRowOperand(rows);
5423 NewTL.setAttrColumnOperand(columns);
5424 return Result;
5425}
5426
5427template <typename Derived>
5428QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5429 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5430 const DependentAddressSpaceType *T = TL.getTypePtr();
5431
5432 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5433
5434 if (pointeeType.isNull())
5435 return QualType();
5436
5437 // Address spaces are constant expressions.
5438 EnterExpressionEvaluationContext Unevaluated(
5439 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5440
5441 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5442 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5443 if (AddrSpace.isInvalid())
5444 return QualType();
5445
5446 QualType Result = TL.getType();
5447 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5448 AddrSpace.get() != T->getAddrSpaceExpr()) {
5449 Result = getDerived().RebuildDependentAddressSpaceType(
5450 pointeeType, AddrSpace.get(), T->getAttributeLoc());
5451 if (Result.isNull())
5452 return QualType();
5453 }
5454
5455 // Result might be dependent or not.
5456 if (isa<DependentAddressSpaceType>(Result)) {
5457 DependentAddressSpaceTypeLoc NewTL =
5458 TLB.push<DependentAddressSpaceTypeLoc>(Result);
5459
5460 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5461 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5462 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5463
5464 } else {
5465 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5466 Result, getDerived().getBaseLocation());
5467 TransformType(TLB, DI->getTypeLoc());
5468 }
5469
5470 return Result;
5471}
5472
5473template <typename Derived>
5474QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5475 VectorTypeLoc TL) {
5476 const VectorType *T = TL.getTypePtr();
5477 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5478 if (ElementType.isNull())
5479 return QualType();
5480
5481 QualType Result = TL.getType();
5482 if (getDerived().AlwaysRebuild() ||
5483 ElementType != T->getElementType()) {
5484 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5485 T->getVectorKind());
5486 if (Result.isNull())
5487 return QualType();
5488 }
5489
5490 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5491 NewTL.setNameLoc(TL.getNameLoc());
5492
5493 return Result;
5494}
5495
5496template<typename Derived>
5497QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5498 ExtVectorTypeLoc TL) {
5499 const VectorType *T = TL.getTypePtr();
5500 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5501 if (ElementType.isNull())
5502 return QualType();
5503
5504 QualType Result = TL.getType();
5505 if (getDerived().AlwaysRebuild() ||
5506 ElementType != T->getElementType()) {
5507 Result = getDerived().RebuildExtVectorType(ElementType,
5508 T->getNumElements(),
5509 /*FIXME*/ SourceLocation());
5510 if (Result.isNull())
5511 return QualType();
5512 }
5513
5514 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5515 NewTL.setNameLoc(TL.getNameLoc());
5516
5517 return Result;
5518}
5519
5520template <typename Derived>
5521ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5522 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5523 bool ExpectParameterPack) {
5524 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5525 TypeSourceInfo *NewDI = nullptr;
5526
5527 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5528 // If we're substituting into a pack expansion type and we know the
5529 // length we want to expand to, just substitute for the pattern.
5530 TypeLoc OldTL = OldDI->getTypeLoc();
5531 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5532
5533 TypeLocBuilder TLB;
5534 TypeLoc NewTL = OldDI->getTypeLoc();
5535 TLB.reserve(NewTL.getFullDataSize());
5536
5537 QualType Result = getDerived().TransformType(TLB,
5538 OldExpansionTL.getPatternLoc());
5539 if (Result.isNull())
5540 return nullptr;
5541
5542 Result = RebuildPackExpansionType(Result,
5543 OldExpansionTL.getPatternLoc().getSourceRange(),
5544 OldExpansionTL.getEllipsisLoc(),
5545 NumExpansions);
5546 if (Result.isNull())
5547 return nullptr;
5548
5549 PackExpansionTypeLoc NewExpansionTL
5550 = TLB.push<PackExpansionTypeLoc>(Result);
5551 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5552 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5553 } else
5554 NewDI = getDerived().TransformType(OldDI);
5555 if (!NewDI)
5556 return nullptr;
5557
5558 if (NewDI == OldDI && indexAdjustment == 0)
5559 return OldParm;
5560
5561 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5562 OldParm->getDeclContext(),
5563 OldParm->getInnerLocStart(),
5564 OldParm->getLocation(),
5565 OldParm->getIdentifier(),
5566 NewDI->getType(),
5567 NewDI,
5568 OldParm->getStorageClass(),
5569 /* DefArg */ nullptr);
5570 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5571 OldParm->getFunctionScopeIndex() + indexAdjustment);
5572 transformedLocalDecl(OldParm, {newParm});
5573 return newParm;
5574}
5575
5576template <typename Derived>
5577bool TreeTransform<Derived>::TransformFunctionTypeParams(
5578 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5579 const QualType *ParamTypes,
5580 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5581 SmallVectorImpl<QualType> &OutParamTypes,
5582 SmallVectorImpl<ParmVarDecl *> *PVars,
5583 Sema::ExtParameterInfoBuilder &PInfos) {
5584 int indexAdjustment = 0;
5585
5586 unsigned NumParams = Params.size();
5587 for (unsigned i = 0; i != NumParams; ++i) {
4
Assuming 'i' is not equal to 'NumParams'
5
Loop condition is true. Entering loop body
5588 if (ParmVarDecl *OldParm = Params[i]) {
6
Assuming 'OldParm' is null
7
Taking false branch
5589 assert(OldParm->getFunctionScopeIndex() == i)((OldParm->getFunctionScopeIndex() == i) ? static_cast<
void> (0) : __assert_fail ("OldParm->getFunctionScopeIndex() == i"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5589, __PRETTY_FUNCTION__))
;
5590
5591 Optional<unsigned> NumExpansions;
5592 ParmVarDecl *NewParm = nullptr;
5593 if (OldParm->isParameterPack()) {
5594 // We have a function parameter pack that may need to be expanded.
5595 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5596
5597 // Find the parameter packs that could be expanded.
5598 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5599 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5600 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5601 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5602
5603 // Determine whether we should expand the parameter packs.
5604 bool ShouldExpand = false;
5605 bool RetainExpansion = false;
5606 Optional<unsigned> OrigNumExpansions;
5607 if (Unexpanded.size() > 0) {
5608 OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5609 NumExpansions = OrigNumExpansions;
5610 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5611 Pattern.getSourceRange(),
5612 Unexpanded,
5613 ShouldExpand,
5614 RetainExpansion,
5615 NumExpansions)) {
5616 return true;
5617 }
5618 } else {
5619#ifndef NDEBUG
5620 const AutoType *AT =
5621 Pattern.getType().getTypePtr()->getContainedAutoType();
5622 assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&(((AT && (!AT->isDeduced() || AT->getDeducedType
().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? static_cast<void> (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5623, __PRETTY_FUNCTION__))
5623 "Could not find parameter packs or undeduced auto type!")(((AT && (!AT->isDeduced() || AT->getDeducedType
().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? static_cast<void> (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5623, __PRETTY_FUNCTION__))
;
5624#endif
5625 }
5626
5627 if (ShouldExpand) {
5628 // Expand the function parameter pack into multiple, separate
5629 // parameters.
5630 getDerived().ExpandingFunctionParameterPack(OldParm);
5631 for (unsigned I = 0; I != *NumExpansions; ++I) {
5632 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5633 ParmVarDecl *NewParm
5634 = getDerived().TransformFunctionTypeParam(OldParm,
5635 indexAdjustment++,
5636 OrigNumExpansions,
5637 /*ExpectParameterPack=*/false);
5638 if (!NewParm)
5639 return true;
5640
5641 if (ParamInfos)
5642 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5643 OutParamTypes.push_back(NewParm->getType());
5644 if (PVars)
5645 PVars->push_back(NewParm);
5646 }
5647
5648 // If we're supposed to retain a pack expansion, do so by temporarily
5649 // forgetting the partially-substituted parameter pack.
5650 if (RetainExpansion) {
5651 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5652 ParmVarDecl *NewParm
5653 = getDerived().TransformFunctionTypeParam(OldParm,
5654 indexAdjustment++,
5655 OrigNumExpansions,
5656 /*ExpectParameterPack=*/false);
5657 if (!NewParm)
5658 return true;
5659
5660 if (ParamInfos)
5661 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5662 OutParamTypes.push_back(NewParm->getType());
5663 if (PVars)
5664 PVars->push_back(NewParm);
5665 }
5666
5667 // The next parameter should have the same adjustment as the
5668 // last thing we pushed, but we post-incremented indexAdjustment
5669 // on every push. Also, if we push nothing, the adjustment should
5670 // go down by one.
5671 indexAdjustment--;
5672
5673 // We're done with the pack expansion.
5674 continue;
5675 }
5676
5677 // We'll substitute the parameter now without expanding the pack
5678 // expansion.
5679 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5680 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5681 indexAdjustment,
5682 NumExpansions,
5683 /*ExpectParameterPack=*/true);
5684 assert(NewParm->isParameterPack() &&((NewParm->isParameterPack() && "Parameter pack no longer a parameter pack after "
"transformation.") ? static_cast<void> (0) : __assert_fail
("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5686, __PRETTY_FUNCTION__))
5685 "Parameter pack no longer a parameter pack after "((NewParm->isParameterPack() && "Parameter pack no longer a parameter pack after "
"transformation.") ? static_cast<void> (0) : __assert_fail
("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5686, __PRETTY_FUNCTION__))
5686 "transformation.")((NewParm->isParameterPack() && "Parameter pack no longer a parameter pack after "
"transformation.") ? static_cast<void> (0) : __assert_fail
("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5686, __PRETTY_FUNCTION__))
;
5687 } else {
5688 NewParm = getDerived().TransformFunctionTypeParam(
5689 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5690 }
5691
5692 if (!NewParm)
5693 return true;
5694
5695 if (ParamInfos)
5696 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5697 OutParamTypes.push_back(NewParm->getType());
5698 if (PVars)
5699 PVars->push_back(NewParm);
5700 continue;
5701 }
5702
5703 // Deal with the possibility that we don't have a parameter
5704 // declaration for this parameter.
5705 QualType OldType = ParamTypes[i];
8
Forming reference to null pointer
5706 bool IsPackExpansion = false;
5707 Optional<unsigned> NumExpansions;
5708 QualType NewType;
5709 if (const PackExpansionType *Expansion
5710 = dyn_cast<PackExpansionType>(OldType)) {
5711 // We have a function parameter pack that may need to be expanded.
5712 QualType Pattern = Expansion->getPattern();
5713 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5714 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5715
5716 // Determine whether we should expand the parameter packs.
5717 bool ShouldExpand = false;
5718 bool RetainExpansion = false;
5719 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5720 Unexpanded,
5721 ShouldExpand,
5722 RetainExpansion,
5723 NumExpansions)) {
5724 return true;
5725 }
5726
5727 if (ShouldExpand) {
5728 // Expand the function parameter pack into multiple, separate
5729 // parameters.
5730 for (unsigned I = 0; I != *NumExpansions; ++I) {
5731 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5732 QualType NewType = getDerived().TransformType(Pattern);
5733 if (NewType.isNull())
5734 return true;
5735
5736 if (NewType->containsUnexpandedParameterPack()) {
5737 NewType =
5738 getSema().getASTContext().getPackExpansionType(NewType, None);
5739
5740 if (NewType.isNull())
5741 return true;
5742 }
5743
5744 if (ParamInfos)
5745 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5746 OutParamTypes.push_back(NewType);
5747 if (PVars)
5748 PVars->push_back(nullptr);
5749 }
5750
5751 // We're done with the pack expansion.
5752 continue;
5753 }
5754
5755 // If we're supposed to retain a pack expansion, do so by temporarily
5756 // forgetting the partially-substituted parameter pack.
5757 if (RetainExpansion) {
5758 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5759 QualType NewType = getDerived().TransformType(Pattern);
5760 if (NewType.isNull())
5761 return true;
5762
5763 if (ParamInfos)
5764 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5765 OutParamTypes.push_back(NewType);
5766 if (PVars)
5767 PVars->push_back(nullptr);
5768 }
5769
5770 // We'll substitute the parameter now without expanding the pack
5771 // expansion.
5772 OldType = Expansion->getPattern();
5773 IsPackExpansion = true;
5774 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5775 NewType = getDerived().TransformType(OldType);
5776 } else {
5777 NewType = getDerived().TransformType(OldType);
5778 }
5779
5780 if (NewType.isNull())
5781 return true;
5782
5783 if (IsPackExpansion)
5784 NewType = getSema().Context.getPackExpansionType(NewType,
5785 NumExpansions);
5786
5787 if (ParamInfos)
5788 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5789 OutParamTypes.push_back(NewType);
5790 if (PVars)
5791 PVars->push_back(nullptr);
5792 }
5793
5794#ifndef NDEBUG
5795 if (PVars) {
5796 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5797 if (ParmVarDecl *parm = (*PVars)[i])
5798 assert(parm->getFunctionScopeIndex() == i)((parm->getFunctionScopeIndex() == i) ? static_cast<void
> (0) : __assert_fail ("parm->getFunctionScopeIndex() == i"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5798, __PRETTY_FUNCTION__))
;
5799 }
5800#endif
5801
5802 return false;
5803}
5804
5805template<typename Derived>
5806QualType
5807TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5808 FunctionProtoTypeLoc TL) {
5809 SmallVector<QualType, 4> ExceptionStorage;
5810 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5811 return getDerived().TransformFunctionProtoType(
5812 TLB, TL, nullptr, Qualifiers(),
5813 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5814 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5815 ExceptionStorage, Changed);
5816 });
5817}
5818
5819template<typename Derived> template<typename Fn>
5820QualType TreeTransform<Derived>::TransformFunctionProtoType(
5821 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5822 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5823
5824 // Transform the parameters and return type.
5825 //
5826 // We are required to instantiate the params and return type in source order.
5827 // When the function has a trailing return type, we instantiate the
5828 // parameters before the return type, since the return type can then refer
5829 // to the parameters themselves (via decltype, sizeof, etc.).
5830 //
5831 SmallVector<QualType, 4> ParamTypes;
5832 SmallVector<ParmVarDecl*, 4> ParamDecls;
5833 Sema::ExtParameterInfoBuilder ExtParamInfos;
5834 const FunctionProtoType *T = TL.getTypePtr();
5835
5836 QualType ResultType;
5837
5838 if (T->hasTrailingReturn()) {
5839 if (getDerived().TransformFunctionTypeParams(
5840 TL.getBeginLoc(), TL.getParams(),
5841 TL.getTypePtr()->param_type_begin(),
5842 T->getExtParameterInfosOrNull(),
5843 ParamTypes, &ParamDecls, ExtParamInfos))
5844 return QualType();
5845
5846 {
5847 // C++11 [expr.prim.general]p3:
5848 // If a declaration declares a member function or member function
5849 // template of a class X, the expression this is a prvalue of type
5850 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5851 // and the end of the function-definition, member-declarator, or
5852 // declarator.
5853 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5854
5855 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5856 if (ResultType.isNull())
5857 return QualType();
5858 }
5859 }
5860 else {
5861 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5862 if (ResultType.isNull())
5863 return QualType();
5864
5865 if (getDerived().TransformFunctionTypeParams(
5866 TL.getBeginLoc(), TL.getParams(),
5867 TL.getTypePtr()->param_type_begin(),
5868 T->getExtParameterInfosOrNull(),
5869 ParamTypes, &ParamDecls, ExtParamInfos))
5870 return QualType();
5871 }
5872
5873 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5874
5875 bool EPIChanged = false;
5876 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5877 return QualType();
5878
5879 // Handle extended parameter information.
5880 if (auto NewExtParamInfos =
5881 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5882 if (!EPI.ExtParameterInfos ||
5883 llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5884 != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5885 EPIChanged = true;
5886 }
5887 EPI.ExtParameterInfos = NewExtParamInfos;
5888 } else if (EPI.ExtParameterInfos) {
5889 EPIChanged = true;
5890 EPI.ExtParameterInfos = nullptr;
5891 }
5892
5893 QualType Result = TL.getType();
5894 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5895 T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5896 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5897 if (Result.isNull())
5898 return QualType();
5899 }
5900
5901 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5902 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5903 NewTL.setLParenLoc(TL.getLParenLoc());
5904 NewTL.setRParenLoc(TL.getRParenLoc());
5905 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5906 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5907 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5908 NewTL.setParam(i, ParamDecls[i]);
5909
5910 return Result;
5911}
5912
5913template<typename Derived>
5914bool TreeTransform<Derived>::TransformExceptionSpec(
5915 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5916 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5917 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated)((ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated
) ? static_cast<void> (0) : __assert_fail ("ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5917, __PRETTY_FUNCTION__))
;
5918
5919 // Instantiate a dynamic noexcept expression, if any.
5920 if (isComputedNoexcept(ESI.Type)) {
5921 EnterExpressionEvaluationContext Unevaluated(
5922 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5923 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5924 if (NoexceptExpr.isInvalid())
5925 return true;
5926
5927 ExceptionSpecificationType EST = ESI.Type;
5928 NoexceptExpr =
5929 getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5930 if (NoexceptExpr.isInvalid())
5931 return true;
5932
5933 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5934 Changed = true;
5935 ESI.NoexceptExpr = NoexceptExpr.get();
5936 ESI.Type = EST;
5937 }
5938
5939 if (ESI.Type != EST_Dynamic)
5940 return false;
5941
5942 // Instantiate a dynamic exception specification's type.
5943 for (QualType T : ESI.Exceptions) {
5944 if (const PackExpansionType *PackExpansion =
5945 T->getAs<PackExpansionType>()) {
5946 Changed = true;
5947
5948 // We have a pack expansion. Instantiate it.
5949 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5950 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5951 Unexpanded);
5952 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 5952, __PRETTY_FUNCTION__))
;
5953
5954 // Determine whether the set of unexpanded parameter packs can and
5955 // should
5956 // be expanded.
5957 bool Expand = false;
5958 bool RetainExpansion = false;
5959 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5960 // FIXME: Track the location of the ellipsis (and track source location
5961 // information for the types in the exception specification in general).
5962 if (getDerived().TryExpandParameterPacks(
5963 Loc, SourceRange(), Unexpanded, Expand,
5964 RetainExpansion, NumExpansions))
5965 return true;
5966
5967 if (!Expand) {
5968 // We can't expand this pack expansion into separate arguments yet;
5969 // just substitute into the pattern and create a new pack expansion
5970 // type.
5971 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5972 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5973 if (U.isNull())
5974 return true;
5975
5976 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5977 Exceptions.push_back(U);
5978 continue;
5979 }
5980
5981 // Substitute into the pack expansion pattern for each slice of the
5982 // pack.
5983 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5984 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5985
5986 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5987 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5988 return true;
5989
5990 Exceptions.push_back(U);
5991 }
5992 } else {
5993 QualType U = getDerived().TransformType(T);
5994 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5995 return true;
5996 if (T != U)
5997 Changed = true;
5998
5999 Exceptions.push_back(U);
6000 }
6001 }
6002
6003 ESI.Exceptions = Exceptions;
6004 if (ESI.Exceptions.empty())
6005 ESI.Type = EST_DynamicNone;
6006 return false;
6007}
6008
6009template<typename Derived>
6010QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6011 TypeLocBuilder &TLB,
6012 FunctionNoProtoTypeLoc TL) {
6013 const FunctionNoProtoType *T = TL.getTypePtr();
6014 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6015 if (ResultType.isNull())
6016 return QualType();
6017
6018 QualType Result = TL.getType();
6019 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6020 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6021
6022 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6023 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6024 NewTL.setLParenLoc(TL.getLParenLoc());
6025 NewTL.setRParenLoc(TL.getRParenLoc());
6026 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6027
6028 return Result;
6029}
6030
6031template<typename Derived> QualType
6032TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
6033 UnresolvedUsingTypeLoc TL) {
6034 const UnresolvedUsingType *T = TL.getTypePtr();
6035 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6036 if (!D)
6037 return QualType();
6038
6039 QualType Result = TL.getType();
6040 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6041 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6042 if (Result.isNull())
6043 return QualType();
6044 }
6045
6046 // We might get an arbitrary type spec type back. We should at
6047 // least always get a type spec type, though.
6048 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6049 NewTL.setNameLoc(TL.getNameLoc());
6050
6051 return Result;
6052}
6053
6054template<typename Derived>
6055QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6056 TypedefTypeLoc TL) {
6057 const TypedefType *T = TL.getTypePtr();
6058 TypedefNameDecl *Typedef
6059 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6060 T->getDecl()));
6061 if (!Typedef)
6062 return QualType();
6063
6064 QualType Result = TL.getType();
6065 if (getDerived().AlwaysRebuild() ||
6066 Typedef != T->getDecl()) {
6067 Result = getDerived().RebuildTypedefType(Typedef);
6068 if (Result.isNull())
6069 return QualType();
6070 }
6071
6072 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6073 NewTL.setNameLoc(TL.getNameLoc());
6074
6075 return Result;
6076}
6077
6078template<typename Derived>
6079QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6080 TypeOfExprTypeLoc TL) {
6081 // typeof expressions are not potentially evaluated contexts
6082 EnterExpressionEvaluationContext Unevaluated(
6083 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6084 Sema::ReuseLambdaContextDecl);
6085
6086 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6087 if (E.isInvalid())
6088 return QualType();
6089
6090 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6091 if (E.isInvalid())
6092 return QualType();
6093
6094 QualType Result = TL.getType();
6095 if (getDerived().AlwaysRebuild() ||
6096 E.get() != TL.getUnderlyingExpr()) {
6097 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
6098 if (Result.isNull())
6099 return QualType();
6100 }
6101 else E.get();
6102
6103 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6104 NewTL.setTypeofLoc(TL.getTypeofLoc());
6105 NewTL.setLParenLoc(TL.getLParenLoc());
6106 NewTL.setRParenLoc(TL.getRParenLoc());
6107
6108 return Result;
6109}
6110
6111template<typename Derived>
6112QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6113 TypeOfTypeLoc TL) {
6114 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
6115 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6116 if (!New_Under_TI)
6117 return QualType();
6118
6119 QualType Result = TL.getType();
6120 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6121 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
6122 if (Result.isNull())
6123 return QualType();
6124 }
6125
6126 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6127 NewTL.setTypeofLoc(TL.getTypeofLoc());
6128 NewTL.setLParenLoc(TL.getLParenLoc());
6129 NewTL.setRParenLoc(TL.getRParenLoc());
6130 NewTL.setUnderlyingTInfo(New_Under_TI);
6131
6132 return Result;
6133}
6134
6135template<typename Derived>
6136QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6137 DecltypeTypeLoc TL) {
6138 const DecltypeType *T = TL.getTypePtr();
6139
6140 // decltype expressions are not potentially evaluated contexts
6141 EnterExpressionEvaluationContext Unevaluated(
6142 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6143 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6144
6145 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6146 if (E.isInvalid())
6147 return QualType();
6148
6149 E = getSema().ActOnDecltypeExpression(E.get());
6150 if (E.isInvalid())
6151 return QualType();
6152
6153 QualType Result = TL.getType();
6154 if (getDerived().AlwaysRebuild() ||
6155 E.get() != T->getUnderlyingExpr()) {
6156 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
6157 if (Result.isNull())
6158 return QualType();
6159 }
6160 else E.get();
6161
6162 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6163 NewTL.setNameLoc(TL.getNameLoc());
6164
6165 return Result;
6166}
6167
6168template<typename Derived>
6169QualType TreeTransform<Derived>::TransformUnaryTransformType(
6170 TypeLocBuilder &TLB,
6171 UnaryTransformTypeLoc TL) {
6172 QualType Result = TL.getType();
6173 if (Result->isDependentType()) {
6174 const UnaryTransformType *T = TL.getTypePtr();
6175 QualType NewBase =
6176 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6177 Result = getDerived().RebuildUnaryTransformType(NewBase,
6178 T->getUTTKind(),
6179 TL.getKWLoc());
6180 if (Result.isNull())
6181 return QualType();
6182 }
6183
6184 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6185 NewTL.setKWLoc(TL.getKWLoc());
6186 NewTL.setParensRange(TL.getParensRange());
6187 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6188 return Result;
6189}
6190
6191template<typename Derived>
6192QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6193 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6194 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6195
6196 CXXScopeSpec SS;
6197 TemplateName TemplateName = getDerived().TransformTemplateName(
6198 SS, T->getTemplateName(), TL.getTemplateNameLoc());
6199 if (TemplateName.isNull())
6200 return QualType();
6201
6202 QualType OldDeduced = T->getDeducedType();
6203 QualType NewDeduced;
6204 if (!OldDeduced.isNull()) {
6205 NewDeduced = getDerived().TransformType(OldDeduced);
6206 if (NewDeduced.isNull())
6207 return QualType();
6208 }
6209
6210 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6211 TemplateName, NewDeduced);
6212 if (Result.isNull())
6213 return QualType();
6214
6215 DeducedTemplateSpecializationTypeLoc NewTL =
6216 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6217 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6218
6219 return Result;
6220}
6221
6222template<typename Derived>
6223QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6224 RecordTypeLoc TL) {
6225 const RecordType *T = TL.getTypePtr();
6226 RecordDecl *Record
6227 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6228 T->getDecl()));
6229 if (!Record)
6230 return QualType();
6231
6232 QualType Result = TL.getType();
6233 if (getDerived().AlwaysRebuild() ||
6234 Record != T->getDecl()) {
6235 Result = getDerived().RebuildRecordType(Record);
6236 if (Result.isNull())
6237 return QualType();
6238 }
6239
6240 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6241 NewTL.setNameLoc(TL.getNameLoc());
6242
6243 return Result;
6244}
6245
6246template<typename Derived>
6247QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6248 EnumTypeLoc TL) {
6249 const EnumType *T = TL.getTypePtr();
6250 EnumDecl *Enum
6251 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6252 T->getDecl()));
6253 if (!Enum)
6254 return QualType();
6255
6256 QualType Result = TL.getType();
6257 if (getDerived().AlwaysRebuild() ||
6258 Enum != T->getDecl()) {
6259 Result = getDerived().RebuildEnumType(Enum);
6260 if (Result.isNull())
6261 return QualType();
6262 }
6263
6264 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6265 NewTL.setNameLoc(TL.getNameLoc());
6266
6267 return Result;
6268}
6269
6270template<typename Derived>
6271QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6272 TypeLocBuilder &TLB,
6273 InjectedClassNameTypeLoc TL) {
6274 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6275 TL.getTypePtr()->getDecl());
6276 if (!D) return QualType();
6277
6278 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6279 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6280 return T;
6281}
6282
6283template<typename Derived>
6284QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6285 TypeLocBuilder &TLB,
6286 TemplateTypeParmTypeLoc TL) {
6287 return TransformTypeSpecType(TLB, TL);
6288}
6289
6290template<typename Derived>
6291QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6292 TypeLocBuilder &TLB,
6293 SubstTemplateTypeParmTypeLoc TL) {
6294 const SubstTemplateTypeParmType *T = TL.getTypePtr();
6295
6296 // Substitute into the replacement type, which itself might involve something
6297 // that needs to be transformed. This only tends to occur with default
6298 // template arguments of template template parameters.
6299 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6300 QualType Replacement = getDerived().TransformType(T->getReplacementType());
6301 if (Replacement.isNull())
6302 return QualType();
6303
6304 // Always canonicalize the replacement type.
6305 Replacement = SemaRef.Context.getCanonicalType(Replacement);
6306 QualType Result
6307 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
6308 Replacement);
6309
6310 // Propagate type-source information.
6311 SubstTemplateTypeParmTypeLoc NewTL
6312 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6313 NewTL.setNameLoc(TL.getNameLoc());
6314 return Result;
6315
6316}
6317
6318template<typename Derived>
6319QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6320 TypeLocBuilder &TLB,
6321 SubstTemplateTypeParmPackTypeLoc TL) {
6322 return TransformTypeSpecType(TLB, TL);
6323}
6324
6325template<typename Derived>
6326QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6327 TypeLocBuilder &TLB,
6328 TemplateSpecializationTypeLoc TL) {
6329 const TemplateSpecializationType *T = TL.getTypePtr();
6330
6331 // The nested-name-specifier never matters in a TemplateSpecializationType,
6332 // because we can't have a dependent nested-name-specifier anyway.
6333 CXXScopeSpec SS;
6334 TemplateName Template
6335 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6336 TL.getTemplateNameLoc());
6337 if (Template.isNull())
6338 return QualType();
6339
6340 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6341}
6342
6343template<typename Derived>
6344QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6345 AtomicTypeLoc TL) {
6346 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6347 if (ValueType.isNull())
6348 return QualType();
6349
6350 QualType Result = TL.getType();
6351 if (getDerived().AlwaysRebuild() ||
6352 ValueType != TL.getValueLoc().getType()) {
6353 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6354 if (Result.isNull())
6355 return QualType();
6356 }
6357
6358 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6359 NewTL.setKWLoc(TL.getKWLoc());
6360 NewTL.setLParenLoc(TL.getLParenLoc());
6361 NewTL.setRParenLoc(TL.getRParenLoc());
6362
6363 return Result;
6364}
6365
6366template <typename Derived>
6367QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6368 PipeTypeLoc TL) {
6369 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6370 if (ValueType.isNull())
6371 return QualType();
6372
6373 QualType Result = TL.getType();
6374 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6375 const PipeType *PT = Result->castAs<PipeType>();
6376 bool isReadPipe = PT->isReadOnly();
6377 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6378 if (Result.isNull())
6379 return QualType();
6380 }
6381
6382 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6383 NewTL.setKWLoc(TL.getKWLoc());
6384
6385 return Result;
6386}
6387
6388template <typename Derived>
6389QualType TreeTransform<Derived>::TransformExtIntType(TypeLocBuilder &TLB,
6390 ExtIntTypeLoc TL) {
6391 const ExtIntType *EIT = TL.getTypePtr();
6392 QualType Result = TL.getType();
6393
6394 if (getDerived().AlwaysRebuild()) {
6395 Result = getDerived().RebuildExtIntType(EIT->isUnsigned(),
6396 EIT->getNumBits(), TL.getNameLoc());
6397 if (Result.isNull())
6398 return QualType();
6399 }
6400
6401 ExtIntTypeLoc NewTL = TLB.push<ExtIntTypeLoc>(Result);
6402 NewTL.setNameLoc(TL.getNameLoc());
6403 return Result;
6404}
6405
6406template <typename Derived>
6407QualType TreeTransform<Derived>::TransformDependentExtIntType(
6408 TypeLocBuilder &TLB, DependentExtIntTypeLoc TL) {
6409 const DependentExtIntType *EIT = TL.getTypePtr();
6410
6411 EnterExpressionEvaluationContext Unevaluated(
6412 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6413 ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6414 BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6415
6416 if (BitsExpr.isInvalid())
6417 return QualType();
6418
6419 QualType Result = TL.getType();
6420
6421 if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6422 Result = getDerived().RebuildDependentExtIntType(
6423 EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6424
6425 if (Result.isNull())
6426 return QualType();
6427 }
6428
6429 if (isa<DependentExtIntType>(Result)) {
6430 DependentExtIntTypeLoc NewTL = TLB.push<DependentExtIntTypeLoc>(Result);
6431 NewTL.setNameLoc(TL.getNameLoc());
6432 } else {
6433 ExtIntTypeLoc NewTL = TLB.push<ExtIntTypeLoc>(Result);
6434 NewTL.setNameLoc(TL.getNameLoc());
6435 }
6436 return Result;
6437}
6438
6439 /// Simple iterator that traverses the template arguments in a
6440 /// container that provides a \c getArgLoc() member function.
6441 ///
6442 /// This iterator is intended to be used with the iterator form of
6443 /// \c TreeTransform<Derived>::TransformTemplateArguments().
6444 template<typename ArgLocContainer>
6445 class TemplateArgumentLocContainerIterator {
6446 ArgLocContainer *Container;
6447 unsigned Index;
6448
6449 public:
6450 typedef TemplateArgumentLoc value_type;
6451 typedef TemplateArgumentLoc reference;
6452 typedef int difference_type;
6453 typedef std::input_iterator_tag iterator_category;
6454
6455 class pointer {
6456 TemplateArgumentLoc Arg;
6457
6458 public:
6459 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6460
6461 const TemplateArgumentLoc *operator->() const {
6462 return &Arg;
6463 }
6464 };
6465
6466
6467 TemplateArgumentLocContainerIterator() {}
6468
6469 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6470 unsigned Index)
6471 : Container(&Container), Index(Index) { }
6472
6473 TemplateArgumentLocContainerIterator &operator++() {
6474 ++Index;
6475 return *this;
6476 }
6477
6478 TemplateArgumentLocContainerIterator operator++(int) {
6479 TemplateArgumentLocContainerIterator Old(*this);
6480 ++(*this);
6481 return Old;
6482 }
6483
6484 TemplateArgumentLoc operator*() const {
6485 return Container->getArgLoc(Index);
6486 }
6487
6488 pointer operator->() const {
6489 return pointer(Container->getArgLoc(Index));
6490 }
6491
6492 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6493 const TemplateArgumentLocContainerIterator &Y) {
6494 return X.Container == Y.Container && X.Index == Y.Index;
6495 }
6496
6497 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6498 const TemplateArgumentLocContainerIterator &Y) {
6499 return !(X == Y);
6500 }
6501 };
6502
6503template<typename Derived>
6504QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6505 AutoTypeLoc TL) {
6506 const AutoType *T = TL.getTypePtr();
6507 QualType OldDeduced = T->getDeducedType();
6508 QualType NewDeduced;
6509 if (!OldDeduced.isNull()) {
6510 NewDeduced = getDerived().TransformType(OldDeduced);
6511 if (NewDeduced.isNull())
6512 return QualType();
6513 }
6514
6515 ConceptDecl *NewCD = nullptr;
6516 TemplateArgumentListInfo NewTemplateArgs;
6517 NestedNameSpecifierLoc NewNestedNameSpec;
6518 if (TL.getTypePtr()->isConstrained()) {
6519 NewCD = cast_or_null<ConceptDecl>(
6520 getDerived().TransformDecl(
6521 TL.getConceptNameLoc(),
6522 TL.getTypePtr()->getTypeConstraintConcept()));
6523
6524 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6525 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6526 typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6527 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6528 ArgIterator(TL,
6529 TL.getNumArgs()),
6530 NewTemplateArgs))
6531 return QualType();
6532
6533 if (TL.getNestedNameSpecifierLoc()) {
6534 NewNestedNameSpec
6535 = getDerived().TransformNestedNameSpecifierLoc(
6536 TL.getNestedNameSpecifierLoc());
6537 if (!NewNestedNameSpec)
6538 return QualType();
6539 }
6540 }
6541
6542 QualType Result = TL.getType();
6543 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6544 T->isDependentType()) {
6545 llvm::SmallVector<TemplateArgument, 4> NewArgList;
6546 NewArgList.reserve(NewArgList.size());
6547 for (const auto &ArgLoc : NewTemplateArgs.arguments())
6548 NewArgList.push_back(ArgLoc.getArgument());
6549 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6550 NewArgList);
6551 if (Result.isNull())
6552 return QualType();
6553 }
6554
6555 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6556 NewTL.setNameLoc(TL.getNameLoc());
6557 NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6558 NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6559 NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6560 NewTL.setFoundDecl(TL.getFoundDecl());
6561 NewTL.setLAngleLoc(TL.getLAngleLoc());
6562 NewTL.setRAngleLoc(TL.getRAngleLoc());
6563 for (unsigned I = 0; I < TL.getNumArgs(); ++I)
6564 NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6565
6566 return Result;
6567}
6568
6569template <typename Derived>
6570QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6571 TypeLocBuilder &TLB,
6572 TemplateSpecializationTypeLoc TL,
6573 TemplateName Template) {
6574 TemplateArgumentListInfo NewTemplateArgs;
6575 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6576 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6577 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6578 ArgIterator;
6579 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6580 ArgIterator(TL, TL.getNumArgs()),
6581 NewTemplateArgs))
6582 return QualType();
6583
6584 // FIXME: maybe don't rebuild if all the template arguments are the same.
6585
6586 QualType Result =
6587 getDerived().RebuildTemplateSpecializationType(Template,
6588 TL.getTemplateNameLoc(),
6589 NewTemplateArgs);
6590
6591 if (!Result.isNull()) {
6592 // Specializations of template template parameters are represented as
6593 // TemplateSpecializationTypes, and substitution of type alias templates
6594 // within a dependent context can transform them into
6595 // DependentTemplateSpecializationTypes.
6596 if (isa<DependentTemplateSpecializationType>(Result)) {
6597 DependentTemplateSpecializationTypeLoc NewTL
6598 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6599 NewTL.setElaboratedKeywordLoc(SourceLocation());
6600 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6601 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6602 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6603 NewTL.setLAngleLoc(TL.getLAngleLoc());
6604 NewTL.setRAngleLoc(TL.getRAngleLoc());
6605 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6606 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6607 return Result;
6608 }
6609
6610 TemplateSpecializationTypeLoc NewTL
6611 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6612 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6613 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6614 NewTL.setLAngleLoc(TL.getLAngleLoc());
6615 NewTL.setRAngleLoc(TL.getRAngleLoc());
6616 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6617 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6618 }
6619
6620 return Result;
6621}
6622
6623template <typename Derived>
6624QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6625 TypeLocBuilder &TLB,
6626 DependentTemplateSpecializationTypeLoc TL,
6627 TemplateName Template,
6628 CXXScopeSpec &SS) {
6629 TemplateArgumentListInfo NewTemplateArgs;
6630 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6631 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6632 typedef TemplateArgumentLocContainerIterator<
6633 DependentTemplateSpecializationTypeLoc> ArgIterator;
6634 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6635 ArgIterator(TL, TL.getNumArgs()),
6636 NewTemplateArgs))
6637 return QualType();
6638
6639 // FIXME: maybe don't rebuild if all the template arguments are the same.
6640
6641 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6642 QualType Result
6643 = getSema().Context.getDependentTemplateSpecializationType(
6644 TL.getTypePtr()->getKeyword(),
6645 DTN->getQualifier(),
6646 DTN->getIdentifier(),
6647 NewTemplateArgs);
6648
6649 DependentTemplateSpecializationTypeLoc NewTL
6650 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6651 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6652 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6653 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6654 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6655 NewTL.setLAngleLoc(TL.getLAngleLoc());
6656 NewTL.setRAngleLoc(TL.getRAngleLoc());
6657 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6658 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6659 return Result;
6660 }
6661
6662 QualType Result
6663 = getDerived().RebuildTemplateSpecializationType(Template,
6664 TL.getTemplateNameLoc(),
6665 NewTemplateArgs);
6666
6667 if (!Result.isNull()) {
6668 /// FIXME: Wrap this in an elaborated-type-specifier?
6669 TemplateSpecializationTypeLoc NewTL
6670 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6671 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6672 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6673 NewTL.setLAngleLoc(TL.getLAngleLoc());
6674 NewTL.setRAngleLoc(TL.getRAngleLoc());
6675 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6676 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6677 }
6678
6679 return Result;
6680}
6681
6682template<typename Derived>
6683QualType
6684TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6685 ElaboratedTypeLoc TL) {
6686 const ElaboratedType *T = TL.getTypePtr();
6687
6688 NestedNameSpecifierLoc QualifierLoc;
6689 // NOTE: the qualifier in an ElaboratedType is optional.
6690 if (TL.getQualifierLoc()) {
6691 QualifierLoc
6692 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6693 if (!QualifierLoc)
6694 return QualType();
6695 }
6696
6697 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6698 if (NamedT.isNull())
6699 return QualType();
6700
6701 // C++0x [dcl.type.elab]p2:
6702 // If the identifier resolves to a typedef-name or the simple-template-id
6703 // resolves to an alias template specialization, the
6704 // elaborated-type-specifier is ill-formed.
6705 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6706 if (const TemplateSpecializationType *TST =
6707 NamedT->getAs<TemplateSpecializationType>()) {
6708 TemplateName Template = TST->getTemplateName();
6709 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6710 Template.getAsTemplateDecl())) {
6711 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6712 diag::err_tag_reference_non_tag)
6713 << TAT << Sema::NTK_TypeAliasTemplate
6714 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6715 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6716 }
6717 }
6718 }
6719
6720 QualType Result = TL.getType();
6721 if (getDerived().AlwaysRebuild() ||
6722 QualifierLoc != TL.getQualifierLoc() ||
6723 NamedT != T->getNamedType()) {
6724 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6725 T->getKeyword(),
6726 QualifierLoc, NamedT);
6727 if (Result.isNull())
6728 return QualType();
6729 }
6730
6731 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6732 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6733 NewTL.setQualifierLoc(QualifierLoc);
6734 return Result;
6735}
6736
6737template<typename Derived>
6738QualType TreeTransform<Derived>::TransformAttributedType(
6739 TypeLocBuilder &TLB,
6740 AttributedTypeLoc TL) {
6741 const AttributedType *oldType = TL.getTypePtr();
6742 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6743 if (modifiedType.isNull())
6744 return QualType();
6745
6746 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6747 const Attr *oldAttr = TL.getAttr();
6748 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6749 if (oldAttr && !newAttr)
6750 return QualType();
6751
6752 QualType result = TL.getType();
6753
6754 // FIXME: dependent operand expressions?
6755 if (getDerived().AlwaysRebuild() ||
6756 modifiedType != oldType->getModifiedType()) {
6757 // TODO: this is really lame; we should really be rebuilding the
6758 // equivalent type from first principles.
6759 QualType equivalentType
6760 = getDerived().TransformType(oldType->getEquivalentType());
6761 if (equivalentType.isNull())
6762 return QualType();
6763
6764 // Check whether we can add nullability; it is only represented as
6765 // type sugar, and therefore cannot be diagnosed in any other way.
6766 if (auto nullability = oldType->getImmediateNullability()) {
6767 if (!modifiedType->canHaveNullability()) {
6768 SemaRef.Diag(TL.getAttr()->getLocation(),
6769 diag::err_nullability_nonpointer)
6770 << DiagNullabilityKind(*nullability, false) << modifiedType;
6771 return QualType();
6772 }
6773 }
6774
6775 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6776 modifiedType,
6777 equivalentType);
6778 }
6779
6780 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6781 newTL.setAttr(newAttr);
6782 return result;
6783}
6784
6785template<typename Derived>
6786QualType
6787TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6788 ParenTypeLoc TL) {
6789 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6790 if (Inner.isNull())
6791 return QualType();
6792
6793 QualType Result = TL.getType();
6794 if (getDerived().AlwaysRebuild() ||
6795 Inner != TL.getInnerLoc().getType()) {
6796 Result = getDerived().RebuildParenType(Inner);
6797 if (Result.isNull())
6798 return QualType();
6799 }
6800
6801 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6802 NewTL.setLParenLoc(TL.getLParenLoc());
6803 NewTL.setRParenLoc(TL.getRParenLoc());
6804 return Result;
6805}
6806
6807template <typename Derived>
6808QualType
6809TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6810 MacroQualifiedTypeLoc TL) {
6811 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6812 if (Inner.isNull())
6813 return QualType();
6814
6815 QualType Result = TL.getType();
6816 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6817 Result =
6818 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6819 if (Result.isNull())
6820 return QualType();
6821 }
6822
6823 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6824 NewTL.setExpansionLoc(TL.getExpansionLoc());
6825 return Result;
6826}
6827
6828template<typename Derived>
6829QualType TreeTransform<Derived>::TransformDependentNameType(
6830 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6831 return TransformDependentNameType(TLB, TL, false);
6832}
6833
6834template<typename Derived>
6835QualType TreeTransform<Derived>::TransformDependentNameType(
6836 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6837 const DependentNameType *T = TL.getTypePtr();
6838
6839 NestedNameSpecifierLoc QualifierLoc
6840 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6841 if (!QualifierLoc)
6842 return QualType();
6843
6844 QualType Result
6845 = getDerived().RebuildDependentNameType(T->getKeyword(),
6846 TL.getElaboratedKeywordLoc(),
6847 QualifierLoc,
6848 T->getIdentifier(),
6849 TL.getNameLoc(),
6850 DeducedTSTContext);
6851 if (Result.isNull())
6852 return QualType();
6853
6854 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6855 QualType NamedT = ElabT->getNamedType();
6856 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6857
6858 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6859 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6860 NewTL.setQualifierLoc(QualifierLoc);
6861 } else {
6862 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6863 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6864 NewTL.setQualifierLoc(QualifierLoc);
6865 NewTL.setNameLoc(TL.getNameLoc());
6866 }
6867 return Result;
6868}
6869
6870template<typename Derived>
6871QualType TreeTransform<Derived>::
6872 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6873 DependentTemplateSpecializationTypeLoc TL) {
6874 NestedNameSpecifierLoc QualifierLoc;
6875 if (TL.getQualifierLoc()) {
6876 QualifierLoc
6877 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6878 if (!QualifierLoc)
6879 return QualType();
6880 }
6881
6882 return getDerived()
6883 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6884}
6885
6886template<typename Derived>
6887QualType TreeTransform<Derived>::
6888TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6889 DependentTemplateSpecializationTypeLoc TL,
6890 NestedNameSpecifierLoc QualifierLoc) {
6891 const DependentTemplateSpecializationType *T = TL.getTypePtr();
6892
6893 TemplateArgumentListInfo NewTemplateArgs;
6894 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6895 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6896
6897 typedef TemplateArgumentLocContainerIterator<
6898 DependentTemplateSpecializationTypeLoc> ArgIterator;
6899 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6900 ArgIterator(TL, TL.getNumArgs()),
6901 NewTemplateArgs))
6902 return QualType();
6903
6904 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6905 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6906 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6907 /*AllowInjectedClassName*/ false);
6908 if (Result.isNull())
6909 return QualType();
6910
6911 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6912 QualType NamedT = ElabT->getNamedType();
6913
6914 // Copy information relevant to the template specialization.
6915 TemplateSpecializationTypeLoc NamedTL
6916 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6917 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6918 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6919 NamedTL.setLAngleLoc(TL.getLAngleLoc());
6920 NamedTL.setRAngleLoc(TL.getRAngleLoc());
6921 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6922 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6923
6924 // Copy information relevant to the elaborated type.
6925 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6926 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6927 NewTL.setQualifierLoc(QualifierLoc);
6928 } else if (isa<DependentTemplateSpecializationType>(Result)) {
6929 DependentTemplateSpecializationTypeLoc SpecTL
6930 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6931 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6932 SpecTL.setQualifierLoc(QualifierLoc);
6933 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6934 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6935 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6936 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6937 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6938 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6939 } else {
6940 TemplateSpecializationTypeLoc SpecTL
6941 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6942 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6943 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6944 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6945 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6946 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6947 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6948 }
6949 return Result;
6950}
6951
6952template<typename Derived>
6953QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6954 PackExpansionTypeLoc TL) {
6955 QualType Pattern
6956 = getDerived().TransformType(TLB, TL.getPatternLoc());
6957 if (Pattern.isNull())
6958 return QualType();
6959
6960 QualType Result = TL.getType();
6961 if (getDerived().AlwaysRebuild() ||
6962 Pattern != TL.getPatternLoc().getType()) {
6963 Result = getDerived().RebuildPackExpansionType(Pattern,
6964 TL.getPatternLoc().getSourceRange(),
6965 TL.getEllipsisLoc(),
6966 TL.getTypePtr()->getNumExpansions());
6967 if (Result.isNull())
6968 return QualType();
6969 }
6970
6971 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6972 NewT.setEllipsisLoc(TL.getEllipsisLoc());
6973 return Result;
6974}
6975
6976template<typename Derived>
6977QualType
6978TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6979 ObjCInterfaceTypeLoc TL) {
6980 // ObjCInterfaceType is never dependent.
6981 TLB.pushFullCopy(TL);
6982 return TL.getType();
6983}
6984
6985template<typename Derived>
6986QualType
6987TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6988 ObjCTypeParamTypeLoc TL) {
6989 const ObjCTypeParamType *T = TL.getTypePtr();
6990 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6991 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6992 if (!OTP)
6993 return QualType();
6994
6995 QualType Result = TL.getType();
6996 if (getDerived().AlwaysRebuild() ||
6997 OTP != T->getDecl()) {
6998 Result = getDerived().RebuildObjCTypeParamType(OTP,
6999 TL.getProtocolLAngleLoc(),
7000 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
7001 TL.getNumProtocols()),
7002 TL.getProtocolLocs(),
7003 TL.getProtocolRAngleLoc());
7004 if (Result.isNull())
7005 return QualType();
7006 }
7007
7008 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7009 if (TL.getNumProtocols()) {
7010 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7011 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7012 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7013 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7014 }
7015 return Result;
7016}
7017
7018template<typename Derived>
7019QualType
7020TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7021 ObjCObjectTypeLoc TL) {
7022 // Transform base type.
7023 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7024 if (BaseType.isNull())
7025 return QualType();
7026
7027 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7028
7029 // Transform type arguments.
7030 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7031 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7032 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7033 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7034 QualType TypeArg = TypeArgInfo->getType();
7035 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7036 AnyChanged = true;
7037
7038 // We have a pack expansion. Instantiate it.
7039 const auto *PackExpansion = PackExpansionLoc.getType()
7040 ->castAs<PackExpansionType>();
7041 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7042 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7043 Unexpanded);
7044 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7044, __PRETTY_FUNCTION__))
;
7045
7046 // Determine whether the set of unexpanded parameter packs can
7047 // and should be expanded.
7048 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7049 bool Expand = false;
7050 bool RetainExpansion = false;
7051 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7052 if (getDerived().TryExpandParameterPacks(
7053 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7054 Unexpanded, Expand, RetainExpansion, NumExpansions))
7055 return QualType();
7056
7057 if (!Expand) {
7058 // We can't expand this pack expansion into separate arguments yet;
7059 // just substitute into the pattern and create a new pack expansion
7060 // type.
7061 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7062
7063 TypeLocBuilder TypeArgBuilder;
7064 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7065 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7066 PatternLoc);
7067 if (NewPatternType.isNull())
7068 return QualType();
7069
7070 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7071 NewPatternType, NumExpansions);
7072 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7073 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7074 NewTypeArgInfos.push_back(
7075 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7076 continue;
7077 }
7078
7079 // Substitute into the pack expansion pattern for each slice of the
7080 // pack.
7081 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7082 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7083
7084 TypeLocBuilder TypeArgBuilder;
7085 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7086
7087 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7088 PatternLoc);
7089 if (NewTypeArg.isNull())
7090 return QualType();
7091
7092 NewTypeArgInfos.push_back(
7093 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7094 }
7095
7096 continue;
7097 }
7098
7099 TypeLocBuilder TypeArgBuilder;
7100 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7101 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7102 if (NewTypeArg.isNull())
7103 return QualType();
7104
7105 // If nothing changed, just keep the old TypeSourceInfo.
7106 if (NewTypeArg == TypeArg) {
7107 NewTypeArgInfos.push_back(TypeArgInfo);
7108 continue;
7109 }
7110
7111 NewTypeArgInfos.push_back(
7112 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7113 AnyChanged = true;
7114 }
7115
7116 QualType Result = TL.getType();
7117 if (getDerived().AlwaysRebuild() || AnyChanged) {
7118 // Rebuild the type.
7119 Result = getDerived().RebuildObjCObjectType(
7120 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7121 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7122 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7123 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7124
7125 if (Result.isNull())
7126 return QualType();
7127 }
7128
7129 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7130 NewT.setHasBaseTypeAsWritten(true);
7131 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7132 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7133 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7134 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7135 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7136 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7137 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7138 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7139 return Result;
7140}
7141
7142template<typename Derived>
7143QualType
7144TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7145 ObjCObjectPointerTypeLoc TL) {
7146 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7147 if (PointeeType.isNull())
7148 return QualType();
7149
7150 QualType Result = TL.getType();
7151 if (getDerived().AlwaysRebuild() ||
7152 PointeeType != TL.getPointeeLoc().getType()) {
7153 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7154 TL.getStarLoc());
7155 if (Result.isNull())
7156 return QualType();
7157 }
7158
7159 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7160 NewT.setStarLoc(TL.getStarLoc());
7161 return Result;
7162}
7163
7164//===----------------------------------------------------------------------===//
7165// Statement transformation
7166//===----------------------------------------------------------------------===//
7167template<typename Derived>
7168StmtResult
7169TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7170 return S;
7171}
7172
7173template<typename Derived>
7174StmtResult
7175TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7176 return getDerived().TransformCompoundStmt(S, false);
7177}
7178
7179template<typename Derived>
7180StmtResult
7181TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7182 bool IsStmtExpr) {
7183 Sema::CompoundScopeRAII CompoundScope(getSema());
7184
7185 const Stmt *ExprResult = S->getStmtExprResult();
7186 bool SubStmtInvalid = false;
7187 bool SubStmtChanged = false;
7188 SmallVector<Stmt*, 8> Statements;
7189 for (auto *B : S->body()) {
7190 StmtResult Result = getDerived().TransformStmt(
7191 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7192
7193 if (Result.isInvalid()) {
7194 // Immediately fail if this was a DeclStmt, since it's very
7195 // likely that this will cause problems for future statements.
7196 if (isa<DeclStmt>(B))
7197 return StmtError();
7198
7199 // Otherwise, just keep processing substatements and fail later.
7200 SubStmtInvalid = true;
7201 continue;
7202 }
7203
7204 SubStmtChanged = SubStmtChanged || Result.get() != B;
7205 Statements.push_back(Result.getAs<Stmt>());
7206 }
7207
7208 if (SubStmtInvalid)
7209 return StmtError();
7210
7211 if (!getDerived().AlwaysRebuild() &&
7212 !SubStmtChanged)
7213 return S;
7214
7215 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7216 Statements,
7217 S->getRBracLoc(),
7218 IsStmtExpr);
7219}
7220
7221template<typename Derived>
7222StmtResult
7223TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7224 ExprResult LHS, RHS;
7225 {
7226 EnterExpressionEvaluationContext Unevaluated(
7227 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7228
7229 // Transform the left-hand case value.
7230 LHS = getDerived().TransformExpr(S->getLHS());
7231 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7232 if (LHS.isInvalid())
7233 return StmtError();
7234
7235 // Transform the right-hand case value (for the GNU case-range extension).
7236 RHS = getDerived().TransformExpr(S->getRHS());
7237 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7238 if (RHS.isInvalid())
7239 return StmtError();
7240 }
7241
7242 // Build the case statement.
7243 // Case statements are always rebuilt so that they will attached to their
7244 // transformed switch statement.
7245 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7246 LHS.get(),
7247 S->getEllipsisLoc(),
7248 RHS.get(),
7249 S->getColonLoc());
7250 if (Case.isInvalid())
7251 return StmtError();
7252
7253 // Transform the statement following the case
7254 StmtResult SubStmt =
7255 getDerived().TransformStmt(S->getSubStmt());
7256 if (SubStmt.isInvalid())
7257 return StmtError();
7258
7259 // Attach the body to the case statement
7260 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7261}
7262
7263template <typename Derived>
7264StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7265 // Transform the statement following the default case
7266 StmtResult SubStmt =
7267 getDerived().TransformStmt(S->getSubStmt());
7268 if (SubStmt.isInvalid())
7269 return StmtError();
7270
7271 // Default statements are always rebuilt
7272 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7273 SubStmt.get());
7274}
7275
7276template<typename Derived>
7277StmtResult
7278TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7279 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7280 if (SubStmt.isInvalid())
7281 return StmtError();
7282
7283 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7284 S->getDecl());
7285 if (!LD)
7286 return StmtError();
7287
7288 // If we're transforming "in-place" (we're not creating new local
7289 // declarations), assume we're replacing the old label statement
7290 // and clear out the reference to it.
7291 if (LD == S->getDecl())
7292 S->getDecl()->setStmt(nullptr);
7293
7294 // FIXME: Pass the real colon location in.
7295 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7296 cast<LabelDecl>(LD), SourceLocation(),
7297 SubStmt.get());
7298}
7299
7300template <typename Derived>
7301const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7302 if (!R)
7303 return R;
7304
7305 switch (R->getKind()) {
7306// Transform attributes with a pragma spelling by calling TransformXXXAttr.
7307#define ATTR(X)
7308#define PRAGMA_SPELLING_ATTR(X) \
7309 case attr::X: \
7310 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7311#include "clang/Basic/AttrList.inc"
7312 default:
7313 return R;
7314 }
7315}
7316
7317template <typename Derived>
7318StmtResult
7319TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7320 StmtDiscardKind SDK) {
7321 bool AttrsChanged = false;
7322 SmallVector<const Attr *, 1> Attrs;
7323
7324 // Visit attributes and keep track if any are transformed.
7325 for (const auto *I : S->getAttrs()) {
7326 const Attr *R = getDerived().TransformAttr(I);
7327 AttrsChanged |= (I != R);
7328 Attrs.push_back(R);
7329 }
7330
7331 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7332 if (SubStmt.isInvalid())
7333 return StmtError();
7334
7335 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7336 return S;
7337
7338 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7339 SubStmt.get());
7340}
7341
7342template<typename Derived>
7343StmtResult
7344TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7345 // Transform the initialization statement
7346 StmtResult Init = getDerived().TransformStmt(S->getInit());
7347 if (Init.isInvalid())
7348 return StmtError();
7349
7350 // Transform the condition
7351 Sema::ConditionResult Cond = getDerived().TransformCondition(
7352 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7353 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7354 : Sema::ConditionKind::Boolean);
7355 if (Cond.isInvalid())
7356 return StmtError();
7357
7358 // If this is a constexpr if, determine which arm we should instantiate.
7359 llvm::Optional<bool> ConstexprConditionValue;
7360 if (S->isConstexpr())
7361 ConstexprConditionValue = Cond.getKnownValue();
7362
7363 // Transform the "then" branch.
7364 StmtResult Then;
7365 if (!ConstexprConditionValue || *ConstexprConditionValue) {
7366 Then = getDerived().TransformStmt(S->getThen());
7367 if (Then.isInvalid())
7368 return StmtError();
7369 } else {
7370 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7371 }
7372
7373 // Transform the "else" branch.
7374 StmtResult Else;
7375 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7376 Else = getDerived().TransformStmt(S->getElse());
7377 if (Else.isInvalid())
7378 return StmtError();
7379 }
7380
7381 if (!getDerived().AlwaysRebuild() &&
7382 Init.get() == S->getInit() &&
7383 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7384 Then.get() == S->getThen() &&
7385 Else.get() == S->getElse())
7386 return S;
7387
7388 return getDerived().RebuildIfStmt(
7389 S->getIfLoc(), S->isConstexpr(), S->getLParenLoc(), Cond,
7390 S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7391}
7392
7393template<typename Derived>
7394StmtResult
7395TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7396 // Transform the initialization statement
7397 StmtResult Init = getDerived().TransformStmt(S->getInit());
7398 if (Init.isInvalid())
7399 return StmtError();
7400
7401 // Transform the condition.
7402 Sema::ConditionResult Cond = getDerived().TransformCondition(
7403 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7404 Sema::ConditionKind::Switch);
7405 if (Cond.isInvalid())
7406 return StmtError();
7407
7408 // Rebuild the switch statement.
7409 StmtResult Switch =
7410 getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7411 Init.get(), Cond, S->getRParenLoc());
7412 if (Switch.isInvalid())
7413 return StmtError();
7414
7415 // Transform the body of the switch statement.
7416 StmtResult Body = getDerived().TransformStmt(S->getBody());
7417 if (Body.isInvalid())
7418 return StmtError();
7419
7420 // Complete the switch statement.
7421 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7422 Body.get());
7423}
7424
7425template<typename Derived>
7426StmtResult
7427TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7428 // Transform the condition
7429 Sema::ConditionResult Cond = getDerived().TransformCondition(
7430 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7431 Sema::ConditionKind::Boolean);
7432 if (Cond.isInvalid())
7433 return StmtError();
7434
7435 // Transform the body
7436 StmtResult Body = getDerived().TransformStmt(S->getBody());
7437 if (Body.isInvalid())
7438 return StmtError();
7439
7440 if (!getDerived().AlwaysRebuild() &&
7441 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7442 Body.get() == S->getBody())
7443 return Owned(S);
7444
7445 return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7446 Cond, S->getRParenLoc(), Body.get());
7447}
7448
7449template<typename Derived>
7450StmtResult
7451TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7452 // Transform the body
7453 StmtResult Body = getDerived().TransformStmt(S->getBody());
7454 if (Body.isInvalid())
7455 return StmtError();
7456
7457 // Transform the condition
7458 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7459 if (Cond.isInvalid())
7460 return StmtError();
7461
7462 if (!getDerived().AlwaysRebuild() &&
7463 Cond.get() == S->getCond() &&
7464 Body.get() == S->getBody())
7465 return S;
7466
7467 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7468 /*FIXME:*/S->getWhileLoc(), Cond.get(),
7469 S->getRParenLoc());
7470}
7471
7472template<typename Derived>
7473StmtResult
7474TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7475 if (getSema().getLangOpts().OpenMP)
7476 getSema().startOpenMPLoop();
7477
7478 // Transform the initialization statement
7479 StmtResult Init = getDerived().TransformStmt(S->getInit());
7480 if (Init.isInvalid())
7481 return StmtError();
7482
7483 // In OpenMP loop region loop control variable must be captured and be
7484 // private. Perform analysis of first part (if any).
7485 if (getSema().getLangOpts().OpenMP && Init.isUsable())
7486 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7487
7488 // Transform the condition
7489 Sema::ConditionResult Cond = getDerived().TransformCondition(
7490 S->getForLoc(), S->getConditionVariable(), S->getCond(),
7491 Sema::ConditionKind::Boolean);
7492 if (Cond.isInvalid())
7493 return StmtError();
7494
7495 // Transform the increment
7496 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7497 if (Inc.isInvalid())
7498 return StmtError();
7499
7500 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7501 if (S->getInc() && !FullInc.get())
7502 return StmtError();
7503
7504 // Transform the body
7505 StmtResult Body = getDerived().TransformStmt(S->getBody());
7506 if (Body.isInvalid())
7507 return StmtError();
7508
7509 if (!getDerived().AlwaysRebuild() &&
7510 Init.get() == S->getInit() &&
7511 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7512 Inc.get() == S->getInc() &&
7513 Body.get() == S->getBody())
7514 return S;
7515
7516 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7517 Init.get(), Cond, FullInc,
7518 S->getRParenLoc(), Body.get());
7519}
7520
7521template<typename Derived>
7522StmtResult
7523TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7524 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7525 S->getLabel());
7526 if (!LD)
7527 return StmtError();
7528
7529 // Goto statements must always be rebuilt, to resolve the label.
7530 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7531 cast<LabelDecl>(LD));
7532}
7533
7534template<typename Derived>
7535StmtResult
7536TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7537 ExprResult Target = getDerived().TransformExpr(S->getTarget());
7538 if (Target.isInvalid())
7539 return StmtError();
7540 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7541
7542 if (!getDerived().AlwaysRebuild() &&
7543 Target.get() == S->getTarget())
7544 return S;
7545
7546 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7547 Target.get());
7548}
7549
7550template<typename Derived>
7551StmtResult
7552TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7553 return S;
7554}
7555
7556template<typename Derived>
7557StmtResult
7558TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7559 return S;
7560}
7561
7562template<typename Derived>
7563StmtResult
7564TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7565 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7566 /*NotCopyInit*/false);
7567 if (Result.isInvalid())
7568 return StmtError();
7569
7570 // FIXME: We always rebuild the return statement because there is no way
7571 // to tell whether the return type of the function has changed.
7572 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7573}
7574
7575template<typename Derived>
7576StmtResult
7577TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7578 bool DeclChanged = false;
7579 SmallVector<Decl *, 4> Decls;
7580 for (auto *D : S->decls()) {
7581 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7582 if (!Transformed)
7583 return StmtError();
7584
7585 if (Transformed != D)
7586 DeclChanged = true;
7587
7588 Decls.push_back(Transformed);
7589 }
7590
7591 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7592 return S;
7593
7594 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7595}
7596
7597template<typename Derived>
7598StmtResult
7599TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7600
7601 SmallVector<Expr*, 8> Constraints;
7602 SmallVector<Expr*, 8> Exprs;
7603 SmallVector<IdentifierInfo *, 4> Names;
7604
7605 ExprResult AsmString;
7606 SmallVector<Expr*, 8> Clobbers;
7607
7608 bool ExprsChanged = false;
7609
7610 // Go through the outputs.
7611 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7612 Names.push_back(S->getOutputIdentifier(I));
7613
7614 // No need to transform the constraint literal.
7615 Constraints.push_back(S->getOutputConstraintLiteral(I));
7616
7617 // Transform the output expr.
7618 Expr *OutputExpr = S->getOutputExpr(I);
7619 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7620 if (Result.isInvalid())
7621 return StmtError();
7622
7623 ExprsChanged |= Result.get() != OutputExpr;
7624
7625 Exprs.push_back(Result.get());
7626 }
7627
7628 // Go through the inputs.
7629 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7630 Names.push_back(S->getInputIdentifier(I));
7631
7632 // No need to transform the constraint literal.
7633 Constraints.push_back(S->getInputConstraintLiteral(I));
7634
7635 // Transform the input expr.
7636 Expr *InputExpr = S->getInputExpr(I);
7637 ExprResult Result = getDerived().TransformExpr(InputExpr);
7638 if (Result.isInvalid())
7639 return StmtError();
7640
7641 ExprsChanged |= Result.get() != InputExpr;
7642
7643 Exprs.push_back(Result.get());
7644 }
7645
7646 // Go through the Labels.
7647 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7648 Names.push_back(S->getLabelIdentifier(I));
7649
7650 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7651 if (Result.isInvalid())
7652 return StmtError();
7653 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7654 Exprs.push_back(Result.get());
7655 }
7656 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7657 return S;
7658
7659 // Go through the clobbers.
7660 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7661 Clobbers.push_back(S->getClobberStringLiteral(I));
7662
7663 // No need to transform the asm string literal.
7664 AsmString = S->getAsmString();
7665 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7666 S->isVolatile(), S->getNumOutputs(),
7667 S->getNumInputs(), Names.data(),
7668 Constraints, Exprs, AsmString.get(),
7669 Clobbers, S->getNumLabels(),
7670 S->getRParenLoc());
7671}
7672
7673template<typename Derived>
7674StmtResult
7675TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7676 ArrayRef<Token> AsmToks =
7677 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7678
7679 bool HadError = false, HadChange = false;
7680
7681 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7682 SmallVector<Expr*, 8> TransformedExprs;
7683 TransformedExprs.reserve(SrcExprs.size());
7684 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7685 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7686 if (!Result.isUsable()) {
7687 HadError = true;
7688 } else {
7689 HadChange |= (Result.get() != SrcExprs[i]);
7690 TransformedExprs.push_back(Result.get());
7691 }
7692 }
7693
7694 if (HadError) return StmtError();
7695 if (!HadChange && !getDerived().AlwaysRebuild())
7696 return Owned(S);
7697
7698 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7699 AsmToks, S->getAsmString(),
7700 S->getNumOutputs(), S->getNumInputs(),
7701 S->getAllConstraints(), S->getClobbers(),
7702 TransformedExprs, S->getEndLoc());
7703}
7704
7705// C++ Coroutines TS
7706
7707template<typename Derived>
7708StmtResult
7709TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7710 auto *ScopeInfo = SemaRef.getCurFunction();
7711 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7712 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7716, __PRETTY_FUNCTION__))
7713 ScopeInfo->NeedsCoroutineSuspends &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7716, __PRETTY_FUNCTION__))
7714 ScopeInfo->CoroutineSuspends.first == nullptr &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7716, __PRETTY_FUNCTION__))
7715 ScopeInfo->CoroutineSuspends.second == nullptr &&((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7716, __PRETTY_FUNCTION__))
7716 "expected clean scope info")((FD && ScopeInfo && !ScopeInfo->CoroutinePromise
&& ScopeInfo->NeedsCoroutineSuspends && ScopeInfo
->CoroutineSuspends.first == nullptr && ScopeInfo->
CoroutineSuspends.second == nullptr && "expected clean scope info"
) ? static_cast<void> (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7716, __PRETTY_FUNCTION__))
;
7717
7718 // Set that we have (possibly-invalid) suspend points before we do anything
7719 // that may fail.
7720 ScopeInfo->setNeedsCoroutineSuspends(false);
7721
7722 // We re-build the coroutine promise object (and the coroutine parameters its
7723 // type and constructor depend on) based on the types used in our current
7724 // function. We must do so, and set it on the current FunctionScopeInfo,
7725 // before attempting to transform the other parts of the coroutine body
7726 // statement, such as the implicit suspend statements (because those
7727 // statements reference the FunctionScopeInfo::CoroutinePromise).
7728 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7729 return StmtError();
7730 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7731 if (!Promise)
7732 return StmtError();
7733 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7734 ScopeInfo->CoroutinePromise = Promise;
7735
7736 // Transform the implicit coroutine statements constructed using dependent
7737 // types during the previous parse: initial and final suspensions, the return
7738 // object, and others. We also transform the coroutine function's body.
7739 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7740 if (InitSuspend.isInvalid())
7741 return StmtError();
7742 StmtResult FinalSuspend =
7743 getDerived().TransformStmt(S->getFinalSuspendStmt());
7744 if (FinalSuspend.isInvalid() ||
7745 !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7746 return StmtError();
7747 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7748 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()))((isa<Expr>(InitSuspend.get()) && isa<Expr>
(FinalSuspend.get())) ? static_cast<void> (0) : __assert_fail
("isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7748, __PRETTY_FUNCTION__))
;
7749
7750 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7751 if (BodyRes.isInvalid())
7752 return StmtError();
7753
7754 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7755 if (Builder.isInvalid())
7756 return StmtError();
7757
7758 Expr *ReturnObject = S->getReturnValueInit();
7759 assert(ReturnObject && "the return object is expected to be valid")((ReturnObject && "the return object is expected to be valid"
) ? static_cast<void> (0) : __assert_fail ("ReturnObject && \"the return object is expected to be valid\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7759, __PRETTY_FUNCTION__))
;
7760 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7761 /*NoCopyInit*/ false);
7762 if (Res.isInvalid())
7763 return StmtError();
7764 Builder.ReturnValue = Res.get();
7765
7766 // If during the previous parse the coroutine still had a dependent promise
7767 // statement, we may need to build some implicit coroutine statements
7768 // (such as exception and fallthrough handlers) for the first time.
7769 if (S->hasDependentPromiseType()) {
7770 // We can only build these statements, however, if the current promise type
7771 // is not dependent.
7772 if (!Promise->getType()->isDependentType()) {
7773 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&((!S->getFallthroughHandler() && !S->getExceptionHandler
() && !S->getReturnStmtOnAllocFailure() &&
!S->getDeallocate() && "these nodes should not have been built yet"
) ? static_cast<void> (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7775, __PRETTY_FUNCTION__))
7774 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&((!S->getFallthroughHandler() && !S->getExceptionHandler
() && !S->getReturnStmtOnAllocFailure() &&
!S->getDeallocate() && "these nodes should not have been built yet"
) ? static_cast<void> (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7775, __PRETTY_FUNCTION__))
7775 "these nodes should not have been built yet")((!S->getFallthroughHandler() && !S->getExceptionHandler
() && !S->getReturnStmtOnAllocFailure() &&
!S->getDeallocate() && "these nodes should not have been built yet"
) ? static_cast<void> (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7775, __PRETTY_FUNCTION__))
;
7776 if (!Builder.buildDependentStatements())
7777 return StmtError();
7778 }
7779 } else {
7780 if (auto *OnFallthrough = S->getFallthroughHandler()) {
7781 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7782 if (Res.isInvalid())
7783 return StmtError();
7784 Builder.OnFallthrough = Res.get();
7785 }
7786
7787 if (auto *OnException = S->getExceptionHandler()) {
7788 StmtResult Res = getDerived().TransformStmt(OnException);
7789 if (Res.isInvalid())
7790 return StmtError();
7791 Builder.OnException = Res.get();
7792 }
7793
7794 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7795 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7796 if (Res.isInvalid())
7797 return StmtError();
7798 Builder.ReturnStmtOnAllocFailure = Res.get();
7799 }
7800
7801 // Transform any additional statements we may have already built
7802 assert(S->getAllocate() && S->getDeallocate() &&((S->getAllocate() && S->getDeallocate() &&
"allocation and deallocation calls must already be built") ?
static_cast<void> (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7803, __PRETTY_FUNCTION__))
7803 "allocation and deallocation calls must already be built")((S->getAllocate() && S->getDeallocate() &&
"allocation and deallocation calls must already be built") ?
static_cast<void> (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7803, __PRETTY_FUNCTION__))
;
7804 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7805 if (AllocRes.isInvalid())
7806 return StmtError();
7807 Builder.Allocate = AllocRes.get();
7808
7809 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7810 if (DeallocRes.isInvalid())
7811 return StmtError();
7812 Builder.Deallocate = DeallocRes.get();
7813
7814 assert(S->getResultDecl() && "ResultDecl must already be built")((S->getResultDecl() && "ResultDecl must already be built"
) ? static_cast<void> (0) : __assert_fail ("S->getResultDecl() && \"ResultDecl must already be built\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 7814, __PRETTY_FUNCTION__))
;
7815 StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7816 if (ResultDecl.isInvalid())
7817 return StmtError();
7818 Builder.ResultDecl = ResultDecl.get();
7819
7820 if (auto *ReturnStmt = S->getReturnStmt()) {
7821 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7822 if (Res.isInvalid())
7823 return StmtError();
7824 Builder.ReturnStmt = Res.get();
7825 }
7826 }
7827
7828 return getDerived().RebuildCoroutineBodyStmt(Builder);
7829}
7830
7831template<typename Derived>
7832StmtResult
7833TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7834 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7835 /*NotCopyInit*/false);
7836 if (Result.isInvalid())
7837 return StmtError();
7838
7839 // Always rebuild; we don't know if this needs to be injected into a new
7840 // context or if the promise type has changed.
7841 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7842 S->isImplicit());
7843}
7844
7845template<typename Derived>
7846ExprResult
7847TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7848 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7849 /*NotCopyInit*/false);
7850 if (Result.isInvalid())
7851 return ExprError();
7852
7853 // Always rebuild; we don't know if this needs to be injected into a new
7854 // context or if the promise type has changed.
7855 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7856 E->isImplicit());
7857}
7858
7859template <typename Derived>
7860ExprResult
7861TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7862 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7863 /*NotCopyInit*/ false);
7864 if (OperandResult.isInvalid())
7865 return ExprError();
7866
7867 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7868 E->getOperatorCoawaitLookup());
7869
7870 if (LookupResult.isInvalid())
7871 return ExprError();
7872
7873 // Always rebuild; we don't know if this needs to be injected into a new
7874 // context or if the promise type has changed.
7875 return getDerived().RebuildDependentCoawaitExpr(
7876 E->getKeywordLoc(), OperandResult.get(),
7877 cast<UnresolvedLookupExpr>(LookupResult.get()));
7878}
7879
7880template<typename Derived>
7881ExprResult
7882TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7883 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7884 /*NotCopyInit*/false);
7885 if (Result.isInvalid())
7886 return ExprError();
7887
7888 // Always rebuild; we don't know if this needs to be injected into a new
7889 // context or if the promise type has changed.
7890 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7891}
7892
7893// Objective-C Statements.
7894
7895template<typename Derived>
7896StmtResult
7897TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7898 // Transform the body of the @try.
7899 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7900 if (TryBody.isInvalid())
7901 return StmtError();
7902
7903 // Transform the @catch statements (if present).
7904 bool AnyCatchChanged = false;
7905 SmallVector<Stmt*, 8> CatchStmts;
7906 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7907 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7908 if (Catch.isInvalid())
7909 return StmtError();
7910 if (Catch.get() != S->getCatchStmt(I))
7911 AnyCatchChanged = true;
7912 CatchStmts.push_back(Catch.get());
7913 }
7914
7915 // Transform the @finally statement (if present).
7916 StmtResult Finally;
7917 if (S->getFinallyStmt()) {
7918 Finally = getDerived().TransformStmt(S->getFinallyStmt());
7919 if (Finally.isInvalid())
7920 return StmtError();
7921 }
7922
7923 // If nothing changed, just retain this statement.
7924 if (!getDerived().AlwaysRebuild() &&
7925 TryBody.get() == S->getTryBody() &&
7926 !AnyCatchChanged &&
7927 Finally.get() == S->getFinallyStmt())
7928 return S;
7929
7930 // Build a new statement.
7931 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7932 CatchStmts, Finally.get());
7933}
7934
7935template<typename Derived>
7936StmtResult
7937TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7938 // Transform the @catch parameter, if there is one.
7939 VarDecl *Var = nullptr;
7940 if (VarDecl *FromVar = S->getCatchParamDecl()) {
7941 TypeSourceInfo *TSInfo = nullptr;
7942 if (FromVar->getTypeSourceInfo()) {
7943 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7944 if (!TSInfo)
7945 return StmtError();
7946 }
7947
7948 QualType T;
7949 if (TSInfo)
7950 T = TSInfo->getType();
7951 else {
7952 T = getDerived().TransformType(FromVar->getType());
7953 if (T.isNull())
7954 return StmtError();
7955 }
7956
7957 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7958 if (!Var)
7959 return StmtError();
7960 }
7961
7962 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7963 if (Body.isInvalid())
7964 return StmtError();
7965
7966 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7967 S->getRParenLoc(),
7968 Var, Body.get());
7969}
7970
7971template<typename Derived>
7972StmtResult
7973TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7974 // Transform the body.
7975 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7976 if (Body.isInvalid())
7977 return StmtError();
7978
7979 // If nothing changed, just retain this statement.
7980 if (!getDerived().AlwaysRebuild() &&
7981 Body.get() == S->getFinallyBody())
7982 return S;
7983
7984 // Build a new statement.
7985 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7986 Body.get());
7987}
7988
7989template<typename Derived>
7990StmtResult
7991TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7992 ExprResult Operand;
7993 if (S->getThrowExpr()) {
7994 Operand = getDerived().TransformExpr(S->getThrowExpr());
7995 if (Operand.isInvalid())
7996 return StmtError();
7997 }
7998
7999 if (!getDerived().AlwaysRebuild() &&
8000 Operand.get() == S->getThrowExpr())
8001 return S;
8002
8003 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8004}
8005
8006template<typename Derived>
8007StmtResult
8008TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8009 ObjCAtSynchronizedStmt *S) {
8010 // Transform the object we are locking.
8011 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8012 if (Object.isInvalid())
8013 return StmtError();
8014 Object =
8015 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8016 Object.get());
8017 if (Object.isInvalid())
8018 return StmtError();
8019
8020 // Transform the body.
8021 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8022 if (Body.isInvalid())
8023 return StmtError();
8024
8025 // If nothing change, just retain the current statement.
8026 if (!getDerived().AlwaysRebuild() &&
8027 Object.get() == S->getSynchExpr() &&
8028 Body.get() == S->getSynchBody())
8029 return S;
8030
8031 // Build a new statement.
8032 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8033 Object.get(), Body.get());
8034}
8035
8036template<typename Derived>
8037StmtResult
8038TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8039 ObjCAutoreleasePoolStmt *S) {
8040 // Transform the body.
8041 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8042 if (Body.isInvalid())
8043 return StmtError();
8044
8045 // If nothing changed, just retain this statement.
8046 if (!getDerived().AlwaysRebuild() &&
8047 Body.get() == S->getSubStmt())
8048 return S;
8049
8050 // Build a new statement.
8051 return getDerived().RebuildObjCAutoreleasePoolStmt(
8052 S->getAtLoc(), Body.get());
8053}
8054
8055template<typename Derived>
8056StmtResult
8057TreeTransform<Derived>::TransformObjCForCollectionStmt(
8058 ObjCForCollectionStmt *S) {
8059 // Transform the element statement.
8060 StmtResult Element =
8061 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8062 if (Element.isInvalid())
8063 return StmtError();
8064
8065 // Transform the collection expression.
8066 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8067 if (Collection.isInvalid())
8068 return StmtError();
8069
8070 // Transform the body.
8071 StmtResult Body = getDerived().TransformStmt(S->getBody());
8072 if (Body.isInvalid())
8073 return StmtError();
8074
8075 // If nothing changed, just retain this statement.
8076 if (!getDerived().AlwaysRebuild() &&
8077 Element.get() == S->getElement() &&
8078 Collection.get() == S->getCollection() &&
8079 Body.get() == S->getBody())
8080 return S;
8081
8082 // Build a new statement.
8083 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8084 Element.get(),
8085 Collection.get(),
8086 S->getRParenLoc(),
8087 Body.get());
8088}
8089
8090template <typename Derived>
8091StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8092 // Transform the exception declaration, if any.
8093 VarDecl *Var = nullptr;
8094 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8095 TypeSourceInfo *T =
8096 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8097 if (!T)
8098 return StmtError();
8099
8100 Var = getDerived().RebuildExceptionDecl(
8101 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8102 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8103 if (!Var || Var->isInvalidDecl())
8104 return StmtError();
8105 }
8106
8107 // Transform the actual exception handler.
8108 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8109 if (Handler.isInvalid())
8110 return StmtError();
8111
8112 if (!getDerived().AlwaysRebuild() && !Var &&
8113 Handler.get() == S->getHandlerBlock())
8114 return S;
8115
8116 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8117}
8118
8119template <typename Derived>
8120StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8121 // Transform the try block itself.
8122 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8123 if (TryBlock.isInvalid())
8124 return StmtError();
8125
8126 // Transform the handlers.
8127 bool HandlerChanged = false;
8128 SmallVector<Stmt *, 8> Handlers;
8129 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8130 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8131 if (Handler.isInvalid())
8132 return StmtError();
8133
8134 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8135 Handlers.push_back(Handler.getAs<Stmt>());
8136 }
8137
8138 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8139 !HandlerChanged)
8140 return S;
8141
8142 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8143 Handlers);
8144}
8145
8146template<typename Derived>
8147StmtResult
8148TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8149 StmtResult Init =
8150 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8151 if (Init.isInvalid())
8152 return StmtError();
8153
8154 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8155 if (Range.isInvalid())
8156 return StmtError();
8157
8158 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8159 if (Begin.isInvalid())
8160 return StmtError();
8161 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8162 if (End.isInvalid())
8163 return StmtError();
8164
8165 ExprResult Cond = getDerived().TransformExpr(S->getCond());
8166 if (Cond.isInvalid())
8167 return StmtError();
8168 if (Cond.get())
8169 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8170 if (Cond.isInvalid())
8171 return StmtError();
8172 if (Cond.get())
8173 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8174
8175 ExprResult Inc = getDerived().TransformExpr(S->getInc());
8176 if (Inc.isInvalid())
8177 return StmtError();
8178 if (Inc.get())
8179 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8180
8181 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8182 if (LoopVar.isInvalid())
8183 return StmtError();
8184
8185 StmtResult NewStmt = S;
8186 if (getDerived().AlwaysRebuild() ||
8187 Init.get() != S->getInit() ||
8188 Range.get() != S->getRangeStmt() ||
8189 Begin.get() != S->getBeginStmt() ||
8190 End.get() != S->getEndStmt() ||
8191 Cond.get() != S->getCond() ||
8192 Inc.get() != S->getInc() ||
8193 LoopVar.get() != S->getLoopVarStmt()) {
8194 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8195 S->getCoawaitLoc(), Init.get(),
8196 S->getColonLoc(), Range.get(),
8197 Begin.get(), End.get(),
8198 Cond.get(),
8199 Inc.get(), LoopVar.get(),
8200 S->getRParenLoc());
8201 if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8202 // Might not have attached any initializer to the loop variable.
8203 getSema().ActOnInitializerError(
8204 cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8205 return StmtError();
8206 }
8207 }
8208
8209 StmtResult Body = getDerived().TransformStmt(S->getBody());
8210 if (Body.isInvalid())
8211 return StmtError();
8212
8213 // Body has changed but we didn't rebuild the for-range statement. Rebuild
8214 // it now so we have a new statement to attach the body to.
8215 if (Body.get() != S->getBody() && NewStmt.get() == S) {
8216 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8217 S->getCoawaitLoc(), Init.get(),
8218 S->getColonLoc(), Range.get(),
8219 Begin.get(), End.get(),
8220 Cond.get(),
8221 Inc.get(), LoopVar.get(),
8222 S->getRParenLoc());
8223 if (NewStmt.isInvalid())
8224 return StmtError();
8225 }
8226
8227 if (NewStmt.get() == S)
8228 return S;
8229
8230 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8231}
8232
8233template<typename Derived>
8234StmtResult
8235TreeTransform<Derived>::TransformMSDependentExistsStmt(
8236 MSDependentExistsStmt *S) {
8237 // Transform the nested-name-specifier, if any.
8238 NestedNameSpecifierLoc QualifierLoc;
8239 if (S->getQualifierLoc()) {
8240 QualifierLoc
8241 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8242 if (!QualifierLoc)
8243 return StmtError();
8244 }
8245
8246 // Transform the declaration name.
8247 DeclarationNameInfo NameInfo = S->getNameInfo();
8248 if (NameInfo.getName()) {
8249 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8250 if (!NameInfo.getName())
8251 return StmtError();
8252 }
8253
8254 // Check whether anything changed.
8255 if (!getDerived().AlwaysRebuild() &&
8256 QualifierLoc == S->getQualifierLoc() &&
8257 NameInfo.getName() == S->getNameInfo().getName())
8258 return S;
8259
8260 // Determine whether this name exists, if we can.
8261 CXXScopeSpec SS;
8262 SS.Adopt(QualifierLoc);
8263 bool Dependent = false;
8264 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8265 case Sema::IER_Exists:
8266 if (S->isIfExists())
8267 break;
8268
8269 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8270
8271 case Sema::IER_DoesNotExist:
8272 if (S->isIfNotExists())
8273 break;
8274
8275 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8276
8277 case Sema::IER_Dependent:
8278 Dependent = true;
8279 break;
8280
8281 case Sema::IER_Error:
8282 return StmtError();
8283 }
8284
8285 // We need to continue with the instantiation, so do so now.
8286 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8287 if (SubStmt.isInvalid())
8288 return StmtError();
8289
8290 // If we have resolved the name, just transform to the substatement.
8291 if (!Dependent)
8292 return SubStmt;
8293
8294 // The name is still dependent, so build a dependent expression again.
8295 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8296 S->isIfExists(),
8297 QualifierLoc,
8298 NameInfo,
8299 SubStmt.get());
8300}
8301
8302template<typename Derived>
8303ExprResult
8304TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8305 NestedNameSpecifierLoc QualifierLoc;
8306 if (E->getQualifierLoc()) {
8307 QualifierLoc
8308 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8309 if (!QualifierLoc)
8310 return ExprError();
8311 }
8312
8313 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8314 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8315 if (!PD)
8316 return ExprError();
8317
8318 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8319 if (Base.isInvalid())
8320 return ExprError();
8321
8322 return new (SemaRef.getASTContext())
8323 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8324 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8325 QualifierLoc, E->getMemberLoc());
8326}
8327
8328template <typename Derived>
8329ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8330 MSPropertySubscriptExpr *E) {
8331 auto BaseRes = getDerived().TransformExpr(E->getBase());
8332 if (BaseRes.isInvalid())
8333 return ExprError();
8334 auto IdxRes = getDerived().TransformExpr(E->getIdx());
8335 if (IdxRes.isInvalid())
8336 return ExprError();
8337
8338 if (!getDerived().AlwaysRebuild() &&
8339 BaseRes.get() == E->getBase() &&
8340 IdxRes.get() == E->getIdx())
8341 return E;
8342
8343 return getDerived().RebuildArraySubscriptExpr(
8344 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8345}
8346
8347template <typename Derived>
8348StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8349 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8350 if (TryBlock.isInvalid())
8351 return StmtError();
8352
8353 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8354 if (Handler.isInvalid())
8355 return StmtError();
8356
8357 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8358 Handler.get() == S->getHandler())
8359 return S;
8360
8361 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8362 TryBlock.get(), Handler.get());
8363}
8364
8365template <typename Derived>
8366StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8367 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8368 if (Block.isInvalid())
8369 return StmtError();
8370
8371 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8372}
8373
8374template <typename Derived>
8375StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8376 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8377 if (FilterExpr.isInvalid())
8378 return StmtError();
8379
8380 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8381 if (Block.isInvalid())
8382 return StmtError();
8383
8384 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8385 Block.get());
8386}
8387
8388template <typename Derived>
8389StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8390 if (isa<SEHFinallyStmt>(Handler))
8391 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8392 else
8393 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8394}
8395
8396template<typename Derived>
8397StmtResult
8398TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8399 return S;
8400}
8401
8402//===----------------------------------------------------------------------===//
8403// OpenMP directive transformation
8404//===----------------------------------------------------------------------===//
8405
8406template <typename Derived>
8407StmtResult
8408TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8409 // OMPCanonicalLoops are eliminated during transformation, since they will be
8410 // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8411 // after transformation.
8412 return getDerived().TransformStmt(L->getLoopStmt());
8413}
8414
8415template <typename Derived>
8416StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8417 OMPExecutableDirective *D) {
8418
8419 // Transform the clauses
8420 llvm::SmallVector<OMPClause *, 16> TClauses;
8421 ArrayRef<OMPClause *> Clauses = D->clauses();
8422 TClauses.reserve(Clauses.size());
8423 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8424 I != E; ++I) {
8425 if (*I) {
8426 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8427 OMPClause *Clause = getDerived().TransformOMPClause(*I);
8428 getDerived().getSema().EndOpenMPClause();
8429 if (Clause)
8430 TClauses.push_back(Clause);
8431 } else {
8432 TClauses.push_back(nullptr);
8433 }
8434 }
8435 StmtResult AssociatedStmt;
8436 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8437 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8438 /*CurScope=*/nullptr);
8439 StmtResult Body;
8440 {
8441 Sema::CompoundScopeRAII CompoundScope(getSema());
8442 Stmt *CS;
8443 if (D->getDirectiveKind() == OMPD_atomic ||
8444 D->getDirectiveKind() == OMPD_critical ||
8445 D->getDirectiveKind() == OMPD_section ||
8446 D->getDirectiveKind() == OMPD_master)
8447 CS = D->getAssociatedStmt();
8448 else
8449 CS = D->getRawStmt();
8450 Body = getDerived().TransformStmt(CS);
8451 if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8452 getSema().getLangOpts().OpenMPIRBuilder)
8453 Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8454 }
8455 AssociatedStmt =
8456 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8457 if (AssociatedStmt.isInvalid()) {
8458 return StmtError();
8459 }
8460 }
8461 if (TClauses.size() != Clauses.size()) {
8462 return StmtError();
8463 }
8464
8465 // Transform directive name for 'omp critical' directive.
8466 DeclarationNameInfo DirName;
8467 if (D->getDirectiveKind() == OMPD_critical) {
8468 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8469 DirName = getDerived().TransformDeclarationNameInfo(DirName);
8470 }
8471 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8472 if (D->getDirectiveKind() == OMPD_cancellation_point) {
8473 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8474 } else if (D->getDirectiveKind() == OMPD_cancel) {
8475 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8476 }
8477
8478 return getDerived().RebuildOMPExecutableDirective(
8479 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8480 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8481}
8482
8483template <typename Derived>
8484StmtResult
8485TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8486 DeclarationNameInfo DirName;
8487 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8488 D->getBeginLoc());
8489 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8490 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8491 return Res;
8492}
8493
8494template <typename Derived>
8495StmtResult
8496TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8497 DeclarationNameInfo DirName;
8498 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8499 D->getBeginLoc());
8500 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8501 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8502 return Res;
8503}
8504
8505template <typename Derived>
8506StmtResult
8507TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8508 DeclarationNameInfo DirName;
8509 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8510 nullptr, D->getBeginLoc());
8511 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8512 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8513 return Res;
8514}
8515
8516template <typename Derived>
8517StmtResult
8518TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8519 DeclarationNameInfo DirName;
8520 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8521 D->getBeginLoc());
8522 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8523 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8524 return Res;
8525}
8526
8527template <typename Derived>
8528StmtResult
8529TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8530 DeclarationNameInfo DirName;
8531 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8532 D->getBeginLoc());
8533 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8534 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8535 return Res;
8536}
8537
8538template <typename Derived>
8539StmtResult
8540TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8541 DeclarationNameInfo DirName;
8542 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8543 D->getBeginLoc());
8544 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8545 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8546 return Res;
8547}
8548
8549template <typename Derived>
8550StmtResult
8551TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8552 DeclarationNameInfo DirName;
8553 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8554 D->getBeginLoc());
8555 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8556 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8557 return Res;
8558}
8559
8560template <typename Derived>
8561StmtResult
8562TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8563 DeclarationNameInfo DirName;
8564 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8565 D->getBeginLoc());
8566 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8567 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8568 return Res;
8569}
8570
8571template <typename Derived>
8572StmtResult
8573TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8574 DeclarationNameInfo DirName;
8575 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8576 D->getBeginLoc());
8577 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8578 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8579 return Res;
8580}
8581
8582template <typename Derived>
8583StmtResult
8584TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8585 getDerived().getSema().StartOpenMPDSABlock(
8586 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8587 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8588 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8589 return Res;
8590}
8591
8592template <typename Derived>
8593StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8594 OMPParallelForDirective *D) {
8595 DeclarationNameInfo DirName;
8596 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8597 nullptr, D->getBeginLoc());
8598 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8599 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8600 return Res;
8601}
8602
8603template <typename Derived>
8604StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8605 OMPParallelForSimdDirective *D) {
8606 DeclarationNameInfo DirName;
8607 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8608 nullptr, D->getBeginLoc());
8609 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8610 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8611 return Res;
8612}
8613
8614template <typename Derived>
8615StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8616 OMPParallelMasterDirective *D) {
8617 DeclarationNameInfo DirName;
8618 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8619 nullptr, D->getBeginLoc());
8620 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8621 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8622 return Res;
8623}
8624
8625template <typename Derived>
8626StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8627 OMPParallelSectionsDirective *D) {
8628 DeclarationNameInfo DirName;
8629 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8630 nullptr, D->getBeginLoc());
8631 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8632 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8633 return Res;
8634}
8635
8636template <typename Derived>
8637StmtResult
8638TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8639 DeclarationNameInfo DirName;
8640 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8641 D->getBeginLoc());
8642 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8643 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8644 return Res;
8645}
8646
8647template <typename Derived>
8648StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8649 OMPTaskyieldDirective *D) {
8650 DeclarationNameInfo DirName;
8651 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8652 D->getBeginLoc());
8653 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8654 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8655 return Res;
8656}
8657
8658template <typename Derived>
8659StmtResult
8660TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8661 DeclarationNameInfo DirName;
8662 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8663 D->getBeginLoc());
8664 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8665 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8666 return Res;
8667}
8668
8669template <typename Derived>
8670StmtResult
8671TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8672 DeclarationNameInfo DirName;
8673 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8674 D->getBeginLoc());
8675 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8676 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8677 return Res;
8678}
8679
8680template <typename Derived>
8681StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8682 OMPTaskgroupDirective *D) {
8683 DeclarationNameInfo DirName;
8684 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8685 D->getBeginLoc());
8686 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8687 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8688 return Res;
8689}
8690
8691template <typename Derived>
8692StmtResult
8693TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8694 DeclarationNameInfo DirName;
8695 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8696 D->getBeginLoc());
8697 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8698 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8699 return Res;
8700}
8701
8702template <typename Derived>
8703StmtResult
8704TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8705 DeclarationNameInfo DirName;
8706 getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8707 D->getBeginLoc());
8708 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8709 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8710 return Res;
8711}
8712
8713template <typename Derived>
8714StmtResult
8715TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
8716 DeclarationNameInfo DirName;
8717 getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
8718 D->getBeginLoc());
8719 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8720 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8721 return Res;
8722}
8723
8724template <typename Derived>
8725StmtResult
8726TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8727 DeclarationNameInfo DirName;
8728 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8729 D->getBeginLoc());
8730 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8731 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8732 return Res;
8733}
8734
8735template <typename Derived>
8736StmtResult
8737TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8738 DeclarationNameInfo DirName;
8739 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8740 D->getBeginLoc());
8741 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8742 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8743 return Res;
8744}
8745
8746template <typename Derived>
8747StmtResult
8748TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8749 DeclarationNameInfo DirName;
8750 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8751 D->getBeginLoc());
8752 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8753 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8754 return Res;
8755}
8756
8757template <typename Derived>
8758StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8759 OMPTargetDataDirective *D) {
8760 DeclarationNameInfo DirName;
8761 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8762 D->getBeginLoc());
8763 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8764 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8765 return Res;
8766}
8767
8768template <typename Derived>
8769StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8770 OMPTargetEnterDataDirective *D) {
8771 DeclarationNameInfo DirName;
8772 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8773 nullptr, D->getBeginLoc());
8774 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8775 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8776 return Res;
8777}
8778
8779template <typename Derived>
8780StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8781 OMPTargetExitDataDirective *D) {
8782 DeclarationNameInfo DirName;
8783 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8784 nullptr, D->getBeginLoc());
8785 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8786 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8787 return Res;
8788}
8789
8790template <typename Derived>
8791StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8792 OMPTargetParallelDirective *D) {
8793 DeclarationNameInfo DirName;
8794 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8795 nullptr, D->getBeginLoc());
8796 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8797 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8798 return Res;
8799}
8800
8801template <typename Derived>
8802StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8803 OMPTargetParallelForDirective *D) {
8804 DeclarationNameInfo DirName;
8805 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8806 nullptr, D->getBeginLoc());
8807 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8808 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8809 return Res;
8810}
8811
8812template <typename Derived>
8813StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8814 OMPTargetUpdateDirective *D) {
8815 DeclarationNameInfo DirName;
8816 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8817 nullptr, D->getBeginLoc());
8818 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8819 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8820 return Res;
8821}
8822
8823template <typename Derived>
8824StmtResult
8825TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8826 DeclarationNameInfo DirName;
8827 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8828 D->getBeginLoc());
8829 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8830 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8831 return Res;
8832}
8833
8834template <typename Derived>
8835StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8836 OMPCancellationPointDirective *D) {
8837 DeclarationNameInfo DirName;
8838 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8839 nullptr, D->getBeginLoc());
8840 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8841 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8842 return Res;
8843}
8844
8845template <typename Derived>
8846StmtResult
8847TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8848 DeclarationNameInfo DirName;
8849 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8850 D->getBeginLoc());
8851 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8852 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8853 return Res;
8854}
8855
8856template <typename Derived>
8857StmtResult
8858TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8859 DeclarationNameInfo DirName;
8860 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8861 D->getBeginLoc());
8862 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8863 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8864 return Res;
8865}
8866
8867template <typename Derived>
8868StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8869 OMPTaskLoopSimdDirective *D) {
8870 DeclarationNameInfo DirName;
8871 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8872 nullptr, D->getBeginLoc());
8873 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8874 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8875 return Res;
8876}
8877
8878template <typename Derived>
8879StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8880 OMPMasterTaskLoopDirective *D) {
8881 DeclarationNameInfo DirName;
8882 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8883 nullptr, D->getBeginLoc());
8884 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8885 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8886 return Res;
8887}
8888
8889template <typename Derived>
8890StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8891 OMPMasterTaskLoopSimdDirective *D) {
8892 DeclarationNameInfo DirName;
8893 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8894 nullptr, D->getBeginLoc());
8895 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8896 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8897 return Res;
8898}
8899
8900template <typename Derived>
8901StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8902 OMPParallelMasterTaskLoopDirective *D) {
8903 DeclarationNameInfo DirName;
8904 getDerived().getSema().StartOpenMPDSABlock(
8905 OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8906 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8907 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8908 return Res;
8909}
8910
8911template <typename Derived>
8912StmtResult
8913TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
8914 OMPParallelMasterTaskLoopSimdDirective *D) {
8915 DeclarationNameInfo DirName;
8916 getDerived().getSema().StartOpenMPDSABlock(
8917 OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
8918 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8919 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8920 return Res;
8921}
8922
8923template <typename Derived>
8924StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8925 OMPDistributeDirective *D) {
8926 DeclarationNameInfo DirName;
8927 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8928 D->getBeginLoc());
8929 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8930 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8931 return Res;
8932}
8933
8934template <typename Derived>
8935StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8936 OMPDistributeParallelForDirective *D) {
8937 DeclarationNameInfo DirName;
8938 getDerived().getSema().StartOpenMPDSABlock(
8939 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8940 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8941 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8942 return Res;
8943}
8944
8945template <typename Derived>
8946StmtResult
8947TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8948 OMPDistributeParallelForSimdDirective *D) {
8949 DeclarationNameInfo DirName;
8950 getDerived().getSema().StartOpenMPDSABlock(
8951 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8952 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8953 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8954 return Res;
8955}
8956
8957template <typename Derived>
8958StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8959 OMPDistributeSimdDirective *D) {
8960 DeclarationNameInfo DirName;
8961 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8962 nullptr, D->getBeginLoc());
8963 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8964 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8965 return Res;
8966}
8967
8968template <typename Derived>
8969StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8970 OMPTargetParallelForSimdDirective *D) {
8971 DeclarationNameInfo DirName;
8972 getDerived().getSema().StartOpenMPDSABlock(
8973 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8974 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8975 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8976 return Res;
8977}
8978
8979template <typename Derived>
8980StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8981 OMPTargetSimdDirective *D) {
8982 DeclarationNameInfo DirName;
8983 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8984 D->getBeginLoc());
8985 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8986 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8987 return Res;
8988}
8989
8990template <typename Derived>
8991StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8992 OMPTeamsDistributeDirective *D) {
8993 DeclarationNameInfo DirName;
8994 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8995 nullptr, D->getBeginLoc());
8996 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8997 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8998 return Res;
8999}
9000
9001template <typename Derived>
9002StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9003 OMPTeamsDistributeSimdDirective *D) {
9004 DeclarationNameInfo DirName;
9005 getDerived().getSema().StartOpenMPDSABlock(
9006 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9007 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9008 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9009 return Res;
9010}
9011
9012template <typename Derived>
9013StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9014 OMPTeamsDistributeParallelForSimdDirective *D) {
9015 DeclarationNameInfo DirName;
9016 getDerived().getSema().StartOpenMPDSABlock(
9017 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9018 D->getBeginLoc());
9019 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9020 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9021 return Res;
9022}
9023
9024template <typename Derived>
9025StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9026 OMPTeamsDistributeParallelForDirective *D) {
9027 DeclarationNameInfo DirName;
9028 getDerived().getSema().StartOpenMPDSABlock(
9029 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9030 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9031 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9032 return Res;
9033}
9034
9035template <typename Derived>
9036StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9037 OMPTargetTeamsDirective *D) {
9038 DeclarationNameInfo DirName;
9039 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9040 nullptr, D->getBeginLoc());
9041 auto Res = getDerived().TransformOMPExecutableDirective(D);
9042 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9043 return Res;
9044}
9045
9046template <typename Derived>
9047StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9048 OMPTargetTeamsDistributeDirective *D) {
9049 DeclarationNameInfo DirName;
9050 getDerived().getSema().StartOpenMPDSABlock(
9051 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9052 auto Res = getDerived().TransformOMPExecutableDirective(D);
9053 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9054 return Res;
9055}
9056
9057template <typename Derived>
9058StmtResult
9059TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9060 OMPTargetTeamsDistributeParallelForDirective *D) {
9061 DeclarationNameInfo DirName;
9062 getDerived().getSema().StartOpenMPDSABlock(
9063 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9064 D->getBeginLoc());
9065 auto Res = getDerived().TransformOMPExecutableDirective(D);
9066 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9067 return Res;
9068}
9069
9070template <typename Derived>
9071StmtResult TreeTransform<Derived>::
9072 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9073 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9074 DeclarationNameInfo DirName;
9075 getDerived().getSema().StartOpenMPDSABlock(
9076 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9077 D->getBeginLoc());
9078 auto Res = getDerived().TransformOMPExecutableDirective(D);
9079 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9080 return Res;
9081}
9082
9083template <typename Derived>
9084StmtResult
9085TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9086 OMPTargetTeamsDistributeSimdDirective *D) {
9087 DeclarationNameInfo DirName;
9088 getDerived().getSema().StartOpenMPDSABlock(
9089 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9090 auto Res = getDerived().TransformOMPExecutableDirective(D);
9091 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9092 return Res;
9093}
9094
9095template <typename Derived>
9096StmtResult
9097TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9098 DeclarationNameInfo DirName;
9099 getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9100 D->getBeginLoc());
9101 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9102 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9103 return Res;
9104}
9105
9106template <typename Derived>
9107StmtResult
9108TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9109 DeclarationNameInfo DirName;
9110 getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9111 D->getBeginLoc());
9112 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9113 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9114 return Res;
9115}
9116
9117template <typename Derived>
9118StmtResult
9119TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9120 DeclarationNameInfo DirName;
9121 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9122 D->getBeginLoc());
9123 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9124 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9125 return Res;
9126}
9127
9128//===----------------------------------------------------------------------===//
9129// OpenMP clause transformation
9130//===----------------------------------------------------------------------===//
9131template <typename Derived>
9132OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9133 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9134 if (Cond.isInvalid())
9135 return nullptr;
9136 return getDerived().RebuildOMPIfClause(
9137 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9138 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9139}
9140
9141template <typename Derived>
9142OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9143 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9144 if (Cond.isInvalid())
9145 return nullptr;
9146 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9147 C->getLParenLoc(), C->getEndLoc());
9148}
9149
9150template <typename Derived>
9151OMPClause *
9152TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9153 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9154 if (NumThreads.isInvalid())
9155 return nullptr;
9156 return getDerived().RebuildOMPNumThreadsClause(
9157 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9158}
9159
9160template <typename Derived>
9161OMPClause *
9162TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9163 ExprResult E = getDerived().TransformExpr(C->getSafelen());
9164 if (E.isInvalid())
9165 return nullptr;
9166 return getDerived().RebuildOMPSafelenClause(
9167 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9168}
9169
9170template <typename Derived>
9171OMPClause *
9172TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9173 ExprResult E = getDerived().TransformExpr(C->getAllocator());
9174 if (E.isInvalid())
9175 return nullptr;
9176 return getDerived().RebuildOMPAllocatorClause(
9177 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9178}
9179
9180template <typename Derived>
9181OMPClause *
9182TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9183 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9184 if (E.isInvalid())
9185 return nullptr;
9186 return getDerived().RebuildOMPSimdlenClause(
9187 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9188}
9189
9190template <typename Derived>
9191OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9192 SmallVector<Expr *, 4> TransformedSizes;
9193 TransformedSizes.reserve(C->getNumSizes());
9194 bool Changed = false;
9195 for (Expr *E : C->getSizesRefs()) {
9196 if (!E) {
9197 TransformedSizes.push_back(nullptr);
9198 continue;
9199 }
9200
9201 ExprResult T = getDerived().TransformExpr(E);
9202 if (T.isInvalid())
9203 return nullptr;
9204 if (E != T.get())
9205 Changed = true;
9206 TransformedSizes.push_back(T.get());
9207 }
9208
9209 if (!Changed && !getDerived().AlwaysRebuild())
9210 return C;
9211 return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9212 C->getLParenLoc(), C->getEndLoc());
9213}
9214
9215template <typename Derived>
9216OMPClause *
9217TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9218 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9219 if (E.isInvalid())
9220 return nullptr;
9221 return getDerived().RebuildOMPCollapseClause(
9222 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9223}
9224
9225template <typename Derived>
9226OMPClause *
9227TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9228 return getDerived().RebuildOMPDefaultClause(
9229 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9230 C->getLParenLoc(), C->getEndLoc());
9231}
9232
9233template <typename Derived>
9234OMPClause *
9235TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9236 return getDerived().RebuildOMPProcBindClause(
9237 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9238 C->getLParenLoc(), C->getEndLoc());
9239}
9240
9241template <typename Derived>
9242OMPClause *
9243TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9244 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9245 if (E.isInvalid())
9246 return nullptr;
9247 return getDerived().RebuildOMPScheduleClause(
9248 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9249 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9250 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9251 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9252}
9253
9254template <typename Derived>
9255OMPClause *
9256TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9257 ExprResult E;
9258 if (auto *Num = C->getNumForLoops()) {
9259 E = getDerived().TransformExpr(Num);
9260 if (E.isInvalid())
9261 return nullptr;
9262 }
9263 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9264 C->getLParenLoc(), E.get());
9265}
9266
9267template <typename Derived>
9268OMPClause *
9269TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9270 ExprResult E;
9271 if (Expr *Evt = C->getEventHandler()) {
9272 E = getDerived().TransformExpr(Evt);
9273 if (E.isInvalid())
9274 return nullptr;
9275 }
9276 return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9277 C->getLParenLoc(), C->getEndLoc());
9278}
9279
9280template <typename Derived>
9281OMPClause *
9282TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9283 // No need to rebuild this clause, no template-dependent parameters.
9284 return C;
9285}
9286
9287template <typename Derived>
9288OMPClause *
9289TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9290 // No need to rebuild this clause, no template-dependent parameters.
9291 return C;
9292}
9293
9294template <typename Derived>
9295OMPClause *
9296TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9297 // No need to rebuild this clause, no template-dependent parameters.
9298 return C;
9299}
9300
9301template <typename Derived>
9302OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9303 // No need to rebuild this clause, no template-dependent parameters.
9304 return C;
9305}
9306
9307template <typename Derived>
9308OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9309 // No need to rebuild this clause, no template-dependent parameters.
9310 return C;
9311}
9312
9313template <typename Derived>
9314OMPClause *
9315TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9316 // No need to rebuild this clause, no template-dependent parameters.
9317 return C;
9318}
9319
9320template <typename Derived>
9321OMPClause *
9322TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9323 // No need to rebuild this clause, no template-dependent parameters.
9324 return C;
9325}
9326
9327template <typename Derived>
9328OMPClause *
9329TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9330 // No need to rebuild this clause, no template-dependent parameters.
9331 return C;
9332}
9333
9334template <typename Derived>
9335OMPClause *
9336TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9337 // No need to rebuild this clause, no template-dependent parameters.
9338 return C;
9339}
9340
9341template <typename Derived>
9342OMPClause *
9343TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9344 // No need to rebuild this clause, no template-dependent parameters.
9345 return C;
9346}
9347
9348template <typename Derived>
9349OMPClause *
9350TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9351 // No need to rebuild this clause, no template-dependent parameters.
9352 return C;
9353}
9354
9355template <typename Derived>
9356OMPClause *
9357TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9358 // No need to rebuild this clause, no template-dependent parameters.
9359 return C;
9360}
9361
9362template <typename Derived>
9363OMPClause *
9364TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9365 // No need to rebuild this clause, no template-dependent parameters.
9366 return C;
9367}
9368
9369template <typename Derived>
9370OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9371 // No need to rebuild this clause, no template-dependent parameters.
9372 return C;
9373}
9374
9375template <typename Derived>
9376OMPClause *
9377TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9378 // No need to rebuild this clause, no template-dependent parameters.
9379 return C;
9380}
9381
9382template <typename Derived>
9383OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9384 ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9385 if (IVR.isInvalid())
9386 return nullptr;
9387
9388 llvm::SmallVector<Expr *, 8> PrefExprs;
9389 PrefExprs.reserve(C->varlist_size() - 1);
9390 for (Expr *E : llvm::drop_begin(C->varlists())) {
9391 ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9392 if (ER.isInvalid())
9393 return nullptr;
9394 PrefExprs.push_back(ER.get());
9395 }
9396 return getDerived().RebuildOMPInitClause(
9397 IVR.get(), PrefExprs, C->getIsTarget(), C->getIsTargetSync(),
9398 C->getBeginLoc(), C->getLParenLoc(), C->getVarLoc(), C->getEndLoc());
9399}
9400
9401template <typename Derived>
9402OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9403 ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9404 if (ER.isInvalid())
9405 return nullptr;
9406 return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9407 C->getLParenLoc(), C->getVarLoc(),
9408 C->getEndLoc());
9409}
9410
9411template <typename Derived>
9412OMPClause *
9413TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9414 ExprResult ER;
9415 if (Expr *IV = C->getInteropVar()) {
9416 ER = getDerived().TransformExpr(IV);
9417 if (ER.isInvalid())
9418 return nullptr;
9419 }
9420 return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9421 C->getLParenLoc(), C->getVarLoc(),
9422 C->getEndLoc());
9423}
9424
9425template <typename Derived>
9426OMPClause *
9427TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9428 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9429 if (Cond.isInvalid())
9430 return nullptr;
9431 return getDerived().RebuildOMPNovariantsClause(
9432 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9433}
9434
9435template <typename Derived>
9436OMPClause *
9437TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9438 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9439 if (Cond.isInvalid())
9440 return nullptr;
9441 return getDerived().RebuildOMPNocontextClause(
9442 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9443}
9444
9445template <typename Derived>
9446OMPClause *
9447TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9448 ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9449 if (ThreadID.isInvalid())
9450 return nullptr;
9451 return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9452 C->getLParenLoc(), C->getEndLoc());
9453}
9454
9455template <typename Derived>
9456OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9457 OMPUnifiedAddressClause *C) {
9458 llvm_unreachable("unified_address clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_address clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9458)
;
9459}
9460
9461template <typename Derived>
9462OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9463 OMPUnifiedSharedMemoryClause *C) {
9464 llvm_unreachable(::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9465)
9465 "unified_shared_memory clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9465)
;
9466}
9467
9468template <typename Derived>
9469OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9470 OMPReverseOffloadClause *C) {
9471 llvm_unreachable("reverse_offload clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("reverse_offload clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9471)
;
9472}
9473
9474template <typename Derived>
9475OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9476 OMPDynamicAllocatorsClause *C) {
9477 llvm_unreachable(::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9478)
9478 "dynamic_allocators clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9478)
;
9479}
9480
9481template <typename Derived>
9482OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9483 OMPAtomicDefaultMemOrderClause *C) {
9484 llvm_unreachable(::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9485)
9485 "atomic_default_mem_order clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 9485)
;
9486}
9487
9488template <typename Derived>
9489OMPClause *
9490TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9491 llvm::SmallVector<Expr *, 16> Vars;
9492 Vars.reserve(C->varlist_size());
9493 for (auto *VE : C->varlists()) {
9494 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9495 if (EVar.isInvalid())
9496 return nullptr;
9497 Vars.push_back(EVar.get());
9498 }
9499 return getDerived().RebuildOMPPrivateClause(
9500 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9501}
9502
9503template <typename Derived>
9504OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9505 OMPFirstprivateClause *C) {
9506 llvm::SmallVector<Expr *, 16> Vars;
9507 Vars.reserve(C->varlist_size());
9508 for (auto *VE : C->varlists()) {
9509 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9510 if (EVar.isInvalid())
9511 return nullptr;
9512 Vars.push_back(EVar.get());
9513 }
9514 return getDerived().RebuildOMPFirstprivateClause(
9515 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9516}
9517
9518template <typename Derived>
9519OMPClause *
9520TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9521 llvm::SmallVector<Expr *, 16> Vars;
9522 Vars.reserve(C->varlist_size());
9523 for (auto *VE : C->varlists()) {
9524 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9525 if (EVar.isInvalid())
9526 return nullptr;
9527 Vars.push_back(EVar.get());
9528 }
9529 return getDerived().RebuildOMPLastprivateClause(
9530 Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9531 C->getLParenLoc(), C->getEndLoc());
9532}
9533
9534template <typename Derived>
9535OMPClause *
9536TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9537 llvm::SmallVector<Expr *, 16> Vars;
9538 Vars.reserve(C->varlist_size());
9539 for (auto *VE : C->varlists()) {
9540 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9541 if (EVar.isInvalid())
9542 return nullptr;
9543 Vars.push_back(EVar.get());
9544 }
9545 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9546 C->getLParenLoc(), C->getEndLoc());
9547}
9548
9549template <typename Derived>
9550OMPClause *
9551TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9552 llvm::SmallVector<Expr *, 16> Vars;
9553 Vars.reserve(C->varlist_size());
9554 for (auto *VE : C->varlists()) {
9555 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9556 if (EVar.isInvalid())
9557 return nullptr;
9558 Vars.push_back(EVar.get());
9559 }
9560 CXXScopeSpec ReductionIdScopeSpec;
9561 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9562
9563 DeclarationNameInfo NameInfo = C->getNameInfo();
9564 if (NameInfo.getName()) {
9565 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9566 if (!NameInfo.getName())
9567 return nullptr;
9568 }
9569 // Build a list of all UDR decls with the same names ranged by the Scopes.
9570 // The Scope boundary is a duplication of the previous decl.
9571 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9572 for (auto *E : C->reduction_ops()) {
9573 // Transform all the decls.
9574 if (E) {
9575 auto *ULE = cast<UnresolvedLookupExpr>(E);
9576 UnresolvedSet<8> Decls;
9577 for (auto *D : ULE->decls()) {
9578 NamedDecl *InstD =
9579 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9580 Decls.addDecl(InstD, InstD->getAccess());
9581 }
9582 UnresolvedReductions.push_back(
9583 UnresolvedLookupExpr::Create(
9584 SemaRef.Context, /*NamingClass=*/nullptr,
9585 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
9586 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
9587 Decls.begin(), Decls.end()));
9588 } else
9589 UnresolvedReductions.push_back(nullptr);
9590 }
9591 return getDerived().RebuildOMPReductionClause(
9592 Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
9593 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
9594 ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9595}
9596
9597template <typename Derived>
9598OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
9599 OMPTaskReductionClause *C) {
9600 llvm::SmallVector<Expr *, 16> Vars;
9601 Vars.reserve(C->varlist_size());
9602 for (auto *VE : C->varlists()) {
9603 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9604 if (EVar.isInvalid())
9605 return nullptr;
9606 Vars.push_back(EVar.get());
9607 }
9608 CXXScopeSpec ReductionIdScopeSpec;
9609 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9610
9611 DeclarationNameInfo NameInfo = C->getNameInfo();
9612 if (NameInfo.getName()) {
9613 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9614 if (!NameInfo.getName())
9615 return nullptr;
9616 }
9617 // Build a list of all UDR decls with the same names ranged by the Scopes.
9618 // The Scope boundary is a duplication of the previous decl.
9619 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9620 for (auto *E : C->reduction_ops()) {
9621 // Transform all the decls.
9622 if (E) {
9623 auto *ULE = cast<UnresolvedLookupExpr>(E);
9624 UnresolvedSet<8> Decls;
9625 for (auto *D : ULE->decls()) {
9626 NamedDecl *InstD =
9627 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9628 Decls.addDecl(InstD, InstD->getAccess());
9629 }
9630 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9631 SemaRef.Context, /*NamingClass=*/nullptr,
9632 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9633 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9634 } else
9635 UnresolvedReductions.push_back(nullptr);
9636 }
9637 return getDerived().RebuildOMPTaskReductionClause(
9638 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9639 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9640}
9641
9642template <typename Derived>
9643OMPClause *
9644TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
9645 llvm::SmallVector<Expr *, 16> Vars;
9646 Vars.reserve(C->varlist_size());
9647 for (auto *VE : C->varlists()) {
9648 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9649 if (EVar.isInvalid())
9650 return nullptr;
9651 Vars.push_back(EVar.get());
9652 }
9653 CXXScopeSpec ReductionIdScopeSpec;
9654 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9655
9656 DeclarationNameInfo NameInfo = C->getNameInfo();
9657 if (NameInfo.getName()) {
9658 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9659 if (!NameInfo.getName())
9660 return nullptr;
9661 }
9662 // Build a list of all UDR decls with the same names ranged by the Scopes.
9663 // The Scope boundary is a duplication of the previous decl.
9664 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9665 for (auto *E : C->reduction_ops()) {
9666 // Transform all the decls.
9667 if (E) {
9668 auto *ULE = cast<UnresolvedLookupExpr>(E);
9669 UnresolvedSet<8> Decls;
9670 for (auto *D : ULE->decls()) {
9671 NamedDecl *InstD =
9672 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9673 Decls.addDecl(InstD, InstD->getAccess());
9674 }
9675 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9676 SemaRef.Context, /*NamingClass=*/nullptr,
9677 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9678 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9679 } else
9680 UnresolvedReductions.push_back(nullptr);
9681 }
9682 return getDerived().RebuildOMPInReductionClause(
9683 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9684 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9685}
9686
9687template <typename Derived>
9688OMPClause *
9689TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9690 llvm::SmallVector<Expr *, 16> Vars;
9691 Vars.reserve(C->varlist_size());
9692 for (auto *VE : C->varlists()) {
9693 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9694 if (EVar.isInvalid())
9695 return nullptr;
9696 Vars.push_back(EVar.get());
9697 }
9698 ExprResult Step = getDerived().TransformExpr(C->getStep());
9699 if (Step.isInvalid())
9700 return nullptr;
9701 return getDerived().RebuildOMPLinearClause(
9702 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
9703 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
9704}
9705
9706template <typename Derived>
9707OMPClause *
9708TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
9709 llvm::SmallVector<Expr *, 16> Vars;
9710 Vars.reserve(C->varlist_size());
9711 for (auto *VE : C->varlists()) {
9712 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9713 if (EVar.isInvalid())
9714 return nullptr;
9715 Vars.push_back(EVar.get());
9716 }
9717 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
9718 if (Alignment.isInvalid())
9719 return nullptr;
9720 return getDerived().RebuildOMPAlignedClause(
9721 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
9722 C->getColonLoc(), C->getEndLoc());
9723}
9724
9725template <typename Derived>
9726OMPClause *
9727TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
9728 llvm::SmallVector<Expr *, 16> Vars;
9729 Vars.reserve(C->varlist_size());
9730 for (auto *VE : C->varlists()) {
9731 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9732 if (EVar.isInvalid())
9733 return nullptr;
9734 Vars.push_back(EVar.get());
9735 }
9736 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
9737 C->getLParenLoc(), C->getEndLoc());
9738}
9739
9740template <typename Derived>
9741OMPClause *
9742TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9743 llvm::SmallVector<Expr *, 16> Vars;
9744 Vars.reserve(C->varlist_size());
9745 for (auto *VE : C->varlists()) {
9746 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9747 if (EVar.isInvalid())
9748 return nullptr;
9749 Vars.push_back(EVar.get());
9750 }
9751 return getDerived().RebuildOMPCopyprivateClause(
9752 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9753}
9754
9755template <typename Derived>
9756OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9757 llvm::SmallVector<Expr *, 16> Vars;
9758 Vars.reserve(C->varlist_size());
9759 for (auto *VE : C->varlists()) {
9760 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9761 if (EVar.isInvalid())
9762 return nullptr;
9763 Vars.push_back(EVar.get());
9764 }
9765 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9766 C->getLParenLoc(), C->getEndLoc());
9767}
9768
9769template <typename Derived>
9770OMPClause *
9771TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
9772 ExprResult E = getDerived().TransformExpr(C->getDepobj());
9773 if (E.isInvalid())
9774 return nullptr;
9775 return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
9776 C->getLParenLoc(), C->getEndLoc());
9777}
9778
9779template <typename Derived>
9780OMPClause *
9781TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9782 llvm::SmallVector<Expr *, 16> Vars;
9783 Expr *DepModifier = C->getModifier();
9784 if (DepModifier) {
9785 ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
9786 if (DepModRes.isInvalid())
9787 return nullptr;
9788 DepModifier = DepModRes.get();
9789 }
9790 Vars.reserve(C->varlist_size());
9791 for (auto *VE : C->varlists()) {
9792 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9793 if (EVar.isInvalid())
9794 return nullptr;
9795 Vars.push_back(EVar.get());
9796 }
9797 return getDerived().RebuildOMPDependClause(
9798 DepModifier, C->getDependencyKind(), C->getDependencyLoc(),
9799 C->getColonLoc(), Vars, C->getBeginLoc(), C->getLParenLoc(),
9800 C->getEndLoc());
9801}
9802
9803template <typename Derived>
9804OMPClause *
9805TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9806 ExprResult E = getDerived().TransformExpr(C->getDevice());
9807 if (E.isInvalid())
9808 return nullptr;
9809 return getDerived().RebuildOMPDeviceClause(
9810 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9811 C->getModifierLoc(), C->getEndLoc());
9812}
9813
9814template <typename Derived, class T>
9815bool transformOMPMappableExprListClause(
9816 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9817 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9818 DeclarationNameInfo &MapperIdInfo,
9819 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9820 // Transform expressions in the list.
9821 Vars.reserve(C->varlist_size());
9822 for (auto *VE : C->varlists()) {
9823 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9824 if (EVar.isInvalid())
9825 return true;
9826 Vars.push_back(EVar.get());
9827 }
9828 // Transform mapper scope specifier and identifier.
9829 NestedNameSpecifierLoc QualifierLoc;
9830 if (C->getMapperQualifierLoc()) {
9831 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9832 C->getMapperQualifierLoc());
9833 if (!QualifierLoc)
9834 return true;
9835 }
9836 MapperIdScopeSpec.Adopt(QualifierLoc);
9837 MapperIdInfo = C->getMapperIdInfo();
9838 if (MapperIdInfo.getName()) {
9839 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9840 if (!MapperIdInfo.getName())
9841 return true;
9842 }
9843 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9844 // the previous user-defined mapper lookup in dependent environment.
9845 for (auto *E : C->mapperlists()) {
9846 // Transform all the decls.
9847 if (E) {
9848 auto *ULE = cast<UnresolvedLookupExpr>(E);
9849 UnresolvedSet<8> Decls;
9850 for (auto *D : ULE->decls()) {
9851 NamedDecl *InstD =
9852 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9853 Decls.addDecl(InstD, InstD->getAccess());
9854 }
9855 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9856 TT.getSema().Context, /*NamingClass=*/nullptr,
9857 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9858 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9859 Decls.end()));
9860 } else {
9861 UnresolvedMappers.push_back(nullptr);
9862 }
9863 }
9864 return false;
9865}
9866
9867template <typename Derived>
9868OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9869 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9870 llvm::SmallVector<Expr *, 16> Vars;
9871 CXXScopeSpec MapperIdScopeSpec;
9872 DeclarationNameInfo MapperIdInfo;
9873 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9874 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9875 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9876 return nullptr;
9877 return getDerived().RebuildOMPMapClause(
9878 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9879 MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9880 C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9881}
9882
9883template <typename Derived>
9884OMPClause *
9885TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9886 Expr *Allocator = C->getAllocator();
9887 if (Allocator) {
9888 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9889 if (AllocatorRes.isInvalid())
9890 return nullptr;
9891 Allocator = AllocatorRes.get();
9892 }
9893 llvm::SmallVector<Expr *, 16> Vars;
9894 Vars.reserve(C->varlist_size());
9895 for (auto *VE : C->varlists()) {
9896 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9897 if (EVar.isInvalid())
9898 return nullptr;
9899 Vars.push_back(EVar.get());
9900 }
9901 return getDerived().RebuildOMPAllocateClause(
9902 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9903 C->getEndLoc());
9904}
9905
9906template <typename Derived>
9907OMPClause *
9908TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9909 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9910 if (E.isInvalid())
9911 return nullptr;
9912 return getDerived().RebuildOMPNumTeamsClause(
9913 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9914}
9915
9916template <typename Derived>
9917OMPClause *
9918TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9919 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9920 if (E.isInvalid())
9921 return nullptr;
9922 return getDerived().RebuildOMPThreadLimitClause(
9923 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9924}
9925
9926template <typename Derived>
9927OMPClause *
9928TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9929 ExprResult E = getDerived().TransformExpr(C->getPriority());
9930 if (E.isInvalid())
9931 return nullptr;
9932 return getDerived().RebuildOMPPriorityClause(
9933 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9934}
9935
9936template <typename Derived>
9937OMPClause *
9938TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9939 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9940 if (E.isInvalid())
9941 return nullptr;
9942 return getDerived().RebuildOMPGrainsizeClause(
9943 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9944}
9945
9946template <typename Derived>
9947OMPClause *
9948TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9949 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9950 if (E.isInvalid())
9951 return nullptr;
9952 return getDerived().RebuildOMPNumTasksClause(
9953 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9954}
9955
9956template <typename Derived>
9957OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9958 ExprResult E = getDerived().TransformExpr(C->getHint());
9959 if (E.isInvalid())
9960 return nullptr;
9961 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9962 C->getLParenLoc(), C->getEndLoc());
9963}
9964
9965template <typename Derived>
9966OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9967 OMPDistScheduleClause *C) {
9968 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9969 if (E.isInvalid())
9970 return nullptr;
9971 return getDerived().RebuildOMPDistScheduleClause(
9972 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9973 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9974}
9975
9976template <typename Derived>
9977OMPClause *
9978TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9979 // Rebuild Defaultmap Clause since we need to invoke the checking of
9980 // defaultmap(none:variable-category) after template initialization.
9981 return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
9982 C->getDefaultmapKind(),
9983 C->getBeginLoc(),
9984 C->getLParenLoc(),
9985 C->getDefaultmapModifierLoc(),
9986 C->getDefaultmapKindLoc(),
9987 C->getEndLoc());
9988}
9989
9990template <typename Derived>
9991OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9992 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9993 llvm::SmallVector<Expr *, 16> Vars;
9994 CXXScopeSpec MapperIdScopeSpec;
9995 DeclarationNameInfo MapperIdInfo;
9996 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9997 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9998 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9999 return nullptr;
10000 return getDerived().RebuildOMPToClause(
10001 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10002 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10003}
10004
10005template <typename Derived>
10006OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10007 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10008 llvm::SmallVector<Expr *, 16> Vars;
10009 CXXScopeSpec MapperIdScopeSpec;
10010 DeclarationNameInfo MapperIdInfo;
10011 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10012 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10013 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10014 return nullptr;
10015 return getDerived().RebuildOMPFromClause(
10016 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10017 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10018}
10019
10020template <typename Derived>
10021OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10022 OMPUseDevicePtrClause *C) {
10023 llvm::SmallVector<Expr *, 16> Vars;
10024 Vars.reserve(C->varlist_size());
10025 for (auto *VE : C->varlists()) {
10026 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10027 if (EVar.isInvalid())
10028 return nullptr;
10029 Vars.push_back(EVar.get());
10030 }
10031 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10032 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10033}
10034
10035template <typename Derived>
10036OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10037 OMPUseDeviceAddrClause *C) {
10038 llvm::SmallVector<Expr *, 16> Vars;
10039 Vars.reserve(C->varlist_size());
10040 for (auto *VE : C->varlists()) {
10041 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10042 if (EVar.isInvalid())
10043 return nullptr;
10044 Vars.push_back(EVar.get());
10045 }
10046 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10047 return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10048}
10049
10050template <typename Derived>
10051OMPClause *
10052TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10053 llvm::SmallVector<Expr *, 16> Vars;
10054 Vars.reserve(C->varlist_size());
10055 for (auto *VE : C->varlists()) {
10056 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10057 if (EVar.isInvalid())
10058 return nullptr;
10059 Vars.push_back(EVar.get());
10060 }
10061 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10062 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10063}
10064
10065template <typename Derived>
10066OMPClause *
10067TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10068 llvm::SmallVector<Expr *, 16> Vars;
10069 Vars.reserve(C->varlist_size());
10070 for (auto *VE : C->varlists()) {
10071 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10072 if (EVar.isInvalid())
10073 return nullptr;
10074 Vars.push_back(EVar.get());
10075 }
10076 return getDerived().RebuildOMPNontemporalClause(
10077 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10078}
10079
10080template <typename Derived>
10081OMPClause *
10082TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10083 llvm::SmallVector<Expr *, 16> Vars;
10084 Vars.reserve(C->varlist_size());
10085 for (auto *VE : C->varlists()) {
10086 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10087 if (EVar.isInvalid())
10088 return nullptr;
10089 Vars.push_back(EVar.get());
10090 }
10091 return getDerived().RebuildOMPInclusiveClause(
10092 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10093}
10094
10095template <typename Derived>
10096OMPClause *
10097TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10098 llvm::SmallVector<Expr *, 16> Vars;
10099 Vars.reserve(C->varlist_size());
10100 for (auto *VE : C->varlists()) {
10101 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10102 if (EVar.isInvalid())
10103 return nullptr;
10104 Vars.push_back(EVar.get());
10105 }
10106 return getDerived().RebuildOMPExclusiveClause(
10107 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10108}
10109
10110template <typename Derived>
10111OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10112 OMPUsesAllocatorsClause *C) {
10113 SmallVector<Sema::UsesAllocatorsData, 16> Data;
10114 Data.reserve(C->getNumberOfAllocators());
10115 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10116 OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10117 ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10118 if (Allocator.isInvalid())
10119 continue;
10120 ExprResult AllocatorTraits;
10121 if (Expr *AT = D.AllocatorTraits) {
10122 AllocatorTraits = getDerived().TransformExpr(AT);
10123 if (AllocatorTraits.isInvalid())
10124 continue;
10125 }
10126 Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10127 NewD.Allocator = Allocator.get();
10128 NewD.AllocatorTraits = AllocatorTraits.get();
10129 NewD.LParenLoc = D.LParenLoc;
10130 NewD.RParenLoc = D.RParenLoc;
10131 }
10132 return getDerived().RebuildOMPUsesAllocatorsClause(
10133 Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10134}
10135
10136template <typename Derived>
10137OMPClause *
10138TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10139 SmallVector<Expr *, 4> Locators;
10140 Locators.reserve(C->varlist_size());
10141 ExprResult ModifierRes;
10142 if (Expr *Modifier = C->getModifier()) {
10143 ModifierRes = getDerived().TransformExpr(Modifier);
10144 if (ModifierRes.isInvalid())
10145 return nullptr;
10146 }
10147 for (Expr *E : C->varlists()) {
10148 ExprResult Locator = getDerived().TransformExpr(E);
10149 if (Locator.isInvalid())
10150 continue;
10151 Locators.push_back(Locator.get());
10152 }
10153 return getDerived().RebuildOMPAffinityClause(
10154 C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10155 ModifierRes.get(), Locators);
10156}
10157
10158template <typename Derived>
10159OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10160 return getDerived().RebuildOMPOrderClause(C->getKind(), C->getKindKwLoc(),
10161 C->getBeginLoc(), C->getLParenLoc(),
10162 C->getEndLoc());
10163}
10164
10165//===----------------------------------------------------------------------===//
10166// Expression transformation
10167//===----------------------------------------------------------------------===//
10168template<typename Derived>
10169ExprResult
10170TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10171 return TransformExpr(E->getSubExpr());
10172}
10173
10174template<typename Derived>
10175ExprResult
10176TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10177 if (!E->isTypeDependent())
10178 return E;
10179
10180 return getDerived().RebuildPredefinedExpr(E->getLocation(),
10181 E->getIdentKind());
10182}
10183
10184template<typename Derived>
10185ExprResult
10186TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10187 NestedNameSpecifierLoc QualifierLoc;
10188 if (E->getQualifierLoc()) {
10189 QualifierLoc
10190 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10191 if (!QualifierLoc)
10192 return ExprError();
10193 }
10194
10195 ValueDecl *ND
10196 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10197 E->getDecl()));
10198 if (!ND)
10199 return ExprError();
10200
10201 NamedDecl *Found = ND;
10202 if (E->getFoundDecl() != E->getDecl()) {
10203 Found = cast_or_null<NamedDecl>(
10204 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10205 if (!Found)
10206 return ExprError();
10207 }
10208
10209 DeclarationNameInfo NameInfo = E->getNameInfo();
10210 if (NameInfo.getName()) {
10211 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10212 if (!NameInfo.getName())
10213 return ExprError();
10214 }
10215
10216 if (!getDerived().AlwaysRebuild() &&
10217 QualifierLoc == E->getQualifierLoc() &&
10218 ND == E->getDecl() &&
10219 Found == E->getFoundDecl() &&
10220 NameInfo.getName() == E->getDecl()->getDeclName() &&
10221 !E->hasExplicitTemplateArgs()) {
10222
10223 // Mark it referenced in the new context regardless.
10224 // FIXME: this is a bit instantiation-specific.
10225 SemaRef.MarkDeclRefReferenced(E);
10226
10227 return E;
10228 }
10229
10230 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10231 if (E->hasExplicitTemplateArgs()) {
10232 TemplateArgs = &TransArgs;
10233 TransArgs.setLAngleLoc(E->getLAngleLoc());
10234 TransArgs.setRAngleLoc(E->getRAngleLoc());
10235 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10236 E->getNumTemplateArgs(),
10237 TransArgs))
10238 return ExprError();
10239 }
10240
10241 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10242 Found, TemplateArgs);
10243}
10244
10245template<typename Derived>
10246ExprResult
10247TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10248 return E;
10249}
10250
10251template <typename Derived>
10252ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10253 FixedPointLiteral *E) {
10254 return E;
10255}
10256
10257template<typename Derived>
10258ExprResult
10259TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10260 return E;
10261}
10262
10263template<typename Derived>
10264ExprResult
10265TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10266 return E;
10267}
10268
10269template<typename Derived>
10270ExprResult
10271TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10272 return E;
10273}
10274
10275template<typename Derived>
10276ExprResult
10277TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10278 return E;
10279}
10280
10281template<typename Derived>
10282ExprResult
10283TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10284 if (FunctionDecl *FD = E->getDirectCallee())
10285 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
10286 return SemaRef.MaybeBindToTemporary(E);
10287}
10288
10289template<typename Derived>
10290ExprResult
10291TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10292 ExprResult ControllingExpr =
10293 getDerived().TransformExpr(E->getControllingExpr());
10294 if (ControllingExpr.isInvalid())
10295 return ExprError();
10296
10297 SmallVector<Expr *, 4> AssocExprs;
10298 SmallVector<TypeSourceInfo *, 4> AssocTypes;
10299 for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10300 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10301 if (TSI) {
10302 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10303 if (!AssocType)
10304 return ExprError();
10305 AssocTypes.push_back(AssocType);
10306 } else {
10307 AssocTypes.push_back(nullptr);
10308 }
10309
10310 ExprResult AssocExpr =
10311 getDerived().TransformExpr(Assoc.getAssociationExpr());
10312 if (AssocExpr.isInvalid())
10313 return ExprError();
10314 AssocExprs.push_back(AssocExpr.get());
10315 }
10316
10317 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10318 E->getDefaultLoc(),
10319 E->getRParenLoc(),
10320 ControllingExpr.get(),
10321 AssocTypes,
10322 AssocExprs);
10323}
10324
10325template<typename Derived>
10326ExprResult
10327TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10328 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10329 if (SubExpr.isInvalid())
10330 return ExprError();
10331
10332 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10333 return E;
10334
10335 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10336 E->getRParen());
10337}
10338
10339/// The operand of a unary address-of operator has special rules: it's
10340/// allowed to refer to a non-static member of a class even if there's no 'this'
10341/// object available.
10342template<typename Derived>
10343ExprResult
10344TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10345 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10346 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10347 else
10348 return getDerived().TransformExpr(E);
10349}
10350
10351template<typename Derived>
10352ExprResult
10353TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10354 ExprResult SubExpr;
10355 if (E->getOpcode() == UO_AddrOf)
10356 SubExpr = TransformAddressOfOperand(E->getSubExpr());
10357 else
10358 SubExpr = TransformExpr(E->getSubExpr());
10359 if (SubExpr.isInvalid())
10360 return ExprError();
10361
10362 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10363 return E;
10364
10365 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10366 E->getOpcode(),
10367 SubExpr.get());
10368}
10369
10370template<typename Derived>
10371ExprResult
10372TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10373 // Transform the type.
10374 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10375 if (!Type)
10376 return ExprError();
10377
10378 // Transform all of the components into components similar to what the
10379 // parser uses.
10380 // FIXME: It would be slightly more efficient in the non-dependent case to
10381 // just map FieldDecls, rather than requiring the rebuilder to look for
10382 // the fields again. However, __builtin_offsetof is rare enough in
10383 // template code that we don't care.
10384 bool ExprChanged = false;
10385 typedef Sema::OffsetOfComponent Component;
10386 SmallVector<Component, 4> Components;
10387 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10388 const OffsetOfNode &ON = E->getComponent(I);
10389 Component Comp;
10390 Comp.isBrackets = true;
10391 Comp.LocStart = ON.getSourceRange().getBegin();
10392 Comp.LocEnd = ON.getSourceRange().getEnd();
10393 switch (ON.getKind()) {
10394 case OffsetOfNode::Array: {
10395 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10396 ExprResult Index = getDerived().TransformExpr(FromIndex);
10397 if (Index.isInvalid())
10398 return ExprError();
10399
10400 ExprChanged = ExprChanged || Index.get() != FromIndex;
10401 Comp.isBrackets = true;
10402 Comp.U.E = Index.get();
10403 break;
10404 }
10405
10406 case OffsetOfNode::Field:
10407 case OffsetOfNode::Identifier:
10408 Comp.isBrackets = false;
10409 Comp.U.IdentInfo = ON.getFieldName();
10410 if (!Comp.U.IdentInfo)
10411 continue;
10412
10413 break;
10414
10415 case OffsetOfNode::Base:
10416 // Will be recomputed during the rebuild.
10417 continue;
10418 }
10419
10420 Components.push_back(Comp);
10421 }
10422
10423 // If nothing changed, retain the existing expression.
10424 if (!getDerived().AlwaysRebuild() &&
10425 Type == E->getTypeSourceInfo() &&
10426 !ExprChanged)
10427 return E;
10428
10429 // Build a new offsetof expression.
10430 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10431 Components, E->getRParenLoc());
10432}
10433
10434template<typename Derived>
10435ExprResult
10436TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10437 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&(((!E->getSourceExpr() || getDerived().AlreadyTransformed(
E->getType())) && "opaque value expression requires transformation"
) ? static_cast<void> (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 10438, __PRETTY_FUNCTION__))
10438 "opaque value expression requires transformation")(((!E->getSourceExpr() || getDerived().AlreadyTransformed(
E->getType())) && "opaque value expression requires transformation"
) ? static_cast<void> (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 10438, __PRETTY_FUNCTION__))
;
10439 return E;
10440}
10441
10442template<typename Derived>
10443ExprResult
10444TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10445 return E;
10446}
10447
10448template <typename Derived>
10449ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10450 llvm::SmallVector<Expr *, 8> Children;
10451 bool Changed = false;
10452 for (Expr *C : E->subExpressions()) {
10453 ExprResult NewC = getDerived().TransformExpr(C);
10454 if (NewC.isInvalid())
10455 return ExprError();
10456 Children.push_back(NewC.get());
10457
10458 Changed |= NewC.get() != C;
10459 }
10460 if (!getDerived().AlwaysRebuild() && !Changed)
10461 return E;
10462 return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10463 Children, E->getType());
10464}
10465
10466template<typename Derived>
10467ExprResult
10468TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10469 // Rebuild the syntactic form. The original syntactic form has
10470 // opaque-value expressions in it, so strip those away and rebuild
10471 // the result. This is a really awful way of doing this, but the
10472 // better solution (rebuilding the semantic expressions and
10473 // rebinding OVEs as necessary) doesn't work; we'd need
10474 // TreeTransform to not strip away implicit conversions.
10475 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10476 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10477 if (result.isInvalid()) return ExprError();
10478
10479 // If that gives us a pseudo-object result back, the pseudo-object
10480 // expression must have been an lvalue-to-rvalue conversion which we
10481 // should reapply.
10482 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10483 result = SemaRef.checkPseudoObjectRValue(result.get());
10484
10485 return result;
10486}
10487
10488template<typename Derived>
10489ExprResult
10490TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10491 UnaryExprOrTypeTraitExpr *E) {
10492 if (E->isArgumentType()) {
10493 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10494
10495 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10496 if (!NewT)
10497 return ExprError();
10498
10499 if (!getDerived().AlwaysRebuild() && OldT == NewT)
10500 return E;
10501
10502 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
10503 E->getKind(),
10504 E->getSourceRange());
10505 }
10506
10507 // C++0x [expr.sizeof]p1:
10508 // The operand is either an expression, which is an unevaluated operand
10509 // [...]
10510 EnterExpressionEvaluationContext Unevaluated(
10511 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10512 Sema::ReuseLambdaContextDecl);
10513
10514 // Try to recover if we have something like sizeof(T::X) where X is a type.
10515 // Notably, there must be *exactly* one set of parens if X is a type.
10516 TypeSourceInfo *RecoveryTSI = nullptr;
10517 ExprResult SubExpr;
10518 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
10519 if (auto *DRE =
10520 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
10521 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
10522 PE, DRE, false, &RecoveryTSI);
10523 else
10524 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
10525
10526 if (RecoveryTSI) {
10527 return getDerived().RebuildUnaryExprOrTypeTrait(
10528 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
10529 } else if (SubExpr.isInvalid())
10530 return ExprError();
10531
10532 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
10533 return E;
10534
10535 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
10536 E->getOperatorLoc(),
10537 E->getKind(),
10538 E->getSourceRange());
10539}
10540
10541template<typename Derived>
10542ExprResult
10543TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
10544 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10545 if (LHS.isInvalid())
10546 return ExprError();
10547
10548 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10549 if (RHS.isInvalid())
10550 return ExprError();
10551
10552
10553 if (!getDerived().AlwaysRebuild() &&
10554 LHS.get() == E->getLHS() &&
10555 RHS.get() == E->getRHS())
10556 return E;
10557
10558 return getDerived().RebuildArraySubscriptExpr(
10559 LHS.get(),
10560 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
10561}
10562
10563template <typename Derived>
10564ExprResult
10565TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
10566 ExprResult Base = getDerived().TransformExpr(E->getBase());
10567 if (Base.isInvalid())
10568 return ExprError();
10569
10570 ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
10571 if (RowIdx.isInvalid())
10572 return ExprError();
10573
10574 ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
10575 if (ColumnIdx.isInvalid())
10576 return ExprError();
10577
10578 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10579 RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
10580 return E;
10581
10582 return getDerived().RebuildMatrixSubscriptExpr(
10583 Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
10584}
10585
10586template <typename Derived>
10587ExprResult
10588TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
10589 ExprResult Base = getDerived().TransformExpr(E->getBase());
10590 if (Base.isInvalid())
10591 return ExprError();
10592
10593 ExprResult LowerBound;
10594 if (E->getLowerBound()) {
10595 LowerBound = getDerived().TransformExpr(E->getLowerBound());
10596 if (LowerBound.isInvalid())
10597 return ExprError();
10598 }
10599
10600 ExprResult Length;
10601 if (E->getLength()) {
10602 Length = getDerived().TransformExpr(E->getLength());
10603 if (Length.isInvalid())
10604 return ExprError();
10605 }
10606
10607 ExprResult Stride;
10608 if (Expr *Str = E->getStride()) {
10609 Stride = getDerived().TransformExpr(Str);
10610 if (Stride.isInvalid())
10611 return ExprError();
10612 }
10613
10614 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10615 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
10616 return E;
10617
10618 return getDerived().RebuildOMPArraySectionExpr(
10619 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
10620 E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
10621 E->getRBracketLoc());
10622}
10623
10624template <typename Derived>
10625ExprResult
10626TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
10627 ExprResult Base = getDerived().TransformExpr(E->getBase());
10628 if (Base.isInvalid())
10629 return ExprError();
10630
10631 SmallVector<Expr *, 4> Dims;
10632 bool ErrorFound = false;
10633 for (Expr *Dim : E->getDimensions()) {
10634 ExprResult DimRes = getDerived().TransformExpr(Dim);
10635 if (DimRes.isInvalid()) {
10636 ErrorFound = true;
10637 continue;
10638 }
10639 Dims.push_back(DimRes.get());
10640 }
10641
10642 if (ErrorFound)
10643 return ExprError();
10644 return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
10645 E->getRParenLoc(), Dims,
10646 E->getBracketsRanges());
10647}
10648
10649template <typename Derived>
10650ExprResult
10651TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
10652 unsigned NumIterators = E->numOfIterators();
10653 SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
10654
10655 bool ErrorFound = false;
10656 bool NeedToRebuild = getDerived().AlwaysRebuild();
10657 for (unsigned I = 0; I < NumIterators; ++I) {
10658 auto *D = cast<VarDecl>(E->getIteratorDecl(I));
10659 Data[I].DeclIdent = D->getIdentifier();
10660 Data[I].DeclIdentLoc = D->getLocation();
10661 if (D->getLocation() == D->getBeginLoc()) {
10662 assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&((SemaRef.Context.hasSameType(D->getType(), SemaRef.Context
.IntTy) && "Implicit type must be int.") ? static_cast
<void> (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 10663, __PRETTY_FUNCTION__))
10663 "Implicit type must be int.")((SemaRef.Context.hasSameType(D->getType(), SemaRef.Context
.IntTy) && "Implicit type must be int.") ? static_cast
<void> (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 10663, __PRETTY_FUNCTION__))
;
10664 } else {
10665 TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
10666 QualType DeclTy = getDerived().TransformType(D->getType());
10667 Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
10668 }
10669 OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
10670 ExprResult Begin = getDerived().TransformExpr(Range.Begin);
10671 ExprResult End = getDerived().TransformExpr(Range.End);
10672 ExprResult Step = getDerived().TransformExpr(Range.Step);
10673 ErrorFound = ErrorFound ||
10674 !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
10675 !Data[I].Type.get().isNull())) ||
10676 Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
10677 if (ErrorFound)
10678 continue;
10679 Data[I].Range.Begin = Begin.get();
10680 Data[I].Range.End = End.get();
10681 Data[I].Range.Step = Step.get();
10682 Data[I].AssignLoc = E->getAssignLoc(I);
10683 Data[I].ColonLoc = E->getColonLoc(I);
10684 Data[I].SecColonLoc = E->getSecondColonLoc(I);
10685 NeedToRebuild =
10686 NeedToRebuild ||
10687 (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
10688 D->getType().getTypePtrOrNull()) ||
10689 Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
10690 Range.Step != Data[I].Range.Step;
10691 }
10692 if (ErrorFound)
10693 return ExprError();
10694 if (!NeedToRebuild)
10695 return E;
10696
10697 ExprResult Res = getDerived().RebuildOMPIteratorExpr(
10698 E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
10699 if (!Res.isUsable())
10700 return Res;
10701 auto *IE = cast<OMPIteratorExpr>(Res.get());
10702 for (unsigned I = 0; I < NumIterators; ++I)
10703 getDerived().transformedLocalDecl(E->getIteratorDecl(I),
10704 IE->getIteratorDecl(I));
10705 return Res;
10706}
10707
10708template<typename Derived>
10709ExprResult
10710TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
10711 // Transform the callee.
10712 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10713 if (Callee.isInvalid())
10714 return ExprError();
10715
10716 // Transform arguments.
10717 bool ArgChanged = false;
10718 SmallVector<Expr*, 8> Args;
10719 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10720 &ArgChanged))
10721 return ExprError();
10722
10723 if (!getDerived().AlwaysRebuild() &&
10724 Callee.get() == E->getCallee() &&
10725 !ArgChanged)
10726 return SemaRef.MaybeBindToTemporary(E);
10727
10728 // FIXME: Wrong source location information for the '('.
10729 SourceLocation FakeLParenLoc
10730 = ((Expr *)Callee.get())->getSourceRange().getBegin();
10731
10732 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10733 if (E->hasStoredFPFeatures()) {
10734 FPOptionsOverride NewOverrides = E->getFPFeatures();
10735 getSema().CurFPFeatures =
10736 NewOverrides.applyOverrides(getSema().getLangOpts());
10737 getSema().FpPragmaStack.CurrentValue = NewOverrides;
10738 }
10739
10740 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10741 Args,
10742 E->getRParenLoc());
10743}
10744
10745template<typename Derived>
10746ExprResult
10747TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
10748 ExprResult Base = getDerived().TransformExpr(E->getBase());
10749 if (Base.isInvalid())
10750 return ExprError();
10751
10752 NestedNameSpecifierLoc QualifierLoc;
10753 if (E->hasQualifier()) {
10754 QualifierLoc
10755 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10756
10757 if (!QualifierLoc)
10758 return ExprError();
10759 }
10760 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10761
10762 ValueDecl *Member
10763 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
10764 E->getMemberDecl()));
10765 if (!Member)
10766 return ExprError();
10767
10768 NamedDecl *FoundDecl = E->getFoundDecl();
10769 if (FoundDecl == E->getMemberDecl()) {
10770 FoundDecl = Member;
10771 } else {
10772 FoundDecl = cast_or_null<NamedDecl>(
10773 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
10774 if (!FoundDecl)
10775 return ExprError();
10776 }
10777
10778 if (!getDerived().AlwaysRebuild() &&
10779 Base.get() == E->getBase() &&
10780 QualifierLoc == E->getQualifierLoc() &&
10781 Member == E->getMemberDecl() &&
10782 FoundDecl == E->getFoundDecl() &&
10783 !E->hasExplicitTemplateArgs()) {
10784
10785 // Mark it referenced in the new context regardless.
10786 // FIXME: this is a bit instantiation-specific.
10787 SemaRef.MarkMemberReferenced(E);
10788
10789 return E;
10790 }
10791
10792 TemplateArgumentListInfo TransArgs;
10793 if (E->hasExplicitTemplateArgs()) {
10794 TransArgs.setLAngleLoc(E->getLAngleLoc());
10795 TransArgs.setRAngleLoc(E->getRAngleLoc());
10796 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10797 E->getNumTemplateArgs(),
10798 TransArgs))
10799 return ExprError();
10800 }
10801
10802 // FIXME: Bogus source location for the operator
10803 SourceLocation FakeOperatorLoc =
10804 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
10805
10806 // FIXME: to do this check properly, we will need to preserve the
10807 // first-qualifier-in-scope here, just in case we had a dependent
10808 // base (and therefore couldn't do the check) and a
10809 // nested-name-qualifier (and therefore could do the lookup).
10810 NamedDecl *FirstQualifierInScope = nullptr;
10811 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
10812 if (MemberNameInfo.getName()) {
10813 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
10814 if (!MemberNameInfo.getName())
10815 return ExprError();
10816 }
10817
10818 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
10819 E->isArrow(),
10820 QualifierLoc,
10821 TemplateKWLoc,
10822 MemberNameInfo,
10823 Member,
10824 FoundDecl,
10825 (E->hasExplicitTemplateArgs()
10826 ? &TransArgs : nullptr),
10827 FirstQualifierInScope);
10828}
10829
10830template<typename Derived>
10831ExprResult
10832TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
10833 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10834 if (LHS.isInvalid())
10835 return ExprError();
10836
10837 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10838 if (RHS.isInvalid())
10839 return ExprError();
10840
10841 if (!getDerived().AlwaysRebuild() &&
10842 LHS.get() == E->getLHS() &&
10843 RHS.get() == E->getRHS())
10844 return E;
10845
10846 if (E->isCompoundAssignmentOp())
10847 // FPFeatures has already been established from trailing storage
10848 return getDerived().RebuildBinaryOperator(
10849 E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
10850 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10851 FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
10852 getSema().CurFPFeatures =
10853 NewOverrides.applyOverrides(getSema().getLangOpts());
10854 getSema().FpPragmaStack.CurrentValue = NewOverrides;
10855 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
10856 LHS.get(), RHS.get());
10857}
10858
10859template <typename Derived>
10860ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
10861 CXXRewrittenBinaryOperator *E) {
10862 CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
10863
10864 ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
10865 if (LHS.isInvalid())
10866 return ExprError();
10867
10868 ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
10869 if (RHS.isInvalid())
10870 return ExprError();
10871
10872 if (!getDerived().AlwaysRebuild() &&
10873 LHS.get() == Decomp.LHS &&
10874 RHS.get() == Decomp.RHS)
10875 return E;
10876
10877 // Extract the already-resolved callee declarations so that we can restrict
10878 // ourselves to using them as the unqualified lookup results when rebuilding.
10879 UnresolvedSet<2> UnqualLookups;
10880 Expr *PossibleBinOps[] = {E->getSemanticForm(),
10881 const_cast<Expr *>(Decomp.InnerBinOp)};
10882 for (Expr *PossibleBinOp : PossibleBinOps) {
10883 auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
10884 if (!Op)
10885 continue;
10886 auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
10887 if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
10888 continue;
10889
10890 // Transform the callee in case we built a call to a local extern
10891 // declaration.
10892 NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
10893 E->getOperatorLoc(), Callee->getFoundDecl()));
10894 if (!Found)
10895 return ExprError();
10896 UnqualLookups.addDecl(Found);
10897 }
10898
10899 return getDerived().RebuildCXXRewrittenBinaryOperator(
10900 E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
10901}
10902
10903template<typename Derived>
10904ExprResult
10905TreeTransform<Derived>::TransformCompoundAssignOperator(
10906 CompoundAssignOperator *E) {
10907 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
10908 FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
10909 getSema().CurFPFeatures =
10910 NewOverrides.applyOverrides(getSema().getLangOpts());
10911 getSema().FpPragmaStack.CurrentValue = NewOverrides;
10912 return getDerived().TransformBinaryOperator(E);
10913}
10914
10915template<typename Derived>
10916ExprResult TreeTransform<Derived>::
10917TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
10918 // Just rebuild the common and RHS expressions and see whether we
10919 // get any changes.
10920
10921 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
10922 if (commonExpr.isInvalid())
10923 return ExprError();
10924
10925 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
10926 if (rhs.isInvalid())
10927 return ExprError();
10928
10929 if (!getDerived().AlwaysRebuild() &&
10930 commonExpr.get() == e->getCommon() &&
10931 rhs.get() == e->getFalseExpr())
10932 return e;
10933
10934 return getDerived().RebuildConditionalOperator(commonExpr.get(),
10935 e->getQuestionLoc(),
10936 nullptr,
10937 e->getColonLoc(),
10938 rhs.get());
10939}
10940
10941template<typename Derived>
10942ExprResult
10943TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
10944 ExprResult Cond = getDerived().TransformExpr(E->getCond());
10945 if (Cond.isInvalid())
10946 return ExprError();
10947
10948 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10949 if (LHS.isInvalid())
10950 return ExprError();
10951
10952 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10953 if (RHS.isInvalid())
10954 return ExprError();
10955
10956 if (!getDerived().AlwaysRebuild() &&
10957 Cond.get() == E->getCond() &&
10958 LHS.get() == E->getLHS() &&
10959 RHS.get() == E->getRHS())
10960 return E;
10961
10962 return getDerived().RebuildConditionalOperator(Cond.get(),
10963 E->getQuestionLoc(),
10964 LHS.get(),
10965 E->getColonLoc(),
10966 RHS.get());
10967}
10968
10969template<typename Derived>
10970ExprResult
10971TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
10972 // Implicit casts are eliminated during transformation, since they
10973 // will be recomputed by semantic analysis after transformation.
10974 return getDerived().TransformExpr(E->getSubExprAsWritten());
10975}
10976
10977template<typename Derived>
10978ExprResult
10979TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
10980 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10981 if (!Type)
10982 return ExprError();
10983
10984 ExprResult SubExpr
10985 = getDerived().TransformExpr(E->getSubExprAsWritten());
10986 if (SubExpr.isInvalid())
10987 return ExprError();
10988
10989 if (!getDerived().AlwaysRebuild() &&
10990 Type == E->getTypeInfoAsWritten() &&
10991 SubExpr.get() == E->getSubExpr())
10992 return E;
10993
10994 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
10995 Type,
10996 E->getRParenLoc(),
10997 SubExpr.get());
10998}
10999
11000template<typename Derived>
11001ExprResult
11002TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11003 TypeSourceInfo *OldT = E->getTypeSourceInfo();
11004 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11005 if (!NewT)
11006 return ExprError();
11007
11008 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11009 if (Init.isInvalid())
11010 return ExprError();
11011
11012 if (!getDerived().AlwaysRebuild() &&
11013 OldT == NewT &&
11014 Init.get() == E->getInitializer())
11015 return SemaRef.MaybeBindToTemporary(E);
11016
11017 // Note: the expression type doesn't necessarily match the
11018 // type-as-written, but that's okay, because it should always be
11019 // derivable from the initializer.
11020
11021 return getDerived().RebuildCompoundLiteralExpr(
11022 E->getLParenLoc(), NewT,
11023 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11024}
11025
11026template<typename Derived>
11027ExprResult
11028TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11029 ExprResult Base = getDerived().TransformExpr(E->getBase());
11030 if (Base.isInvalid())
11031 return ExprError();
11032
11033 if (!getDerived().AlwaysRebuild() &&
11034 Base.get() == E->getBase())
11035 return E;
11036
11037 // FIXME: Bad source location
11038 SourceLocation FakeOperatorLoc =
11039 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11040 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
11041 E->getAccessorLoc(),
11042 E->getAccessor());
11043}
11044
11045template<typename Derived>
11046ExprResult
11047TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11048 if (InitListExpr *Syntactic = E->getSyntacticForm())
11049 E = Syntactic;
11050
11051 bool InitChanged = false;
11052
11053 EnterExpressionEvaluationContext Context(
11054 getSema(), EnterExpressionEvaluationContext::InitList);
11055
11056 SmallVector<Expr*, 4> Inits;
11057 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11058 Inits, &InitChanged))
11059 return ExprError();
11060
11061 if (!getDerived().AlwaysRebuild() && !InitChanged) {
11062 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11063 // in some cases. We can't reuse it in general, because the syntactic and
11064 // semantic forms are linked, and we can't know that semantic form will
11065 // match even if the syntactic form does.
11066 }
11067
11068 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11069 E->getRBraceLoc());
11070}
11071
11072template<typename Derived>
11073ExprResult
11074TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11075 Designation Desig;
11076
11077 // transform the initializer value
11078 ExprResult Init = getDerived().TransformExpr(E->getInit());
11079 if (Init.isInvalid())
11080 return ExprError();
11081
11082 // transform the designators.
11083 SmallVector<Expr*, 4> ArrayExprs;
11084 bool ExprChanged = false;
11085 for (const DesignatedInitExpr::Designator &D : E->designators()) {
11086 if (D.isFieldDesignator()) {
11087 Desig.AddDesignator(Designator::getField(D.getFieldName(),
11088 D.getDotLoc(),
11089 D.getFieldLoc()));
11090 if (D.getField()) {
11091 FieldDecl *Field = cast_or_null<FieldDecl>(
11092 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
11093 if (Field != D.getField())
11094 // Rebuild the expression when the transformed FieldDecl is
11095 // different to the already assigned FieldDecl.
11096 ExprChanged = true;
11097 } else {
11098 // Ensure that the designator expression is rebuilt when there isn't
11099 // a resolved FieldDecl in the designator as we don't want to assign
11100 // a FieldDecl to a pattern designator that will be instantiated again.
11101 ExprChanged = true;
11102 }
11103 continue;
11104 }
11105
11106 if (D.isArrayDesignator()) {
11107 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11108 if (Index.isInvalid())
11109 return ExprError();
11110
11111 Desig.AddDesignator(
11112 Designator::getArray(Index.get(), D.getLBracketLoc()));
11113
11114 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11115 ArrayExprs.push_back(Index.get());
11116 continue;
11117 }
11118
11119 assert(D.isArrayRangeDesignator() && "New kind of designator?")((D.isArrayRangeDesignator() && "New kind of designator?"
) ? static_cast<void> (0) : __assert_fail ("D.isArrayRangeDesignator() && \"New kind of designator?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11119, __PRETTY_FUNCTION__))
;
11120 ExprResult Start
11121 = getDerived().TransformExpr(E->getArrayRangeStart(D));
11122 if (Start.isInvalid())
11123 return ExprError();
11124
11125 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11126 if (End.isInvalid())
11127 return ExprError();
11128
11129 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
11130 End.get(),
11131 D.getLBracketLoc(),
11132 D.getEllipsisLoc()));
11133
11134 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11135 End.get() != E->getArrayRangeEnd(D);
11136
11137 ArrayExprs.push_back(Start.get());
11138 ArrayExprs.push_back(End.get());
11139 }
11140
11141 if (!getDerived().AlwaysRebuild() &&
11142 Init.get() == E->getInit() &&
11143 !ExprChanged)
11144 return E;
11145
11146 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11147 E->getEqualOrColonLoc(),
11148 E->usesGNUSyntax(), Init.get());
11149}
11150
11151// Seems that if TransformInitListExpr() only works on the syntactic form of an
11152// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11153template<typename Derived>
11154ExprResult
11155TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11156 DesignatedInitUpdateExpr *E) {
11157 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11158)
11158 "initializer")::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11158)
;
11159 return ExprError();
11160}
11161
11162template<typename Derived>
11163ExprResult
11164TreeTransform<Derived>::TransformNoInitExpr(
11165 NoInitExpr *E) {
11166 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer")::llvm::llvm_unreachable_internal("Unexpected NoInitExpr in syntactic form of initializer"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11166)
;
11167 return ExprError();
11168}
11169
11170template<typename Derived>
11171ExprResult
11172TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11173 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitLoopExpr outside of initializer"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11173)
;
11174 return ExprError();
11175}
11176
11177template<typename Derived>
11178ExprResult
11179TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11180 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitIndexExpr outside of initializer"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11180)
;
11181 return ExprError();
11182}
11183
11184template<typename Derived>
11185ExprResult
11186TreeTransform<Derived>::TransformImplicitValueInitExpr(
11187 ImplicitValueInitExpr *E) {
11188 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11189
11190 // FIXME: Will we ever have proper type location here? Will we actually
11191 // need to transform the type?
11192 QualType T = getDerived().TransformType(E->getType());
11193 if (T.isNull())
11194 return ExprError();
11195
11196 if (!getDerived().AlwaysRebuild() &&
11197 T == E->getType())
11198 return E;
11199
11200 return getDerived().RebuildImplicitValueInitExpr(T);
11201}
11202
11203template<typename Derived>
11204ExprResult
11205TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11206 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11207 if (!TInfo)
11208 return ExprError();
11209
11210 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11211 if (SubExpr.isInvalid())
11212 return ExprError();
11213
11214 if (!getDerived().AlwaysRebuild() &&
11215 TInfo == E->getWrittenTypeInfo() &&
11216 SubExpr.get() == E->getSubExpr())
11217 return E;
11218
11219 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11220 TInfo, E->getRParenLoc());
11221}
11222
11223template<typename Derived>
11224ExprResult
11225TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11226 bool ArgumentChanged = false;
11227 SmallVector<Expr*, 4> Inits;
11228 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11229 &ArgumentChanged))
11230 return ExprError();
11231
11232 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11233 Inits,
11234 E->getRParenLoc());
11235}
11236
11237/// Transform an address-of-label expression.
11238///
11239/// By default, the transformation of an address-of-label expression always
11240/// rebuilds the expression, so that the label identifier can be resolved to
11241/// the corresponding label statement by semantic analysis.
11242template<typename Derived>
11243ExprResult
11244TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11245 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11246 E->getLabel());
11247 if (!LD)
11248 return ExprError();
11249
11250 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11251 cast<LabelDecl>(LD));
11252}
11253
11254template<typename Derived>
11255ExprResult
11256TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11257 SemaRef.ActOnStartStmtExpr();
11258 StmtResult SubStmt
11259 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11260 if (SubStmt.isInvalid()) {
11261 SemaRef.ActOnStmtExprError();
11262 return ExprError();
11263 }
11264
11265 unsigned OldDepth = E->getTemplateDepth();
11266 unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11267
11268 if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11269 SubStmt.get() == E->getSubStmt()) {
11270 // Calling this an 'error' is unintuitive, but it does the right thing.
11271 SemaRef.ActOnStmtExprError();
11272 return SemaRef.MaybeBindToTemporary(E);
11273 }
11274
11275 return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11276 E->getRParenLoc(), NewDepth);
11277}
11278
11279template<typename Derived>
11280ExprResult
11281TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11282 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11283 if (Cond.isInvalid())
11284 return ExprError();
11285
11286 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11287 if (LHS.isInvalid())
11288 return ExprError();
11289
11290 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11291 if (RHS.isInvalid())
11292 return ExprError();
11293
11294 if (!getDerived().AlwaysRebuild() &&
11295 Cond.get() == E->getCond() &&
11296 LHS.get() == E->getLHS() &&
11297 RHS.get() == E->getRHS())
11298 return E;
11299
11300 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11301 Cond.get(), LHS.get(), RHS.get(),
11302 E->getRParenLoc());
11303}
11304
11305template<typename Derived>
11306ExprResult
11307TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11308 return E;
11309}
11310
11311template<typename Derived>
11312ExprResult
11313TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11314 switch (E->getOperator()) {
11315 case OO_New:
11316 case OO_Delete:
11317 case OO_Array_New:
11318 case OO_Array_Delete:
11319 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr")::llvm::llvm_unreachable_internal("new and delete operators cannot use CXXOperatorCallExpr"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11319)
;
11320
11321 case OO_Call: {
11322 // This is a call to an object's operator().
11323 assert(E->getNumArgs() >= 1 && "Object call is missing arguments")((E->getNumArgs() >= 1 && "Object call is missing arguments"
) ? static_cast<void> (0) : __assert_fail ("E->getNumArgs() >= 1 && \"Object call is missing arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11323, __PRETTY_FUNCTION__))
;
11324
11325 // Transform the object itself.
11326 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11327 if (Object.isInvalid())
11328 return ExprError();
11329
11330 // FIXME: Poor location information
11331 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11332 static_cast<Expr *>(Object.get())->getEndLoc());
11333
11334 // Transform the call arguments.
11335 SmallVector<Expr*, 8> Args;
11336 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11337 Args))
11338 return ExprError();
11339
11340 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11341 E->getEndLoc());
11342 }
11343
11344#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11345 case OO_##Name:
11346#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11347#include "clang/Basic/OperatorKinds.def"
11348 case OO_Subscript:
11349 // Handled below.
11350 break;
11351
11352 case OO_Conditional:
11353 llvm_unreachable("conditional operator is not actually overloadable")::llvm::llvm_unreachable_internal("conditional operator is not actually overloadable"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11353)
;
11354
11355 case OO_None:
11356 case NUM_OVERLOADED_OPERATORS:
11357 llvm_unreachable("not an overloaded operator?")::llvm::llvm_unreachable_internal("not an overloaded operator?"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 11357)
;
11358 }
11359
11360 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11361 if (Callee.isInvalid())
11362 return ExprError();
11363
11364 ExprResult First;
11365 if (E->getOperator() == OO_Amp)
11366 First = getDerived().TransformAddressOfOperand(E->getArg(0));
11367 else
11368 First = getDerived().TransformExpr(E->getArg(0));
11369 if (First.isInvalid())
11370 return ExprError();
11371
11372 ExprResult Second;
11373 if (E->getNumArgs() == 2) {
11374 Second = getDerived().TransformExpr(E->getArg(1));
11375 if (Second.isInvalid())
11376 return ExprError();
11377 }
11378
11379 if (!getDerived().AlwaysRebuild() &&
11380 Callee.get() == E->getCallee() &&
11381 First.get() == E->getArg(0) &&
11382 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11383 return SemaRef.MaybeBindToTemporary(E);
11384
11385 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11386 FPOptionsOverride NewOverrides(E->getFPFeatures());
11387 getSema().CurFPFeatures =
11388 NewOverrides.applyOverrides(getSema().getLangOpts());
11389 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11390
11391 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11392 E->getOperatorLoc(),
11393 Callee.get(),
11394 First.get(),
11395 Second.get());
11396}
11397
11398template<typename Derived>
11399ExprResult
11400TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11401 return getDerived().TransformCallExpr(E);
11402}
11403
11404template <typename Derived>
11405ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11406 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11407 getSema().CurContext != E->getParentContext();
11408
11409 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11410 return E;
11411
11412 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
11413 E->getEndLoc(),
11414 getSema().CurContext);
11415}
11416
11417template<typename Derived>
11418ExprResult
11419TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11420 // Transform the callee.
11421 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11422 if (Callee.isInvalid())
11423 return ExprError();
11424
11425 // Transform exec config.
11426 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11427 if (EC.isInvalid())
11428 return ExprError();
11429
11430 // Transform arguments.
11431 bool ArgChanged = false;
11432 SmallVector<Expr*, 8> Args;
11433 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11434 &ArgChanged))
11435 return ExprError();
11436
11437 if (!getDerived().AlwaysRebuild() &&
11438 Callee.get() == E->getCallee() &&
11439 !ArgChanged)
11440 return SemaRef.MaybeBindToTemporary(E);
11441
11442 // FIXME: Wrong source location information for the '('.
11443 SourceLocation FakeLParenLoc
11444 = ((Expr *)Callee.get())->getSourceRange().getBegin();
11445 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11446 Args,
11447 E->getRParenLoc(), EC.get());
11448}
11449
11450template<typename Derived>
11451ExprResult
11452TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11453 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11454 if (!Type)
11455 return ExprError();
11456
11457 ExprResult SubExpr
11458 = getDerived().TransformExpr(E->getSubExprAsWritten());
11459 if (SubExpr.isInvalid())
11460 return ExprError();
11461
11462 if (!getDerived().AlwaysRebuild() &&
11463 Type == E->getTypeInfoAsWritten() &&
11464 SubExpr.get() == E->getSubExpr())
11465 return E;
11466 return getDerived().RebuildCXXNamedCastExpr(
11467 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11468 Type, E->getAngleBrackets().getEnd(),
11469 // FIXME. this should be '(' location
11470 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11471}
11472
11473template<typename Derived>
11474ExprResult
11475TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11476 TypeSourceInfo *TSI =
11477 getDerived().TransformType(BCE->getTypeInfoAsWritten());
11478 if (!TSI)
11479 return ExprError();
11480
11481 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
11482 if (Sub.isInvalid())
11483 return ExprError();
11484
11485 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
11486 Sub.get(), BCE->getEndLoc());
11487}
11488
11489template<typename Derived>
11490ExprResult
11491TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
11492 return getDerived().TransformCXXNamedCastExpr(E);
11493}
11494
11495template<typename Derived>
11496ExprResult
11497TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
11498 return getDerived().TransformCXXNamedCastExpr(E);
11499}
11500
11501template<typename Derived>
11502ExprResult
11503TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
11504 CXXReinterpretCastExpr *E) {
11505 return getDerived().TransformCXXNamedCastExpr(E);
11506}
11507
11508template<typename Derived>
11509ExprResult
11510TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
11511 return getDerived().TransformCXXNamedCastExpr(E);
11512}
11513
11514template<typename Derived>
11515ExprResult
11516TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
11517 return getDerived().TransformCXXNamedCastExpr(E);
11518}
11519
11520template<typename Derived>
11521ExprResult
11522TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
11523 CXXFunctionalCastExpr *E) {
11524 TypeSourceInfo *Type =
11525 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
11526 if (!Type)
11527 return ExprError();
11528
11529 ExprResult SubExpr
11530 = getDerived().TransformExpr(E->getSubExprAsWritten());
11531 if (SubExpr.isInvalid())
11532 return ExprError();
11533
11534 if (!getDerived().AlwaysRebuild() &&
11535 Type == E->getTypeInfoAsWritten() &&
11536 SubExpr.get() == E->getSubExpr())
11537 return E;
11538
11539 return getDerived().RebuildCXXFunctionalCastExpr(Type,
11540 E->getLParenLoc(),
11541 SubExpr.get(),
11542 E->getRParenLoc(),
11543 E->isListInitialization());
11544}
11545
11546template<typename Derived>
11547ExprResult
11548TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
11549 if (E->isTypeOperand()) {
11550 TypeSourceInfo *TInfo
11551 = getDerived().TransformType(E->getTypeOperandSourceInfo());
11552 if (!TInfo)
11553 return ExprError();
11554
11555 if (!getDerived().AlwaysRebuild() &&
11556 TInfo == E->getTypeOperandSourceInfo())
11557 return E;
11558
11559 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11560 TInfo, E->getEndLoc());
11561 }
11562
11563 // We don't know whether the subexpression is potentially evaluated until
11564 // after we perform semantic analysis. We speculatively assume it is
11565 // unevaluated; it will get fixed later if the subexpression is in fact
11566 // potentially evaluated.
11567 EnterExpressionEvaluationContext Unevaluated(
11568 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11569 Sema::ReuseLambdaContextDecl);
11570
11571 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11572 if (SubExpr.isInvalid())
11573 return ExprError();
11574
11575 if (!getDerived().AlwaysRebuild() &&
11576 SubExpr.get() == E->getExprOperand())
11577 return E;
11578
11579 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11580 SubExpr.get(), E->getEndLoc());
11581}
11582
11583template<typename Derived>
11584ExprResult
11585TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
11586 if (E->isTypeOperand()) {
11587 TypeSourceInfo *TInfo
11588 = getDerived().TransformType(E->getTypeOperandSourceInfo());
11589 if (!TInfo)
11590 return ExprError();
11591
11592 if (!getDerived().AlwaysRebuild() &&
11593 TInfo == E->getTypeOperandSourceInfo())
11594 return E;
11595
11596 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11597 TInfo, E->getEndLoc());
11598 }
11599
11600 EnterExpressionEvaluationContext Unevaluated(
11601 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11602
11603 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11604 if (SubExpr.isInvalid())
11605 return ExprError();
11606
11607 if (!getDerived().AlwaysRebuild() &&
11608 SubExpr.get() == E->getExprOperand())
11609 return E;
11610
11611 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11612 SubExpr.get(), E->getEndLoc());
11613}
11614
11615template<typename Derived>
11616ExprResult
11617TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
11618 return E;
11619}
11620
11621template<typename Derived>
11622ExprResult
11623TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
11624 CXXNullPtrLiteralExpr *E) {
11625 return E;
11626}
11627
11628template<typename Derived>
11629ExprResult
11630TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
11631 QualType T = getSema().getCurrentThisType();
11632
11633 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
11634 // Mark it referenced in the new context regardless.
11635 // FIXME: this is a bit instantiation-specific.
11636 getSema().MarkThisReferenced(E);
11637 return E;
11638 }
11639
11640 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
11641}
11642
11643template<typename Derived>
11644ExprResult
11645TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
11646 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11647 if (SubExpr.isInvalid())
11648 return ExprError();
11649
11650 if (!getDerived().AlwaysRebuild() &&
11651 SubExpr.get() == E->getSubExpr())
11652 return E;
11653
11654 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
11655 E->isThrownVariableInScope());
11656}
11657
11658template<typename Derived>
11659ExprResult
11660TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11661 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
11662 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
11663 if (!Param)
11664 return ExprError();
11665
11666 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
11667 E->getUsedContext() == SemaRef.CurContext)
11668 return E;
11669
11670 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
11671}
11672
11673template<typename Derived>
11674ExprResult
11675TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
11676 FieldDecl *Field = cast_or_null<FieldDecl>(
11677 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
11678 if (!Field)
11679 return ExprError();
11680
11681 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
11682 E->getUsedContext() == SemaRef.CurContext)
11683 return E;
11684
11685 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
11686}
11687
11688template<typename Derived>
11689ExprResult
11690TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
11691 CXXScalarValueInitExpr *E) {
11692 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
11693 if (!T)
11694 return ExprError();
11695
11696 if (!getDerived().AlwaysRebuild() &&
11697 T == E->getTypeSourceInfo())
11698 return E;
11699
11700 return getDerived().RebuildCXXScalarValueInitExpr(T,
11701 /*FIXME:*/T->getTypeLoc().getEndLoc(),
11702 E->getRParenLoc());
11703}
11704
11705template<typename Derived>
11706ExprResult
11707TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
11708 // Transform the type that we're allocating
11709 TypeSourceInfo *AllocTypeInfo =
11710 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
11711 if (!AllocTypeInfo)
11712 return ExprError();
11713
11714 // Transform the size of the array we're allocating (if any).
11715 Optional<Expr *> ArraySize;
11716 if (Optional<Expr *> OldArraySize = E->getArraySize()) {
11717 ExprResult NewArraySize;
11718 if (*OldArraySize) {
11719 NewArraySize = getDerived().TransformExpr(*OldArraySize);
11720 if (NewArraySize.isInvalid())
11721 return ExprError();
11722 }
11723 ArraySize = NewArraySize.get();
11724 }
11725
11726 // Transform the placement arguments (if any).
11727 bool ArgumentChanged = false;
11728 SmallVector<Expr*, 8> PlacementArgs;
11729 if (getDerived().TransformExprs(E->getPlacementArgs(),
11730 E->getNumPlacementArgs(), true,
11731 PlacementArgs, &ArgumentChanged))
11732 return ExprError();
11733
11734 // Transform the initializer (if any).
11735 Expr *OldInit = E->getInitializer();
11736 ExprResult NewInit;
11737 if (OldInit)
11738 NewInit = getDerived().TransformInitializer(OldInit, true);
11739 if (NewInit.isInvalid())
11740 return ExprError();
11741
11742 // Transform new operator and delete operator.
11743 FunctionDecl *OperatorNew = nullptr;
11744 if (E->getOperatorNew()) {
11745 OperatorNew = cast_or_null<FunctionDecl>(
11746 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
11747 if (!OperatorNew)
11748 return ExprError();
11749 }
11750
11751 FunctionDecl *OperatorDelete = nullptr;
11752 if (E->getOperatorDelete()) {
11753 OperatorDelete = cast_or_null<FunctionDecl>(
11754 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11755 if (!OperatorDelete)
11756 return ExprError();
11757 }
11758
11759 if (!getDerived().AlwaysRebuild() &&
11760 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
11761 ArraySize == E->getArraySize() &&
11762 NewInit.get() == OldInit &&
11763 OperatorNew == E->getOperatorNew() &&
11764 OperatorDelete == E->getOperatorDelete() &&
11765 !ArgumentChanged) {
11766 // Mark any declarations we need as referenced.
11767 // FIXME: instantiation-specific.
11768 if (OperatorNew)
11769 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
11770 if (OperatorDelete)
11771 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11772
11773 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
11774 QualType ElementType
11775 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
11776 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
11777 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
11778 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
11779 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
11780 }
11781 }
11782 }
11783
11784 return E;
11785 }
11786
11787 QualType AllocType = AllocTypeInfo->getType();
11788 if (!ArraySize) {
11789 // If no array size was specified, but the new expression was
11790 // instantiated with an array type (e.g., "new T" where T is
11791 // instantiated with "int[4]"), extract the outer bound from the
11792 // array type as our array size. We do this with constant and
11793 // dependently-sized array types.
11794 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
11795 if (!ArrayT) {
11796 // Do nothing
11797 } else if (const ConstantArrayType *ConsArrayT
11798 = dyn_cast<ConstantArrayType>(ArrayT)) {
11799 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
11800 SemaRef.Context.getSizeType(),
11801 /*FIXME:*/ E->getBeginLoc());
11802 AllocType = ConsArrayT->getElementType();
11803 } else if (const DependentSizedArrayType *DepArrayT
11804 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
11805 if (DepArrayT->getSizeExpr()) {
11806 ArraySize = DepArrayT->getSizeExpr();
11807 AllocType = DepArrayT->getElementType();
11808 }
11809 }
11810 }
11811
11812 return getDerived().RebuildCXXNewExpr(
11813 E->getBeginLoc(), E->isGlobalNew(),
11814 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
11815 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
11816 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
11817}
11818
11819template<typename Derived>
11820ExprResult
11821TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
11822 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
11823 if (Operand.isInvalid())
11824 return ExprError();
11825
11826 // Transform the delete operator, if known.
11827 FunctionDecl *OperatorDelete = nullptr;
11828 if (E->getOperatorDelete()) {
11829 OperatorDelete = cast_or_null<FunctionDecl>(
11830 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
11831 if (!OperatorDelete)
11832 return ExprError();
11833 }
11834
11835 if (!getDerived().AlwaysRebuild() &&
11836 Operand.get() == E->getArgument() &&
11837 OperatorDelete == E->getOperatorDelete()) {
11838 // Mark any declarations we need as referenced.
11839 // FIXME: instantiation-specific.
11840 if (OperatorDelete)
11841 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
11842
11843 if (!E->getArgument()->isTypeDependent()) {
11844 QualType Destroyed = SemaRef.Context.getBaseElementType(
11845 E->getDestroyedType());
11846 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11847 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11848 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
11849 SemaRef.LookupDestructor(Record));
11850 }
11851 }
11852
11853 return E;
11854 }
11855
11856 return getDerived().RebuildCXXDeleteExpr(
11857 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
11858}
11859
11860template<typename Derived>
11861ExprResult
11862TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
11863 CXXPseudoDestructorExpr *E) {
11864 ExprResult Base = getDerived().TransformExpr(E->getBase());
11865 if (Base.isInvalid())
11866 return ExprError();
11867
11868 ParsedType ObjectTypePtr;
11869 bool MayBePseudoDestructor = false;
11870 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11871 E->getOperatorLoc(),
11872 E->isArrow()? tok::arrow : tok::period,
11873 ObjectTypePtr,
11874 MayBePseudoDestructor);
11875 if (Base.isInvalid())
11876 return ExprError();
11877
11878 QualType ObjectType = ObjectTypePtr.get();
11879 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
11880 if (QualifierLoc) {
11881 QualifierLoc
11882 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
11883 if (!QualifierLoc)
11884 return ExprError();
11885 }
11886 CXXScopeSpec SS;
11887 SS.Adopt(QualifierLoc);
11888
11889 PseudoDestructorTypeStorage Destroyed;
11890 if (E->getDestroyedTypeInfo()) {
11891 TypeSourceInfo *DestroyedTypeInfo
11892 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
11893 ObjectType, nullptr, SS);
11894 if (!DestroyedTypeInfo)
11895 return ExprError();
11896 Destroyed = DestroyedTypeInfo;
11897 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
11898 // We aren't likely to be able to resolve the identifier down to a type
11899 // now anyway, so just retain the identifier.
11900 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
11901 E->getDestroyedTypeLoc());
11902 } else {
11903 // Look for a destructor known with the given name.
11904 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
11905 *E->getDestroyedTypeIdentifier(),
11906 E->getDestroyedTypeLoc(),
11907 /*Scope=*/nullptr,
11908 SS, ObjectTypePtr,
11909 false);
11910 if (!T)
11911 return ExprError();
11912
11913 Destroyed
11914 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
11915 E->getDestroyedTypeLoc());
11916 }
11917
11918 TypeSourceInfo *ScopeTypeInfo = nullptr;
11919 if (E->getScopeTypeInfo()) {
11920 CXXScopeSpec EmptySS;
11921 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
11922 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
11923 if (!ScopeTypeInfo)
11924 return ExprError();
11925 }
11926
11927 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
11928 E->getOperatorLoc(),
11929 E->isArrow(),
11930 SS,
11931 ScopeTypeInfo,
11932 E->getColonColonLoc(),
11933 E->getTildeLoc(),
11934 Destroyed);
11935}
11936
11937template <typename Derived>
11938bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
11939 bool RequiresADL,
11940 LookupResult &R) {
11941 // Transform all the decls.
11942 bool AllEmptyPacks = true;
11943 for (auto *OldD : Old->decls()) {
11944 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
11945 if (!InstD) {
11946 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
11947 // This can happen because of dependent hiding.
11948 if (isa<UsingShadowDecl>(OldD))
11949 continue;
11950 else {
11951 R.clear();
11952 return true;
11953 }
11954 }
11955
11956 // Expand using pack declarations.
11957 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
11958 ArrayRef<NamedDecl*> Decls = SingleDecl;
11959 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
11960 Decls = UPD->expansions();
11961
11962 // Expand using declarations.
11963 for (auto *D : Decls) {
11964 if (auto *UD = dyn_cast<UsingDecl>(D)) {
11965 for (auto *SD : UD->shadows())
11966 R.addDecl(SD);
11967 } else {
11968 R.addDecl(D);
11969 }
11970 }
11971
11972 AllEmptyPacks &= Decls.empty();
11973 };
11974
11975 // C++ [temp.res]/8.4.2:
11976 // The program is ill-formed, no diagnostic required, if [...] lookup for
11977 // a name in the template definition found a using-declaration, but the
11978 // lookup in the corresponding scope in the instantiation odoes not find
11979 // any declarations because the using-declaration was a pack expansion and
11980 // the corresponding pack is empty
11981 if (AllEmptyPacks && !RequiresADL) {
11982 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
11983 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
11984 return true;
11985 }
11986
11987 // Resolve a kind, but don't do any further analysis. If it's
11988 // ambiguous, the callee needs to deal with it.
11989 R.resolveKind();
11990 return false;
11991}
11992
11993template<typename Derived>
11994ExprResult
11995TreeTransform<Derived>::TransformUnresolvedLookupExpr(
11996 UnresolvedLookupExpr *Old) {
11997 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
11998 Sema::LookupOrdinaryName);
11999
12000 // Transform the declaration set.
12001 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12002 return ExprError();
12003
12004 // Rebuild the nested-name qualifier, if present.
12005 CXXScopeSpec SS;
12006 if (Old->getQualifierLoc()) {
12007 NestedNameSpecifierLoc QualifierLoc
12008 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12009 if (!QualifierLoc)
12010 return ExprError();
12011
12012 SS.Adopt(QualifierLoc);
12013 }
12014
12015 if (Old->getNamingClass()) {
12016 CXXRecordDecl *NamingClass
12017 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12018 Old->getNameLoc(),
12019 Old->getNamingClass()));
12020 if (!NamingClass) {
12021 R.clear();
12022 return ExprError();
12023 }
12024
12025 R.setNamingClass(NamingClass);
12026 }
12027
12028 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12029
12030 // If we have neither explicit template arguments, nor the template keyword,
12031 // it's a normal declaration name or member reference.
12032 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12033 NamedDecl *D = R.getAsSingle<NamedDecl>();
12034 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12035 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12036 // give a good diagnostic.
12037 if (D && D->isCXXInstanceMember()) {
12038 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12039 /*TemplateArgs=*/nullptr,
12040 /*Scope=*/nullptr);
12041 }
12042
12043 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12044 }
12045
12046 // If we have template arguments, rebuild them, then rebuild the
12047 // templateid expression.
12048 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12049 if (Old->hasExplicitTemplateArgs() &&
12050 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12051 Old->getNumTemplateArgs(),
12052 TransArgs)) {
12053 R.clear();
12054 return ExprError();
12055 }
12056
12057 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12058 Old->requiresADL(), &TransArgs);
12059}
12060
12061template<typename Derived>
12062ExprResult
12063TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12064 bool ArgChanged = false;
12065 SmallVector<TypeSourceInfo *, 4> Args;
12066 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12067 TypeSourceInfo *From = E->getArg(I);
12068 TypeLoc FromTL = From->getTypeLoc();
12069 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12070 TypeLocBuilder TLB;
12071 TLB.reserve(FromTL.getFullDataSize());
12072 QualType To = getDerived().TransformType(TLB, FromTL);
12073 if (To.isNull())
12074 return ExprError();
12075
12076 if (To == From->getType())
12077 Args.push_back(From);
12078 else {
12079 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12080 ArgChanged = true;
12081 }
12082 continue;
12083 }
12084
12085 ArgChanged = true;
12086
12087 // We have a pack expansion. Instantiate it.
12088 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12089 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12090 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12091 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12092
12093 // Determine whether the set of unexpanded parameter packs can and should
12094 // be expanded.
12095 bool Expand = true;
12096 bool RetainExpansion = false;
12097 Optional<unsigned> OrigNumExpansions =
12098 ExpansionTL.getTypePtr()->getNumExpansions();
12099 Optional<unsigned> NumExpansions = OrigNumExpansions;
12100 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12101 PatternTL.getSourceRange(),
12102 Unexpanded,
12103 Expand, RetainExpansion,
12104 NumExpansions))
12105 return ExprError();
12106
12107 if (!Expand) {
12108 // The transform has determined that we should perform a simple
12109 // transformation on the pack expansion, producing another pack
12110 // expansion.
12111 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12112
12113 TypeLocBuilder TLB;
12114 TLB.reserve(From->getTypeLoc().getFullDataSize());
12115
12116 QualType To = getDerived().TransformType(TLB, PatternTL);
12117 if (To.isNull())
12118 return ExprError();
12119
12120 To = getDerived().RebuildPackExpansionType(To,
12121 PatternTL.getSourceRange(),
12122 ExpansionTL.getEllipsisLoc(),
12123 NumExpansions);
12124 if (To.isNull())
12125 return ExprError();
12126
12127 PackExpansionTypeLoc ToExpansionTL
12128 = TLB.push<PackExpansionTypeLoc>(To);
12129 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12130 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12131 continue;
12132 }
12133
12134 // Expand the pack expansion by substituting for each argument in the
12135 // pack(s).
12136 for (unsigned I = 0; I != *NumExpansions; ++I) {
12137 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12138 TypeLocBuilder TLB;
12139 TLB.reserve(PatternTL.getFullDataSize());
12140 QualType To = getDerived().TransformType(TLB, PatternTL);
12141 if (To.isNull())
12142 return ExprError();
12143
12144 if (To->containsUnexpandedParameterPack()) {
12145 To = getDerived().RebuildPackExpansionType(To,
12146 PatternTL.getSourceRange(),
12147 ExpansionTL.getEllipsisLoc(),
12148 NumExpansions);
12149 if (To.isNull())
12150 return ExprError();
12151
12152 PackExpansionTypeLoc ToExpansionTL
12153 = TLB.push<PackExpansionTypeLoc>(To);
12154 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12155 }
12156
12157 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12158 }
12159
12160 if (!RetainExpansion)
12161 continue;
12162
12163 // If we're supposed to retain a pack expansion, do so by temporarily
12164 // forgetting the partially-substituted parameter pack.
12165 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12166
12167 TypeLocBuilder TLB;
12168 TLB.reserve(From->getTypeLoc().getFullDataSize());
12169
12170 QualType To = getDerived().TransformType(TLB, PatternTL);
12171 if (To.isNull())
12172 return ExprError();
12173
12174 To = getDerived().RebuildPackExpansionType(To,
12175 PatternTL.getSourceRange(),
12176 ExpansionTL.getEllipsisLoc(),
12177 NumExpansions);
12178 if (To.isNull())
12179 return ExprError();
12180
12181 PackExpansionTypeLoc ToExpansionTL
12182 = TLB.push<PackExpansionTypeLoc>(To);
12183 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12184 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12185 }
12186
12187 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12188 return E;
12189
12190 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12191 E->getEndLoc());
12192}
12193
12194template<typename Derived>
12195ExprResult
12196TreeTransform<Derived>::TransformConceptSpecializationExpr(
12197 ConceptSpecializationExpr *E) {
12198 const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12199 TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12200 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12201 Old->NumTemplateArgs, TransArgs))
12202 return ExprError();
12203
12204 return getDerived().RebuildConceptSpecializationExpr(
12205 E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12206 E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12207 &TransArgs);
12208}
12209
12210template<typename Derived>
12211ExprResult
12212TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12213 SmallVector<ParmVarDecl*, 4> TransParams;
12214 SmallVector<QualType, 4> TransParamTypes;
12215 Sema::ExtParameterInfoBuilder ExtParamInfos;
12216
12217 // C++2a [expr.prim.req]p2
12218 // Expressions appearing within a requirement-body are unevaluated operands.
12219 EnterExpressionEvaluationContext Ctx(
12220 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12221
12222 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12223 getSema().Context, getSema().CurContext,
12224 E->getBody()->getBeginLoc());
12225
12226 Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12227
12228 if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
3
Calling 'TreeTransform::TransformFunctionTypeParams'
12229 E->getLocalParameters(),
12230 /*ParamTypes=*/nullptr,
2
Passing null pointer value via 3rd parameter 'ParamTypes'
12231 /*ParamInfos=*/nullptr,
12232 TransParamTypes, &TransParams,
12233 ExtParamInfos))
12234 return ExprError();
12235
12236 for (ParmVarDecl *Param : TransParams)
12237 Param->setDeclContext(Body);
12238
12239 SmallVector<concepts::Requirement *, 4> TransReqs;
12240 if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12241 TransReqs))
12242 return ExprError();
12243
12244 for (concepts::Requirement *Req : TransReqs) {
12245 if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12246 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12247 ER->getReturnTypeRequirement()
12248 .getTypeConstraintTemplateParameterList()->getParam(0)
12249 ->setDeclContext(Body);
12250 }
12251 }
12252 }
12253
12254 return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12255 TransParams, TransReqs,
12256 E->getRBraceLoc());
12257}
12258
12259template<typename Derived>
12260bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12261 ArrayRef<concepts::Requirement *> Reqs,
12262 SmallVectorImpl<concepts::Requirement *> &Transformed) {
12263 for (concepts::Requirement *Req : Reqs) {
12264 concepts::Requirement *TransReq = nullptr;
12265 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12266 TransReq = getDerived().TransformTypeRequirement(TypeReq);
12267 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12268 TransReq = getDerived().TransformExprRequirement(ExprReq);
12269 else
12270 TransReq = getDerived().TransformNestedRequirement(
12271 cast<concepts::NestedRequirement>(Req));
12272 if (!TransReq)
12273 return true;
12274 Transformed.push_back(TransReq);
12275 }
12276 return false;
12277}
12278
12279template<typename Derived>
12280concepts::TypeRequirement *
12281TreeTransform<Derived>::TransformTypeRequirement(
12282 concepts::TypeRequirement *Req) {
12283 if (Req->isSubstitutionFailure()) {
12284 if (getDerived().AlwaysRebuild())
12285 return getDerived().RebuildTypeRequirement(
12286 Req->getSubstitutionDiagnostic());
12287 return Req;
12288 }
12289 TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12290 if (!TransType)
12291 return nullptr;
12292 return getDerived().RebuildTypeRequirement(TransType);
12293}
12294
12295template<typename Derived>
12296concepts::ExprRequirement *
12297TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12298 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12299 if (Req->isExprSubstitutionFailure())
12300 TransExpr = Req->getExprSubstitutionDiagnostic();
12301 else {
12302 ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12303 if (TransExprRes.isInvalid())
12304 return nullptr;
12305 TransExpr = TransExprRes.get();
12306 }
12307
12308 llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12309 const auto &RetReq = Req->getReturnTypeRequirement();
12310 if (RetReq.isEmpty())
12311 TransRetReq.emplace();
12312 else if (RetReq.isSubstitutionFailure())
12313 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12314 else if (RetReq.isTypeConstraint()) {
12315 TemplateParameterList *OrigTPL =
12316 RetReq.getTypeConstraintTemplateParameterList();
12317 TemplateParameterList *TPL =
12318 getDerived().TransformTemplateParameterList(OrigTPL);
12319 if (!TPL)
12320 return nullptr;
12321 TransRetReq.emplace(TPL);
12322 }
12323 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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 12324, __PRETTY_FUNCTION__))
12324 "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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 12324, __PRETTY_FUNCTION__))
;
12325 if (Expr *E = TransExpr.dyn_cast<Expr *>())
12326 return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12327 Req->getNoexceptLoc(),
12328 std::move(*TransRetReq));
12329 return getDerived().RebuildExprRequirement(
12330 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12331 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12332}
12333
12334template<typename Derived>
12335concepts::NestedRequirement *
12336TreeTransform<Derived>::TransformNestedRequirement(
12337 concepts::NestedRequirement *Req) {
12338 if (Req->isSubstitutionFailure()) {
12339 if (getDerived().AlwaysRebuild())
12340 return getDerived().RebuildNestedRequirement(
12341 Req->getSubstitutionDiagnostic());
12342 return Req;
12343 }
12344 ExprResult TransConstraint =
12345 getDerived().TransformExpr(Req->getConstraintExpr());
12346 if (TransConstraint.isInvalid())
12347 return nullptr;
12348 return getDerived().RebuildNestedRequirement(TransConstraint.get());
12349}
12350
12351template<typename Derived>
12352ExprResult
12353TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12354 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12355 if (!T)
12356 return ExprError();
12357
12358 if (!getDerived().AlwaysRebuild() &&
12359 T == E->getQueriedTypeSourceInfo())
12360 return E;
12361
12362 ExprResult SubExpr;
12363 {
12364 EnterExpressionEvaluationContext Unevaluated(
12365 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12366 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12367 if (SubExpr.isInvalid())
12368 return ExprError();
12369
12370 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12371 return E;
12372 }
12373
12374 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12375 SubExpr.get(), E->getEndLoc());
12376}
12377
12378template<typename Derived>
12379ExprResult
12380TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12381 ExprResult SubExpr;
12382 {
12383 EnterExpressionEvaluationContext Unevaluated(
12384 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12385 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12386 if (SubExpr.isInvalid())
12387 return ExprError();
12388
12389 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12390 return E;
12391 }
12392
12393 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12394 SubExpr.get(), E->getEndLoc());
12395}
12396
12397template <typename Derived>
12398ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12399 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12400 TypeSourceInfo **RecoveryTSI) {
12401 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12402 DRE, AddrTaken, RecoveryTSI);
12403
12404 // Propagate both errors and recovered types, which return ExprEmpty.
12405 if (!NewDRE.isUsable())
12406 return NewDRE;
12407
12408 // We got an expr, wrap it up in parens.
12409 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12410 return PE;
12411 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12412 PE->getRParen());
12413}
12414
12415template <typename Derived>
12416ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12417 DependentScopeDeclRefExpr *E) {
12418 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12419 nullptr);
12420}
12421
12422template<typename Derived>
12423ExprResult
12424TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12425 DependentScopeDeclRefExpr *E,
12426 bool IsAddressOfOperand,
12427 TypeSourceInfo **RecoveryTSI) {
12428 assert(E->getQualifierLoc())((E->getQualifierLoc()) ? static_cast<void> (0) : __assert_fail
("E->getQualifierLoc()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 12428, __PRETTY_FUNCTION__))
;
12429 NestedNameSpecifierLoc QualifierLoc
12430 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12431 if (!QualifierLoc)
12432 return ExprError();
12433 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12434
12435 // TODO: If this is a conversion-function-id, verify that the
12436 // destination type name (if present) resolves the same way after
12437 // instantiation as it did in the local scope.
12438
12439 DeclarationNameInfo NameInfo
12440 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12441 if (!NameInfo.getName())
12442 return ExprError();
12443
12444 if (!E->hasExplicitTemplateArgs()) {
12445 if (!getDerived().AlwaysRebuild() &&
12446 QualifierLoc == E->getQualifierLoc() &&
12447 // Note: it is sufficient to compare the Name component of NameInfo:
12448 // if name has not changed, DNLoc has not changed either.
12449 NameInfo.getName() == E->getDeclName())
12450 return E;
12451
12452 return getDerived().RebuildDependentScopeDeclRefExpr(
12453 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12454 IsAddressOfOperand, RecoveryTSI);
12455 }
12456
12457 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12458 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
12459 E->getNumTemplateArgs(),
12460 TransArgs))
12461 return ExprError();
12462
12463 return getDerived().RebuildDependentScopeDeclRefExpr(
12464 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
12465 RecoveryTSI);
12466}
12467
12468template<typename Derived>
12469ExprResult
12470TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
12471 // CXXConstructExprs other than for list-initialization and
12472 // CXXTemporaryObjectExpr are always implicit, so when we have
12473 // a 1-argument construction we just transform that argument.
12474 if (getDerived().AllowSkippingCXXConstructExpr() &&
12475 ((E->getNumArgs() == 1 ||
12476 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
12477 (!getDerived().DropCallArgument(E->getArg(0))) &&
12478 !E->isListInitialization()))
12479 return getDerived().TransformInitializer(E->getArg(0),
12480 /*DirectInit*/ false);
12481
12482 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
12483
12484 QualType T = getDerived().TransformType(E->getType());
12485 if (T.isNull())
12486 return ExprError();
12487
12488 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12489 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12490 if (!Constructor)
12491 return ExprError();
12492
12493 bool ArgumentChanged = false;
12494 SmallVector<Expr*, 8> Args;
12495 {
12496 EnterExpressionEvaluationContext Context(
12497 getSema(), EnterExpressionEvaluationContext::InitList,
12498 E->isListInitialization());
12499 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12500 &ArgumentChanged))
12501 return ExprError();
12502 }
12503
12504 if (!getDerived().AlwaysRebuild() &&
12505 T == E->getType() &&
12506 Constructor == E->getConstructor() &&
12507 !ArgumentChanged) {
12508 // Mark the constructor as referenced.
12509 // FIXME: Instantiation-specific
12510 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12511 return E;
12512 }
12513
12514 return getDerived().RebuildCXXConstructExpr(
12515 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
12516 E->hadMultipleCandidates(), E->isListInitialization(),
12517 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
12518 E->getConstructionKind(), E->getParenOrBraceRange());
12519}
12520
12521template<typename Derived>
12522ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
12523 CXXInheritedCtorInitExpr *E) {
12524 QualType T = getDerived().TransformType(E->getType());
12525 if (T.isNull())
12526 return ExprError();
12527
12528 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12529 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12530 if (!Constructor)
12531 return ExprError();
12532
12533 if (!getDerived().AlwaysRebuild() &&
12534 T == E->getType() &&
12535 Constructor == E->getConstructor()) {
12536 // Mark the constructor as referenced.
12537 // FIXME: Instantiation-specific
12538 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12539 return E;
12540 }
12541
12542 return getDerived().RebuildCXXInheritedCtorInitExpr(
12543 T, E->getLocation(), Constructor,
12544 E->constructsVBase(), E->inheritedFromVBase());
12545}
12546
12547/// Transform a C++ temporary-binding expression.
12548///
12549/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
12550/// transform the subexpression and return that.
12551template<typename Derived>
12552ExprResult
12553TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12554 return getDerived().TransformExpr(E->getSubExpr());
12555}
12556
12557/// Transform a C++ expression that contains cleanups that should
12558/// be run after the expression is evaluated.
12559///
12560/// Since ExprWithCleanups nodes are implicitly generated, we
12561/// just transform the subexpression and return that.
12562template<typename Derived>
12563ExprResult
12564TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
12565 return getDerived().TransformExpr(E->getSubExpr());
12566}
12567
12568template<typename Derived>
12569ExprResult
12570TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
12571 CXXTemporaryObjectExpr *E) {
12572 TypeSourceInfo *T =
12573 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12574 if (!T)
12575 return ExprError();
12576
12577 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12578 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12579 if (!Constructor)
12580 return ExprError();
12581
12582 bool ArgumentChanged = false;
12583 SmallVector<Expr*, 8> Args;
12584 Args.reserve(E->getNumArgs());
12585 {
12586 EnterExpressionEvaluationContext Context(
12587 getSema(), EnterExpressionEvaluationContext::InitList,
12588 E->isListInitialization());
12589 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12590 &ArgumentChanged))
12591 return ExprError();
12592 }
12593
12594 if (!getDerived().AlwaysRebuild() &&
12595 T == E->getTypeSourceInfo() &&
12596 Constructor == E->getConstructor() &&
12597 !ArgumentChanged) {
12598 // FIXME: Instantiation-specific
12599 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12600 return SemaRef.MaybeBindToTemporary(E);
12601 }
12602
12603 // FIXME: We should just pass E->isListInitialization(), but we're not
12604 // prepared to handle list-initialization without a child InitListExpr.
12605 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
12606 return getDerived().RebuildCXXTemporaryObjectExpr(
12607 T, LParenLoc, Args, E->getEndLoc(),
12608 /*ListInitialization=*/LParenLoc.isInvalid());
12609}
12610
12611template<typename Derived>
12612ExprResult
12613TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
12614 // Transform any init-capture expressions before entering the scope of the
12615 // lambda body, because they are not semantically within that scope.
12616 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
12617 struct TransformedInitCapture {
12618 // The location of the ... if the result is retaining a pack expansion.
12619 SourceLocation EllipsisLoc;
12620 // Zero or more expansions of the init-capture.
12621 SmallVector<InitCaptureInfoTy, 4> Expansions;
12622 };
12623 SmallVector<TransformedInitCapture, 4> InitCaptures;
12624 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
12625 for (LambdaExpr::capture_iterator C = E->capture_begin(),
12626 CEnd = E->capture_end();
12627 C != CEnd; ++C) {
12628 if (!E->isInitCapture(C))
12629 continue;
12630
12631 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
12632 VarDecl *OldVD = C->getCapturedVar();
12633
12634 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
12635 Optional<unsigned> NumExpansions) {
12636 ExprResult NewExprInitResult = getDerived().TransformInitializer(
12637 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
12638
12639 if (NewExprInitResult.isInvalid()) {
12640 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
12641 return;
12642 }
12643 Expr *NewExprInit = NewExprInitResult.get();
12644
12645 QualType NewInitCaptureType =
12646 getSema().buildLambdaInitCaptureInitialization(
12647 C->getLocation(), OldVD->getType()->isReferenceType(),
12648 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
12649 C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
12650 NewExprInit);
12651 Result.Expansions.push_back(
12652 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
12653 };
12654
12655 // If this is an init-capture pack, consider expanding the pack now.
12656 if (OldVD->isParameterPack()) {
12657 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
12658 ->getTypeLoc()
12659 .castAs<PackExpansionTypeLoc>();
12660 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12661 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
12662
12663 // Determine whether the set of unexpanded parameter packs can and should
12664 // be expanded.
12665 bool Expand = true;
12666 bool RetainExpansion = false;
12667 Optional<unsigned> OrigNumExpansions =
12668 ExpansionTL.getTypePtr()->getNumExpansions();
12669 Optional<unsigned> NumExpansions = OrigNumExpansions;
12670 if (getDerived().TryExpandParameterPacks(
12671 ExpansionTL.getEllipsisLoc(),
12672 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
12673 RetainExpansion, NumExpansions))
12674 return ExprError();
12675 if (Expand) {
12676 for (unsigned I = 0; I != *NumExpansions; ++I) {
12677 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12678 SubstInitCapture(SourceLocation(), None);
12679 }
12680 }
12681 if (!Expand || RetainExpansion) {
12682 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12683 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
12684 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
12685 }
12686 } else {
12687 SubstInitCapture(SourceLocation(), None);
12688 }
12689 }
12690
12691 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
12692 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
12693
12694 // Transform the template parameters, and add them to the current
12695 // instantiation scope. The null case is handled correctly.
12696 auto TPL = getDerived().TransformTemplateParameterList(
12697 E->getTemplateParameterList());
12698 LSI->GLTemplateParameterList = TPL;
12699
12700 // Transform the type of the original lambda's call operator.
12701 // The transformation MUST be done in the CurrentInstantiationScope since
12702 // it introduces a mapping of the original to the newly created
12703 // transformed parameters.
12704 TypeSourceInfo *NewCallOpTSI = nullptr;
12705 {
12706 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
12707 FunctionProtoTypeLoc OldCallOpFPTL =
12708 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
12709
12710 TypeLocBuilder NewCallOpTLBuilder;
12711 SmallVector<QualType, 4> ExceptionStorage;
12712 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
12713 QualType NewCallOpType = TransformFunctionProtoType(
12714 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
12715 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
12716 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
12717 ExceptionStorage, Changed);
12718 });
12719 if (NewCallOpType.isNull())
12720 return ExprError();
12721 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
12722 NewCallOpType);
12723 }
12724
12725 // Transform the trailing requires clause
12726 ExprResult NewTrailingRequiresClause;
12727 if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
12728 // FIXME: Concepts: Substitution into requires clause should only happen
12729 // when checking satisfaction.
12730 NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
12731
12732 // Create the local class that will describe the lambda.
12733 // FIXME: KnownDependent below is wrong when substituting inside a templated
12734 // context that isn't a DeclContext (such as a variable template).
12735 CXXRecordDecl *OldClass = E->getLambdaClass();
12736 CXXRecordDecl *Class
12737 = getSema().createLambdaClosureType(E->getIntroducerRange(),
12738 NewCallOpTSI,
12739 /*KnownDependent=*/false,
12740 E->getCaptureDefault());
12741 getDerived().transformedLocalDecl(OldClass, {Class});
12742
12743 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling;
12744 if (getDerived().ReplacingOriginal())
12745 Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(),
12746 OldClass->getLambdaManglingNumber(),
12747 OldClass->getDeviceLambdaManglingNumber(),
12748 OldClass->getLambdaContextDecl());
12749
12750 // Build the call operator.
12751 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
12752 Class, E->getIntroducerRange(), NewCallOpTSI,
12753 E->getCallOperator()->getEndLoc(),
12754 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
12755 E->getCallOperator()->getConstexprKind(),
12756 NewTrailingRequiresClause.get());
12757
12758 LSI->CallOperator = NewCallOperator;
12759
12760 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
12761 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
12762
12763 // Number the lambda for linkage purposes if necessary.
12764 getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
12765
12766 // Introduce the context of the call operator.
12767 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
12768 /*NewThisContext*/false);
12769
12770 // Enter the scope of the lambda.
12771 getSema().buildLambdaScope(LSI, NewCallOperator,
12772 E->getIntroducerRange(),
12773 E->getCaptureDefault(),
12774 E->getCaptureDefaultLoc(),
12775 E->hasExplicitParameters(),
12776 E->hasExplicitResultType(),
12777 E->isMutable());
12778
12779 bool Invalid = false;
12780
12781 // Transform captures.
12782 for (LambdaExpr::capture_iterator C = E->capture_begin(),
12783 CEnd = E->capture_end();
12784 C != CEnd; ++C) {
12785 // When we hit the first implicit capture, tell Sema that we've finished
12786 // the list of explicit captures.
12787 if (C->isImplicit())
12788 break;
12789
12790 // Capturing 'this' is trivial.
12791 if (C->capturesThis()) {
12792 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12793 /*BuildAndDiagnose*/ true, nullptr,
12794 C->getCaptureKind() == LCK_StarThis);
12795 continue;
12796 }
12797 // Captured expression will be recaptured during captured variables
12798 // rebuilding.
12799 if (C->capturesVLAType())
12800 continue;
12801
12802 // Rebuild init-captures, including the implied field declaration.
12803 if (E->isInitCapture(C)) {
12804 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
12805
12806 VarDecl *OldVD = C->getCapturedVar();
12807 llvm::SmallVector<Decl*, 4> NewVDs;
12808
12809 for (InitCaptureInfoTy &Info : NewC.Expansions) {
12810 ExprResult Init = Info.first;
12811 QualType InitQualType = Info.second;
12812 if (Init.isInvalid() || InitQualType.isNull()) {
12813 Invalid = true;
12814 break;
12815 }
12816 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
12817 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
12818 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
12819 if (!NewVD) {
12820 Invalid = true;
12821 break;
12822 }
12823 NewVDs.push_back(NewVD);
12824 getSema().addInitCapture(LSI, NewVD);
12825 }
12826
12827 if (Invalid)
12828 break;
12829
12830 getDerived().transformedLocalDecl(OldVD, NewVDs);
12831 continue;
12832 }
12833
12834 assert(C->capturesVariable() && "unexpected kind of lambda capture")((C->capturesVariable() && "unexpected kind of lambda capture"
) ? static_cast<void> (0) : __assert_fail ("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 12834, __PRETTY_FUNCTION__))
;
12835
12836 // Determine the capture kind for Sema.
12837 Sema::TryCaptureKind Kind
12838 = C->isImplicit()? Sema::TryCapture_Implicit
12839 : C->getCaptureKind() == LCK_ByCopy
12840 ? Sema::TryCapture_ExplicitByVal
12841 : Sema::TryCapture_ExplicitByRef;
12842 SourceLocation EllipsisLoc;
12843 if (C->isPackExpansion()) {
12844 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
12845 bool ShouldExpand = false;
12846 bool RetainExpansion = false;
12847 Optional<unsigned> NumExpansions;
12848 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
12849 C->getLocation(),
12850 Unexpanded,
12851 ShouldExpand, RetainExpansion,
12852 NumExpansions)) {
12853 Invalid = true;
12854 continue;
12855 }
12856
12857 if (ShouldExpand) {
12858 // The transform has determined that we should perform an expansion;
12859 // transform and capture each of the arguments.
12860 // expansion of the pattern. Do so.
12861 VarDecl *Pack = C->getCapturedVar();
12862 for (unsigned I = 0; I != *NumExpansions; ++I) {
12863 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12864 VarDecl *CapturedVar
12865 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
12866 Pack));
12867 if (!CapturedVar) {
12868 Invalid = true;
12869 continue;
12870 }
12871
12872 // Capture the transformed variable.
12873 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
12874 }
12875
12876 // FIXME: Retain a pack expansion if RetainExpansion is true.
12877
12878 continue;
12879 }
12880
12881 EllipsisLoc = C->getEllipsisLoc();
12882 }
12883
12884 // Transform the captured variable.
12885 VarDecl *CapturedVar
12886 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
12887 C->getCapturedVar()));
12888 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
12889 Invalid = true;
12890 continue;
12891 }
12892
12893 // Capture the transformed variable.
12894 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
12895 EllipsisLoc);
12896 }
12897 getSema().finishLambdaExplicitCaptures(LSI);
12898
12899 // FIXME: Sema's lambda-building mechanism expects us to push an expression
12900 // evaluation context even if we're not transforming the function body.
12901 getSema().PushExpressionEvaluationContext(
12902 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
12903
12904 // Instantiate the body of the lambda expression.
12905 StmtResult Body =
12906 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
12907
12908 // ActOnLambda* will pop the function scope for us.
12909 FuncScopeCleanup.disable();
12910
12911 if (Body.isInvalid()) {
12912 SavedContext.pop();
12913 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
12914 /*IsInstantiation=*/true);
12915 return ExprError();
12916 }
12917
12918 // Copy the LSI before ActOnFinishFunctionBody removes it.
12919 // FIXME: This is dumb. Store the lambda information somewhere that outlives
12920 // the call operator.
12921 auto LSICopy = *LSI;
12922 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
12923 /*IsInstantiation*/ true);
12924 SavedContext.pop();
12925
12926 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
12927 &LSICopy);
12928}
12929
12930template<typename Derived>
12931StmtResult
12932TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
12933 return TransformStmt(S);
12934}
12935
12936template<typename Derived>
12937StmtResult
12938TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
12939 // Transform captures.
12940 for (LambdaExpr::capture_iterator C = E->capture_begin(),
12941 CEnd = E->capture_end();
12942 C != CEnd; ++C) {
12943 // When we hit the first implicit capture, tell Sema that we've finished
12944 // the list of explicit captures.
12945 if (!C->isImplicit())
12946 continue;
12947
12948 // Capturing 'this' is trivial.
12949 if (C->capturesThis()) {
12950 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
12951 /*BuildAndDiagnose*/ true, nullptr,
12952 C->getCaptureKind() == LCK_StarThis);
12953 continue;
12954 }
12955 // Captured expression will be recaptured during captured variables
12956 // rebuilding.
12957 if (C->capturesVLAType())
12958 continue;
12959
12960 assert(C->capturesVariable() && "unexpected kind of lambda capture")((C->capturesVariable() && "unexpected kind of lambda capture"
) ? static_cast<void> (0) : __assert_fail ("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 12960, __PRETTY_FUNCTION__))
;
12961 assert(!E->isInitCapture(C) && "implicit init-capture?")((!E->isInitCapture(C) && "implicit init-capture?"
) ? static_cast<void> (0) : __assert_fail ("!E->isInitCapture(C) && \"implicit init-capture?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 12961, __PRETTY_FUNCTION__))
;
12962
12963 // Transform the captured variable.
12964 VarDecl *CapturedVar = cast_or_null<VarDecl>(
12965 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
12966 if (!CapturedVar || CapturedVar->isInvalidDecl())
12967 return StmtError();
12968
12969 // Capture the transformed variable.
12970 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
12971 }
12972
12973 return S;
12974}
12975
12976template<typename Derived>
12977ExprResult
12978TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
12979 CXXUnresolvedConstructExpr *E) {
12980 TypeSourceInfo *T =
12981 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12982 if (!T)
12983 return ExprError();
12984
12985 bool ArgumentChanged = false;
12986 SmallVector<Expr*, 8> Args;
12987 Args.reserve(E->getNumArgs());
12988 {
12989 EnterExpressionEvaluationContext Context(
12990 getSema(), EnterExpressionEvaluationContext::InitList,
12991 E->isListInitialization());
12992 if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
12993 &ArgumentChanged))
12994 return ExprError();
12995 }
12996
12997 if (!getDerived().AlwaysRebuild() &&
12998 T == E->getTypeSourceInfo() &&
12999 !ArgumentChanged)
13000 return E;
13001
13002 // FIXME: we're faking the locations of the commas
13003 return getDerived().RebuildCXXUnresolvedConstructExpr(
13004 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13005}
13006
13007template<typename Derived>
13008ExprResult
13009TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13010 CXXDependentScopeMemberExpr *E) {
13011 // Transform the base of the expression.
13012 ExprResult Base((Expr*) nullptr);
13013 Expr *OldBase;
13014 QualType BaseType;
13015 QualType ObjectType;
13016 if (!E->isImplicitAccess()) {
13017 OldBase = E->getBase();
13018 Base = getDerived().TransformExpr(OldBase);
13019 if (Base.isInvalid())
13020 return ExprError();
13021
13022 // Start the member reference and compute the object's type.
13023 ParsedType ObjectTy;
13024 bool MayBePseudoDestructor = false;
13025 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13026 E->getOperatorLoc(),
13027 E->isArrow()? tok::arrow : tok::period,
13028 ObjectTy,
13029 MayBePseudoDestructor);
13030 if (Base.isInvalid())
13031 return ExprError();
13032
13033 ObjectType = ObjectTy.get();
13034 BaseType = ((Expr*) Base.get())->getType();
13035 } else {
13036 OldBase = nullptr;
13037 BaseType = getDerived().TransformType(E->getBaseType());
13038 ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13039 }
13040
13041 // Transform the first part of the nested-name-specifier that qualifies
13042 // the member name.
13043 NamedDecl *FirstQualifierInScope
13044 = getDerived().TransformFirstQualifierInScope(
13045 E->getFirstQualifierFoundInScope(),
13046 E->getQualifierLoc().getBeginLoc());
13047
13048 NestedNameSpecifierLoc QualifierLoc;
13049 if (E->getQualifier()) {
13050 QualifierLoc
13051 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13052 ObjectType,
13053 FirstQualifierInScope);
13054 if (!QualifierLoc)
13055 return ExprError();
13056 }
13057
13058 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13059
13060 // TODO: If this is a conversion-function-id, verify that the
13061 // destination type name (if present) resolves the same way after
13062 // instantiation as it did in the local scope.
13063
13064 DeclarationNameInfo NameInfo
13065 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13066 if (!NameInfo.getName())
13067 return ExprError();
13068
13069 if (!E->hasExplicitTemplateArgs()) {
13070 // This is a reference to a member without an explicitly-specified
13071 // template argument list. Optimize for this common case.
13072 if (!getDerived().AlwaysRebuild() &&
13073 Base.get() == OldBase &&
13074 BaseType == E->getBaseType() &&
13075 QualifierLoc == E->getQualifierLoc() &&
13076 NameInfo.getName() == E->getMember() &&
13077 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13078 return E;
13079
13080 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13081 BaseType,
13082 E->isArrow(),
13083 E->getOperatorLoc(),
13084 QualifierLoc,
13085 TemplateKWLoc,
13086 FirstQualifierInScope,
13087 NameInfo,
13088 /*TemplateArgs*/nullptr);
13089 }
13090
13091 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13092 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13093 E->getNumTemplateArgs(),
13094 TransArgs))
13095 return ExprError();
13096
13097 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13098 BaseType,
13099 E->isArrow(),
13100 E->getOperatorLoc(),
13101 QualifierLoc,
13102 TemplateKWLoc,
13103 FirstQualifierInScope,
13104 NameInfo,
13105 &TransArgs);
13106}
13107
13108template<typename Derived>
13109ExprResult
13110TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
13111 // Transform the base of the expression.
13112 ExprResult Base((Expr*) nullptr);
13113 QualType BaseType;
13114 if (!Old->isImplicitAccess()) {
13115 Base = getDerived().TransformExpr(Old->getBase());
13116 if (Base.isInvalid())
13117 return ExprError();
13118 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
13119 Old->isArrow());
13120 if (Base.isInvalid())
13121 return ExprError();
13122 BaseType = Base.get()->getType();
13123 } else {
13124 BaseType = getDerived().TransformType(Old->getBaseType());
13125 }
13126
13127 NestedNameSpecifierLoc QualifierLoc;
13128 if (Old->getQualifierLoc()) {
13129 QualifierLoc
13130 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13131 if (!QualifierLoc)
13132 return ExprError();
13133 }
13134
13135 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13136
13137 LookupResult R(SemaRef, Old->getMemberNameInfo(),
13138 Sema::LookupOrdinaryName);
13139
13140 // Transform the declaration set.
13141 if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
13142 return ExprError();
13143
13144 // Determine the naming class.
13145 if (Old->getNamingClass()) {
13146 CXXRecordDecl *NamingClass
13147 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
13148 Old->getMemberLoc(),
13149 Old->getNamingClass()));
13150 if (!NamingClass)
13151 return ExprError();
13152
13153 R.setNamingClass(NamingClass);
13154 }
13155
13156 TemplateArgumentListInfo TransArgs;
13157 if (Old->hasExplicitTemplateArgs()) {
13158 TransArgs.setLAngleLoc(Old->getLAngleLoc());
13159 TransArgs.setRAngleLoc(Old->getRAngleLoc());
13160 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
13161 Old->getNumTemplateArgs(),
13162 TransArgs))
13163 return ExprError();
13164 }
13165
13166 // FIXME: to do this check properly, we will need to preserve the
13167 // first-qualifier-in-scope here, just in case we had a dependent
13168 // base (and therefore couldn't do the check) and a
13169 // nested-name-qualifier (and therefore could do the lookup).
13170 NamedDecl *FirstQualifierInScope = nullptr;
13171
13172 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
13173 BaseType,
13174 Old->getOperatorLoc(),
13175 Old->isArrow(),
13176 QualifierLoc,
13177 TemplateKWLoc,
13178 FirstQualifierInScope,
13179 R,
13180 (Old->hasExplicitTemplateArgs()
13181 ? &TransArgs : nullptr));
13182}
13183
13184template<typename Derived>
13185ExprResult
13186TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13187 EnterExpressionEvaluationContext Unevaluated(
13188 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13189 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13190 if (SubExpr.isInvalid())
13191 return ExprError();
13192
13193 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13194 return E;
13195
13196 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13197}
13198
13199template<typename Derived>
13200ExprResult
13201TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13202 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13203 if (Pattern.isInvalid())
13204 return ExprError();
13205
13206 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13207 return E;
13208
13209 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13210 E->getNumExpansions());
13211}
13212
13213template<typename Derived>
13214ExprResult
13215TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13216 // If E is not value-dependent, then nothing will change when we transform it.
13217 // Note: This is an instantiation-centric view.
13218 if (!E->isValueDependent())
13219 return E;
13220
13221 EnterExpressionEvaluationContext Unevaluated(
13222 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13223
13224 ArrayRef<TemplateArgument> PackArgs;
13225 TemplateArgument ArgStorage;
13226
13227 // Find the argument list to transform.
13228 if (E->isPartiallySubstituted()) {
13229 PackArgs = E->getPartialArguments();
13230 } else if (E->isValueDependent()) {
13231 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13232 bool ShouldExpand = false;
13233 bool RetainExpansion = false;
13234 Optional<unsigned> NumExpansions;
13235 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13236 Unexpanded,
13237 ShouldExpand, RetainExpansion,
13238 NumExpansions))
13239 return ExprError();
13240
13241 // If we need to expand the pack, build a template argument from it and
13242 // expand that.
13243 if (ShouldExpand) {
13244 auto *Pack = E->getPack();
13245 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13246 ArgStorage = getSema().Context.getPackExpansionType(
13247 getSema().Context.getTypeDeclType(TTPD), None);
13248 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13249 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
13250 } else {
13251 auto *VD = cast<ValueDecl>(Pack);
13252 ExprResult DRE = getSema().BuildDeclRefExpr(
13253 VD, VD->getType().getNonLValueExprType(getSema().Context),
13254 VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
13255 E->getPackLoc());
13256 if (DRE.isInvalid())
13257 return ExprError();
13258 ArgStorage = new (getSema().Context) PackExpansionExpr(
13259 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
13260 }
13261 PackArgs = ArgStorage;
13262 }
13263 }
13264
13265 // If we're not expanding the pack, just transform the decl.
13266 if (!PackArgs.size()) {
13267 auto *Pack = cast_or_null<NamedDecl>(
13268 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13269 if (!Pack)
13270 return ExprError();
13271 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
13272 E->getPackLoc(),
13273 E->getRParenLoc(), None, None);
13274 }
13275
13276 // Try to compute the result without performing a partial substitution.
13277 Optional<unsigned> Result = 0;
13278 for (const TemplateArgument &Arg : PackArgs) {
13279 if (!Arg.isPackExpansion()) {
13280 Result = *Result + 1;
13281 continue;
13282 }
13283
13284 TemplateArgumentLoc ArgLoc;
13285 InventTemplateArgumentLoc(Arg, ArgLoc);
13286
13287 // Find the pattern of the pack expansion.
13288 SourceLocation Ellipsis;
13289 Optional<unsigned> OrigNumExpansions;
13290 TemplateArgumentLoc Pattern =
13291 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13292 OrigNumExpansions);
13293
13294 // Substitute under the pack expansion. Do not expand the pack (yet).
13295 TemplateArgumentLoc OutPattern;
13296 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13297 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13298 /*Uneval*/ true))
13299 return true;
13300
13301 // See if we can determine the number of arguments from the result.
13302 Optional<unsigned> NumExpansions =
13303 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13304 if (!NumExpansions) {
13305 // No: we must be in an alias template expansion, and we're going to need
13306 // to actually expand the packs.
13307 Result = None;
13308 break;
13309 }
13310
13311 Result = *Result + *NumExpansions;
13312 }
13313
13314 // Common case: we could determine the number of expansions without
13315 // substituting.
13316 if (Result)
13317 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13318 E->getPackLoc(),
13319 E->getRParenLoc(), *Result, None);
13320
13321 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13322 E->getPackLoc());
13323 {
13324 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13325 typedef TemplateArgumentLocInventIterator<
13326 Derived, const TemplateArgument*> PackLocIterator;
13327 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13328 PackLocIterator(*this, PackArgs.end()),
13329 TransformedPackArgs, /*Uneval*/true))
13330 return ExprError();
13331 }
13332
13333 // Check whether we managed to fully-expand the pack.
13334 // FIXME: Is it possible for us to do so and not hit the early exit path?
13335 SmallVector<TemplateArgument, 8> Args;
13336 bool PartialSubstitution = false;
13337 for (auto &Loc : TransformedPackArgs.arguments()) {
13338 Args.push_back(Loc.getArgument());
13339 if (Loc.getArgument().isPackExpansion())
13340 PartialSubstitution = true;
13341 }
13342
13343 if (PartialSubstitution)
13344 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13345 E->getPackLoc(),
13346 E->getRParenLoc(), None, Args);
13347
13348 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13349 E->getPackLoc(), E->getRParenLoc(),
13350 Args.size(), None);
13351}
13352
13353template<typename Derived>
13354ExprResult
13355TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13356 SubstNonTypeTemplateParmPackExpr *E) {
13357 // Default behavior is to do nothing with this transformation.
13358 return E;
13359}
13360
13361template<typename Derived>
13362ExprResult
13363TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13364 SubstNonTypeTemplateParmExpr *E) {
13365 // Default behavior is to do nothing with this transformation.
13366 return E;
13367}
13368
13369template<typename Derived>
13370ExprResult
13371TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13372 // Default behavior is to do nothing with this transformation.
13373 return E;
13374}
13375
13376template<typename Derived>
13377ExprResult
13378TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13379 MaterializeTemporaryExpr *E) {
13380 return getDerived().TransformExpr(E->getSubExpr());
13381}
13382
13383template<typename Derived>
13384ExprResult
13385TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13386 UnresolvedLookupExpr *Callee = nullptr;
13387 if (Expr *OldCallee = E->getCallee()) {
13388 ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13389 if (CalleeResult.isInvalid())
13390 return ExprError();
13391 Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13392 }
13393
13394 Expr *Pattern = E->getPattern();
13395
13396 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13397 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13398 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 13398, __PRETTY_FUNCTION__))
;
13399
13400 // Determine whether the set of unexpanded parameter packs can and should
13401 // be expanded.
13402 bool Expand = true;
13403 bool RetainExpansion = false;
13404 Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13405 NumExpansions = OrigNumExpansions;
13406 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13407 Pattern->getSourceRange(),
13408 Unexpanded,
13409 Expand, RetainExpansion,
13410 NumExpansions))
13411 return true;
13412
13413 if (!Expand) {
13414 // Do not expand any packs here, just transform and rebuild a fold
13415 // expression.
13416 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13417
13418 ExprResult LHS =
13419 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13420 if (LHS.isInvalid())
13421 return true;
13422
13423 ExprResult RHS =
13424 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13425 if (RHS.isInvalid())
13426 return true;
13427
13428 if (!getDerived().AlwaysRebuild() &&
13429 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13430 return E;
13431
13432 return getDerived().RebuildCXXFoldExpr(
13433 Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
13434 E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
13435 }
13436
13437 // Formally a fold expression expands to nested parenthesized expressions.
13438 // Enforce this limit to avoid creating trees so deep we can't safely traverse
13439 // them.
13440 if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
13441 SemaRef.Diag(E->getEllipsisLoc(),
13442 clang::diag::err_fold_expression_limit_exceeded)
13443 << *NumExpansions << SemaRef.getLangOpts().BracketDepth
13444 << E->getSourceRange();
13445 SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
13446 return ExprError();
13447 }
13448
13449 // The transform has determined that we should perform an elementwise
13450 // expansion of the pattern. Do so.
13451 ExprResult Result = getDerived().TransformExpr(E->getInit());
13452 if (Result.isInvalid())
13453 return true;
13454 bool LeftFold = E->isLeftFold();
13455
13456 // If we're retaining an expansion for a right fold, it is the innermost
13457 // component and takes the init (if any).
13458 if (!LeftFold && RetainExpansion) {
13459 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13460
13461 ExprResult Out = getDerived().TransformExpr(Pattern);
13462 if (Out.isInvalid())
13463 return true;
13464
13465 Result = getDerived().RebuildCXXFoldExpr(
13466 Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
13467 E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
13468 if (Result.isInvalid())
13469 return true;
13470 }
13471
13472 for (unsigned I = 0; I != *NumExpansions; ++I) {
13473 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
13474 getSema(), LeftFold ? I : *NumExpansions - I - 1);
13475 ExprResult Out = getDerived().TransformExpr(Pattern);
13476 if (Out.isInvalid())
13477 return true;
13478
13479 if (Out.get()->containsUnexpandedParameterPack()) {
13480 // We still have a pack; retain a pack expansion for this slice.
13481 Result = getDerived().RebuildCXXFoldExpr(
13482 Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
13483 E->getOperator(), E->getEllipsisLoc(),
13484 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
13485 OrigNumExpansions);
13486 } else if (Result.isUsable()) {
13487 // We've got down to a single element; build a binary operator.
13488 Expr *LHS = LeftFold ? Result.get() : Out.get();
13489 Expr *RHS = LeftFold ? Out.get() : Result.get();
13490 if (Callee)
13491 Result = getDerived().RebuildCXXOperatorCallExpr(
13492 BinaryOperator::getOverloadedOperator(E->getOperator()),
13493 E->getEllipsisLoc(), Callee, LHS, RHS);
13494 else
13495 Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
13496 E->getOperator(), LHS, RHS);
13497 } else
13498 Result = Out;
13499
13500 if (Result.isInvalid())
13501 return true;
13502 }
13503
13504 // If we're retaining an expansion for a left fold, it is the outermost
13505 // component and takes the complete expansion so far as its init (if any).
13506 if (LeftFold && RetainExpansion) {
13507 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13508
13509 ExprResult Out = getDerived().TransformExpr(Pattern);
13510 if (Out.isInvalid())
13511 return true;
13512
13513 Result = getDerived().RebuildCXXFoldExpr(
13514 Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
13515 E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
13516 if (Result.isInvalid())
13517 return true;
13518 }
13519
13520 // If we had no init and an empty pack, and we're not retaining an expansion,
13521 // then produce a fallback value or error.
13522 if (Result.isUnset())
13523 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
13524 E->getOperator());
13525
13526 return Result;
13527}
13528
13529template<typename Derived>
13530ExprResult
13531TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
13532 CXXStdInitializerListExpr *E) {
13533 return getDerived().TransformExpr(E->getSubExpr());
13534}
13535
13536template<typename Derived>
13537ExprResult
13538TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
13539 return SemaRef.MaybeBindToTemporary(E);
13540}
13541
13542template<typename Derived>
13543ExprResult
13544TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
13545 return E;
13546}
13547
13548template<typename Derived>
13549ExprResult
13550TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
13551 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
13552 if (SubExpr.isInvalid())
13553 return ExprError();
13554
13555 if (!getDerived().AlwaysRebuild() &&
13556 SubExpr.get() == E->getSubExpr())
13557 return E;
13558
13559 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
13560}
13561
13562template<typename Derived>
13563ExprResult
13564TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
13565 // Transform each of the elements.
13566 SmallVector<Expr *, 8> Elements;
13567 bool ArgChanged = false;
13568 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
13569 /*IsCall=*/false, Elements, &ArgChanged))
13570 return ExprError();
13571
13572 if (!getDerived().AlwaysRebuild() && !ArgChanged)
13573 return SemaRef.MaybeBindToTemporary(E);
13574
13575 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
13576 Elements.data(),
13577 Elements.size());
13578}
13579
13580template<typename Derived>
13581ExprResult
13582TreeTransform<Derived>::TransformObjCDictionaryLiteral(
13583 ObjCDictionaryLiteral *E) {
13584 // Transform each of the elements.
13585 SmallVector<ObjCDictionaryElement, 8> Elements;
13586 bool ArgChanged = false;
13587 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
13588 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
13589
13590 if (OrigElement.isPackExpansion()) {
13591 // This key/value element is a pack expansion.
13592 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13593 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
13594 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
13595 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")((!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? static_cast<void> (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 13595, __PRETTY_FUNCTION__))
;
13596
13597 // Determine whether the set of unexpanded parameter packs can
13598 // and should be expanded.
13599 bool Expand = true;
13600 bool RetainExpansion = false;
13601 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
13602 Optional<unsigned> NumExpansions = OrigNumExpansions;
13603 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
13604 OrigElement.Value->getEndLoc());
13605 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
13606 PatternRange, Unexpanded, Expand,
13607 RetainExpansion, NumExpansions))
13608 return ExprError();
13609
13610 if (!Expand) {
13611 // The transform has determined that we should perform a simple
13612 // transformation on the pack expansion, producing another pack
13613 // expansion.
13614 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13615 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13616 if (Key.isInvalid())
13617 return ExprError();
13618
13619 if (Key.get() != OrigElement.Key)
13620 ArgChanged = true;
13621
13622 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13623 if (Value.isInvalid())
13624 return ExprError();
13625
13626 if (Value.get() != OrigElement.Value)
13627 ArgChanged = true;
13628
13629 ObjCDictionaryElement Expansion = {
13630 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
13631 };
13632 Elements.push_back(Expansion);
13633 continue;
13634 }
13635
13636 // Record right away that the argument was changed. This needs
13637 // to happen even if the array expands to nothing.
13638 ArgChanged = true;
13639
13640 // The transform has determined that we should perform an elementwise
13641 // expansion of the pattern. Do so.
13642 for (unsigned I = 0; I != *NumExpansions; ++I) {
13643 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13644 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13645 if (Key.isInvalid())
13646 return ExprError();
13647
13648 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13649 if (Value.isInvalid())
13650 return ExprError();
13651
13652 ObjCDictionaryElement Element = {
13653 Key.get(), Value.get(), SourceLocation(), NumExpansions
13654 };
13655
13656 // If any unexpanded parameter packs remain, we still have a
13657 // pack expansion.
13658 // FIXME: Can this really happen?
13659 if (Key.get()->containsUnexpandedParameterPack() ||
13660 Value.get()->containsUnexpandedParameterPack())
13661 Element.EllipsisLoc = OrigElement.EllipsisLoc;
13662
13663 Elements.push_back(Element);
13664 }
13665
13666 // FIXME: Retain a pack expansion if RetainExpansion is true.
13667
13668 // We've finished with this pack expansion.
13669 continue;
13670 }
13671
13672 // Transform and check key.
13673 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13674 if (Key.isInvalid())
13675 return ExprError();
13676
13677 if (Key.get() != OrigElement.Key)
13678 ArgChanged = true;
13679
13680 // Transform and check value.
13681 ExprResult Value
13682 = getDerived().TransformExpr(OrigElement.Value);
13683 if (Value.isInvalid())
13684 return ExprError();
13685
13686 if (Value.get() != OrigElement.Value)
13687 ArgChanged = true;
13688
13689 ObjCDictionaryElement Element = {
13690 Key.get(), Value.get(), SourceLocation(), None
13691 };
13692 Elements.push_back(Element);
13693 }
13694
13695 if (!getDerived().AlwaysRebuild() && !ArgChanged)
13696 return SemaRef.MaybeBindToTemporary(E);
13697
13698 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
13699 Elements);
13700}
13701
13702template<typename Derived>
13703ExprResult
13704TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
13705 TypeSourceInfo *EncodedTypeInfo
13706 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
13707 if (!EncodedTypeInfo)
13708 return ExprError();
13709
13710 if (!getDerived().AlwaysRebuild() &&
13711 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
13712 return E;
13713
13714 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
13715 EncodedTypeInfo,
13716 E->getRParenLoc());
13717}
13718
13719template<typename Derived>
13720ExprResult TreeTransform<Derived>::
13721TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
13722 // This is a kind of implicit conversion, and it needs to get dropped
13723 // and recomputed for the same general reasons that ImplicitCastExprs
13724 // do, as well a more specific one: this expression is only valid when
13725 // it appears *immediately* as an argument expression.
13726 return getDerived().TransformExpr(E->getSubExpr());
13727}
13728
13729template<typename Derived>
13730ExprResult TreeTransform<Derived>::
13731TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
13732 TypeSourceInfo *TSInfo
13733 = getDerived().TransformType(E->getTypeInfoAsWritten());
13734 if (!TSInfo)
13735 return ExprError();
13736
13737 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
13738 if (Result.isInvalid())
13739 return ExprError();
13740
13741 if (!getDerived().AlwaysRebuild() &&
13742 TSInfo == E->getTypeInfoAsWritten() &&
13743 Result.get() == E->getSubExpr())
13744 return E;
13745
13746 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
13747 E->getBridgeKeywordLoc(), TSInfo,
13748 Result.get());
13749}
13750
13751template <typename Derived>
13752ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
13753 ObjCAvailabilityCheckExpr *E) {
13754 return E;
13755}
13756
13757template<typename Derived>
13758ExprResult
13759TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
13760 // Transform arguments.
13761 bool ArgChanged = false;
13762 SmallVector<Expr*, 8> Args;
13763 Args.reserve(E->getNumArgs());
13764 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
13765 &ArgChanged))
13766 return ExprError();
13767
13768 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
13769 // Class message: transform the receiver type.
13770 TypeSourceInfo *ReceiverTypeInfo
13771 = getDerived().TransformType(E->getClassReceiverTypeInfo());
13772 if (!ReceiverTypeInfo)
13773 return ExprError();
13774
13775 // If nothing changed, just retain the existing message send.
13776 if (!getDerived().AlwaysRebuild() &&
13777 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
13778 return SemaRef.MaybeBindToTemporary(E);
13779
13780 // Build a new class message send.
13781 SmallVector<SourceLocation, 16> SelLocs;
13782 E->getSelectorLocs(SelLocs);
13783 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
13784 E->getSelector(),
13785 SelLocs,
13786 E->getMethodDecl(),
13787 E->getLeftLoc(),
13788 Args,
13789 E->getRightLoc());
13790 }
13791 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
13792 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13793 if (!E->getMethodDecl())
13794 return ExprError();
13795
13796 // Build a new class message send to 'super'.
13797 SmallVector<SourceLocation, 16> SelLocs;
13798 E->getSelectorLocs(SelLocs);
13799 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
13800 E->getSelector(),
13801 SelLocs,
13802 E->getReceiverType(),
13803 E->getMethodDecl(),
13804 E->getLeftLoc(),
13805 Args,
13806 E->getRightLoc());
13807 }
13808
13809 // Instance message: transform the receiver
13810 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&((E->getReceiverKind() == ObjCMessageExpr::Instance &&
"Only class and instance messages may be instantiated") ? static_cast
<void> (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 13811, __PRETTY_FUNCTION__))
13811 "Only class and instance messages may be instantiated")((E->getReceiverKind() == ObjCMessageExpr::Instance &&
"Only class and instance messages may be instantiated") ? static_cast
<void> (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 13811, __PRETTY_FUNCTION__))
;
13812 ExprResult Receiver
13813 = getDerived().TransformExpr(E->getInstanceReceiver());
13814 if (Receiver.isInvalid())
13815 return ExprError();
13816
13817 // If nothing changed, just retain the existing message send.
13818 if (!getDerived().AlwaysRebuild() &&
13819 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
13820 return SemaRef.MaybeBindToTemporary(E);
13821
13822 // Build a new instance message send.
13823 SmallVector<SourceLocation, 16> SelLocs;
13824 E->getSelectorLocs(SelLocs);
13825 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
13826 E->getSelector(),
13827 SelLocs,
13828 E->getMethodDecl(),
13829 E->getLeftLoc(),
13830 Args,
13831 E->getRightLoc());
13832}
13833
13834template<typename Derived>
13835ExprResult
13836TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
13837 return E;
13838}
13839
13840template<typename Derived>
13841ExprResult
13842TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
13843 return E;
13844}
13845
13846template<typename Derived>
13847ExprResult
13848TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
13849 // Transform the base expression.
13850 ExprResult Base = getDerived().TransformExpr(E->getBase());
13851 if (Base.isInvalid())
13852 return ExprError();
13853
13854 // We don't need to transform the ivar; it will never change.
13855
13856 // If nothing changed, just retain the existing expression.
13857 if (!getDerived().AlwaysRebuild() &&
13858 Base.get() == E->getBase())
13859 return E;
13860
13861 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
13862 E->getLocation(),
13863 E->isArrow(), E->isFreeIvar());
13864}
13865
13866template<typename Derived>
13867ExprResult
13868TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
13869 // 'super' and types never change. Property never changes. Just
13870 // retain the existing expression.
13871 if (!E->isObjectReceiver())
13872 return E;
13873
13874 // Transform the base expression.
13875 ExprResult Base = getDerived().TransformExpr(E->getBase());
13876 if (Base.isInvalid())
13877 return ExprError();
13878
13879 // We don't need to transform the property; it will never change.
13880
13881 // If nothing changed, just retain the existing expression.
13882 if (!getDerived().AlwaysRebuild() &&
13883 Base.get() == E->getBase())
13884 return E;
13885
13886 if (E->isExplicitProperty())
13887 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
13888 E->getExplicitProperty(),
13889 E->getLocation());
13890
13891 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
13892 SemaRef.Context.PseudoObjectTy,
13893 E->getImplicitPropertyGetter(),
13894 E->getImplicitPropertySetter(),
13895 E->getLocation());
13896}
13897
13898template<typename Derived>
13899ExprResult
13900TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
13901 // Transform the base expression.
13902 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
13903 if (Base.isInvalid())
13904 return ExprError();
13905
13906 // Transform the key expression.
13907 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
13908 if (Key.isInvalid())
13909 return ExprError();
13910
13911 // If nothing changed, just retain the existing expression.
13912 if (!getDerived().AlwaysRebuild() &&
13913 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
13914 return E;
13915
13916 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
13917 Base.get(), Key.get(),
13918 E->getAtIndexMethodDecl(),
13919 E->setAtIndexMethodDecl());
13920}
13921
13922template<typename Derived>
13923ExprResult
13924TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
13925 // Transform the base expression.
13926 ExprResult Base = getDerived().TransformExpr(E->getBase());
13927 if (Base.isInvalid())
13928 return ExprError();
13929
13930 // If nothing changed, just retain the existing expression.
13931 if (!getDerived().AlwaysRebuild() &&
13932 Base.get() == E->getBase())
13933 return E;
13934
13935 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
13936 E->getOpLoc(),
13937 E->isArrow());
13938}
13939
13940template<typename Derived>
13941ExprResult
13942TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
13943 bool ArgumentChanged = false;
13944 SmallVector<Expr*, 8> SubExprs;
13945 SubExprs.reserve(E->getNumSubExprs());
13946 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
13947 SubExprs, &ArgumentChanged))
13948 return ExprError();
13949
13950 if (!getDerived().AlwaysRebuild() &&
13951 !ArgumentChanged)
13952 return E;
13953
13954 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
13955 SubExprs,
13956 E->getRParenLoc());
13957}
13958
13959template<typename Derived>
13960ExprResult
13961TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
13962 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
13963 if (SrcExpr.isInvalid())
13964 return ExprError();
13965
13966 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
13967 if (!Type)
13968 return ExprError();
13969
13970 if (!getDerived().AlwaysRebuild() &&
13971 Type == E->getTypeSourceInfo() &&
13972 SrcExpr.get() == E->getSrcExpr())
13973 return E;
13974
13975 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
13976 SrcExpr.get(), Type,
13977 E->getRParenLoc());
13978}
13979
13980template<typename Derived>
13981ExprResult
13982TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
13983 BlockDecl *oldBlock = E->getBlockDecl();
13984
13985 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
13986 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
13987
13988 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
13989 blockScope->TheDecl->setBlockMissingReturnType(
13990 oldBlock->blockMissingReturnType());
13991
13992 SmallVector<ParmVarDecl*, 4> params;
13993 SmallVector<QualType, 4> paramTypes;
13994
13995 const FunctionProtoType *exprFunctionType = E->getFunctionType();
13996
13997 // Parameter substitution.
13998 Sema::ExtParameterInfoBuilder extParamInfos;
13999 if (getDerived().TransformFunctionTypeParams(
14000 E->getCaretLocation(), oldBlock->parameters(), nullptr,
14001 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14002 extParamInfos)) {
14003 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14004 return ExprError();
14005 }
14006
14007 QualType exprResultType =
14008 getDerived().TransformType(exprFunctionType->getReturnType());
14009
14010 auto epi = exprFunctionType->getExtProtoInfo();
14011 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14012
14013 QualType functionType =
14014 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14015 blockScope->FunctionType = functionType;
14016
14017 // Set the parameters on the block decl.
14018 if (!params.empty())
14019 blockScope->TheDecl->setParams(params);
14020
14021 if (!oldBlock->blockMissingReturnType()) {
14022 blockScope->HasImplicitReturnType = false;
14023 blockScope->ReturnType = exprResultType;
14024 }
14025
14026 // Transform the body
14027 StmtResult body = getDerived().TransformStmt(E->getBody());
14028 if (body.isInvalid()) {
14029 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14030 return ExprError();
14031 }
14032
14033#ifndef NDEBUG
14034 // In builds with assertions, make sure that we captured everything we
14035 // captured before.
14036 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14037 for (const auto &I : oldBlock->captures()) {
14038 VarDecl *oldCapture = I.getVariable();
14039
14040 // Ignore parameter packs.
14041 if (oldCapture->isParameterPack())
14042 continue;
14043
14044 VarDecl *newCapture =
14045 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14046 oldCapture));
14047 assert(blockScope->CaptureMap.count(newCapture))((blockScope->CaptureMap.count(newCapture)) ? static_cast<
void> (0) : __assert_fail ("blockScope->CaptureMap.count(newCapture)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14047, __PRETTY_FUNCTION__))
;
14048 }
14049 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured())((oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured
()) ? static_cast<void> (0) : __assert_fail ("oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14049, __PRETTY_FUNCTION__))
;
14050 }
14051#endif
14052
14053 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14054 /*Scope=*/nullptr);
14055}
14056
14057template<typename Derived>
14058ExprResult
14059TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14060 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14061 if (SrcExpr.isInvalid())
14062 return ExprError();
14063
14064 QualType Type = getDerived().TransformType(E->getType());
14065
14066 return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14067 E->getRParenLoc());
14068}
14069
14070template<typename Derived>
14071ExprResult
14072TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14073 bool ArgumentChanged = false;
14074 SmallVector<Expr*, 8> SubExprs;
14075 SubExprs.reserve(E->getNumSubExprs());
14076 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14077 SubExprs, &ArgumentChanged))
14078 return ExprError();
14079
14080 if (!getDerived().AlwaysRebuild() &&
14081 !ArgumentChanged)
14082 return E;
14083
14084 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14085 E->getOp(), E->getRParenLoc());
14086}
14087
14088//===----------------------------------------------------------------------===//
14089// Type reconstruction
14090//===----------------------------------------------------------------------===//
14091
14092template<typename Derived>
14093QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14094 SourceLocation Star) {
14095 return SemaRef.BuildPointerType(PointeeType, Star,
14096 getDerived().getBaseEntity());
14097}
14098
14099template<typename Derived>
14100QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14101 SourceLocation Star) {
14102 return SemaRef.BuildBlockPointerType(PointeeType, Star,
14103 getDerived().getBaseEntity());
14104}
14105
14106template<typename Derived>
14107QualType
14108TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14109 bool WrittenAsLValue,
14110 SourceLocation Sigil) {
14111 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14112 Sigil, getDerived().getBaseEntity());
14113}
14114
14115template<typename Derived>
14116QualType
14117TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14118 QualType ClassType,
14119 SourceLocation Sigil) {
14120 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14121 getDerived().getBaseEntity());
14122}
14123
14124template<typename Derived>
14125QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14126 const ObjCTypeParamDecl *Decl,
14127 SourceLocation ProtocolLAngleLoc,
14128 ArrayRef<ObjCProtocolDecl *> Protocols,
14129 ArrayRef<SourceLocation> ProtocolLocs,
14130 SourceLocation ProtocolRAngleLoc) {
14131 return SemaRef.BuildObjCTypeParamType(Decl,
14132 ProtocolLAngleLoc, Protocols,
14133 ProtocolLocs, ProtocolRAngleLoc,
14134 /*FailOnError=*/true);
14135}
14136
14137template<typename Derived>
14138QualType TreeTransform<Derived>::RebuildObjCObjectType(
14139 QualType BaseType,
14140 SourceLocation Loc,
14141 SourceLocation TypeArgsLAngleLoc,
14142 ArrayRef<TypeSourceInfo *> TypeArgs,
14143 SourceLocation TypeArgsRAngleLoc,
14144 SourceLocation ProtocolLAngleLoc,
14145 ArrayRef<ObjCProtocolDecl *> Protocols,
14146 ArrayRef<SourceLocation> ProtocolLocs,
14147 SourceLocation ProtocolRAngleLoc) {
14148 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
14149 TypeArgs, TypeArgsRAngleLoc,
14150 ProtocolLAngleLoc, Protocols, ProtocolLocs,
14151 ProtocolRAngleLoc,
14152 /*FailOnError=*/true);
14153}
14154
14155template<typename Derived>
14156QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14157 QualType PointeeType,
14158 SourceLocation Star) {
14159 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14160}
14161
14162template<typename Derived>
14163QualType
14164TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14165 ArrayType::ArraySizeModifier SizeMod,
14166 const llvm::APInt *Size,
14167 Expr *SizeExpr,
14168 unsigned IndexTypeQuals,
14169 SourceRange BracketsRange) {
14170 if (SizeExpr || !Size)
14171 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14172 IndexTypeQuals, BracketsRange,
14173 getDerived().getBaseEntity());
14174
14175 QualType Types[] = {
14176 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14177 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14178 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14179 };
14180 const unsigned NumTypes = llvm::array_lengthof(Types);
14181 QualType SizeType;
14182 for (unsigned I = 0; I != NumTypes; ++I)
14183 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
14184 SizeType = Types[I];
14185 break;
14186 }
14187
14188 // Note that we can return a VariableArrayType here in the case where
14189 // the element type was a dependent VariableArrayType.
14190 IntegerLiteral *ArraySize
14191 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14192 /*FIXME*/BracketsRange.getBegin());
14193 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14194 IndexTypeQuals, BracketsRange,
14195 getDerived().getBaseEntity());
14196}
14197
14198template<typename Derived>
14199QualType
14200TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14201 ArrayType::ArraySizeModifier SizeMod,
14202 const llvm::APInt &Size,
14203 Expr *SizeExpr,
14204 unsigned IndexTypeQuals,
14205 SourceRange BracketsRange) {
14206 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14207 IndexTypeQuals, BracketsRange);
14208}
14209
14210template<typename Derived>
14211QualType
14212TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14213 ArrayType::ArraySizeModifier SizeMod,
14214 unsigned IndexTypeQuals,
14215 SourceRange BracketsRange) {
14216 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14217 IndexTypeQuals, BracketsRange);
14218}
14219
14220template<typename Derived>
14221QualType
14222TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14223 ArrayType::ArraySizeModifier SizeMod,
14224 Expr *SizeExpr,
14225 unsigned IndexTypeQuals,
14226 SourceRange BracketsRange) {
14227 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14228 SizeExpr,
14229 IndexTypeQuals, BracketsRange);
14230}
14231
14232template<typename Derived>
14233QualType
14234TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14235 ArrayType::ArraySizeModifier SizeMod,
14236 Expr *SizeExpr,
14237 unsigned IndexTypeQuals,
14238 SourceRange BracketsRange) {
14239 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14240 SizeExpr,
14241 IndexTypeQuals, BracketsRange);
14242}
14243
14244template <typename Derived>
14245QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14246 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14247 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14248 AttributeLoc);
14249}
14250
14251template <typename Derived>
14252QualType
14253TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14254 unsigned NumElements,
14255 VectorType::VectorKind VecKind) {
14256 // FIXME: semantic checking!
14257 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14258}
14259
14260template <typename Derived>
14261QualType TreeTransform<Derived>::RebuildDependentVectorType(
14262 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14263 VectorType::VectorKind VecKind) {
14264 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14265}
14266
14267template<typename Derived>
14268QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14269 unsigned NumElements,
14270 SourceLocation AttributeLoc) {
14271 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14272 NumElements, true);
14273 IntegerLiteral *VectorSize
14274 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14275 AttributeLoc);
14276 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14277}
14278
14279template<typename Derived>
14280QualType
14281TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14282 Expr *SizeExpr,
14283 SourceLocation AttributeLoc) {
14284 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14285}
14286
14287template <typename Derived>
14288QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14289 QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14290 return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14291 NumColumns);
14292}
14293
14294template <typename Derived>
14295QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14296 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14297 SourceLocation AttributeLoc) {
14298 return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14299 AttributeLoc);
14300}
14301
14302template<typename Derived>
14303QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14304 QualType T,
14305 MutableArrayRef<QualType> ParamTypes,
14306 const FunctionProtoType::ExtProtoInfo &EPI) {
14307 return SemaRef.BuildFunctionType(T, ParamTypes,
14308 getDerived().getBaseLocation(),
14309 getDerived().getBaseEntity(),
14310 EPI);
14311}
14312
14313template<typename Derived>
14314QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14315 return SemaRef.Context.getFunctionNoProtoType(T);
14316}
14317
14318template<typename Derived>
14319QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14320 Decl *D) {
14321 assert(D && "no decl found")((D && "no decl found") ? static_cast<void> (0)
: __assert_fail ("D && \"no decl found\"", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14321, __PRETTY_FUNCTION__))
;
14322 if (D->isInvalidDecl()) return QualType();
14323
14324 // FIXME: Doesn't account for ObjCInterfaceDecl!
14325 TypeDecl *Ty;
14326 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14327 // A valid resolved using typename pack expansion decl can have multiple
14328 // UsingDecls, but they must each have exactly one type, and it must be
14329 // the same type in every case. But we must have at least one expansion!
14330 if (UPD->expansions().empty()) {
14331 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14332 << UPD->isCXXClassMember() << UPD;
14333 return QualType();
14334 }
14335
14336 // We might still have some unresolved types. Try to pick a resolved type
14337 // if we can. The final instantiation will check that the remaining
14338 // unresolved types instantiate to the type we pick.
14339 QualType FallbackT;
14340 QualType T;
14341 for (auto *E : UPD->expansions()) {
14342 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14343 if (ThisT.isNull())
14344 continue;
14345 else if (ThisT->getAs<UnresolvedUsingType>())
14346 FallbackT = ThisT;
14347 else if (T.isNull())
14348 T = ThisT;
14349 else
14350 assert(getSema().Context.hasSameType(ThisT, T) &&((getSema().Context.hasSameType(ThisT, T) && "mismatched resolved types in using pack expansion"
) ? static_cast<void> (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14351, __PRETTY_FUNCTION__))
14351 "mismatched resolved types in using pack expansion")((getSema().Context.hasSameType(ThisT, T) && "mismatched resolved types in using pack expansion"
) ? static_cast<void> (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14351, __PRETTY_FUNCTION__))
;
14352 }
14353 return T.isNull() ? FallbackT : T;
14354 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14355 assert(Using->hasTypename() &&((Using->hasTypename() && "UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? static_cast<void> (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14356, __PRETTY_FUNCTION__))
14356 "UnresolvedUsingTypenameDecl transformed to non-typename using")((Using->hasTypename() && "UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? static_cast<void> (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14356, __PRETTY_FUNCTION__))
;
14357
14358 // A valid resolved using typename decl points to exactly one type decl.
14359 assert(++Using->shadow_begin() == Using->shadow_end())((++Using->shadow_begin() == Using->shadow_end()) ? static_cast
<void> (0) : __assert_fail ("++Using->shadow_begin() == Using->shadow_end()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14359, __PRETTY_FUNCTION__))
;
14360 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
14361 } else {
14362 assert(isa<UnresolvedUsingTypenameDecl>(D) &&((isa<UnresolvedUsingTypenameDecl>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14363, __PRETTY_FUNCTION__))
14363 "UnresolvedUsingTypenameDecl transformed to non-using decl")((isa<UnresolvedUsingTypenameDecl>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/TreeTransform.h"
, 14363, __PRETTY_FUNCTION__))
;
14364 Ty = cast<UnresolvedUsingTypenameDecl>(D);
14365 }
14366
14367 return SemaRef.Context.getTypeDeclType(Ty);
14368}
14369
14370template<typename Derived>
14371QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
14372 SourceLocation Loc) {
14373 return SemaRef.BuildTypeofExprType(E, Loc);
14374}
14375
14376template<typename Derived>
14377QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
14378 return SemaRef.Context.getTypeOfType(Underlying);
14379}
14380
14381template<typename Derived>
14382QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
14383 SourceLocation Loc) {
14384 return SemaRef.BuildDecltypeType(E, Loc);
14385}
14386
14387template<typename Derived>
14388QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14389 UnaryTransformType::UTTKind UKind,
14390 SourceLocation Loc) {
14391 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14392}
14393
14394template<typename Derived>
14395QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14396 TemplateName Template,
14397 SourceLocation TemplateNameLoc,
14398 TemplateArgumentListInfo &TemplateArgs) {
14399 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14400}
14401
14402template<typename Derived>
14403QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14404 SourceLocation KWLoc) {
14405 return SemaRef.BuildAtomicType(ValueType, KWLoc);
14406}
14407
14408template<typename Derived>
14409QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14410 SourceLocation KWLoc,
14411 bool isReadPipe) {
14412 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14413 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14414}
14415
14416template <typename Derived>
14417QualType TreeTransform<Derived>::RebuildExtIntType(bool IsUnsigned,
14418 unsigned NumBits,
14419 SourceLocation Loc) {
14420 llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14421 NumBits, true);
14422 IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14423 SemaRef.Context.IntTy, Loc);
14424 return SemaRef.BuildExtIntType(IsUnsigned, Bits, Loc);
14425}
14426
14427template <typename Derived>
14428QualType TreeTransform<Derived>::RebuildDependentExtIntType(
14429 bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14430 return SemaRef.BuildExtIntType(IsUnsigned, NumBitsExpr, Loc);
14431}
14432
14433template<typename Derived>
14434TemplateName
14435TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14436 bool TemplateKW,
14437 TemplateDecl *Template) {
14438 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14439 Template);
14440}
14441
14442template<typename Derived>
14443TemplateName
14444TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14445 SourceLocation TemplateKWLoc,
14446 const IdentifierInfo &Name,
14447 SourceLocation NameLoc,
14448 QualType ObjectType,
14449 NamedDecl *FirstQualifierInScope,
14450 bool AllowInjectedClassName) {
14451 UnqualifiedId TemplateName;
14452 TemplateName.setIdentifier(&Name, NameLoc);
14453 Sema::TemplateTy Template;
14454 getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
14455 TemplateName, ParsedType::make(ObjectType),
14456 /*EnteringContext=*/false, Template,
14457 AllowInjectedClassName);
14458 return Template.get();
14459}
14460
14461template<typename Derived>
14462TemplateName
14463TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14464 SourceLocation TemplateKWLoc,
14465 OverloadedOperatorKind Operator,
14466 SourceLocation NameLoc,
14467 QualType ObjectType,
14468 bool AllowInjectedClassName) {
14469 UnqualifiedId Name;
14470 // FIXME: Bogus location information.
14471 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
14472 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
14473 Sema::TemplateTy Template;
14474 getSema().ActOnTemplateName(
14475 /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
14476 /*EnteringContext=*/false, Template, AllowInjectedClassName);
14477 return Template.get();
14478}
14479
14480template<typename Derived>
14481ExprResult
14482TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
14483 SourceLocation OpLoc,
14484 Expr *OrigCallee,
14485 Expr *First,
14486 Expr *Second) {
14487 Expr *Callee = OrigCallee->IgnoreParenCasts();
14488 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
14489
14490 if (First->getObjectKind() == OK_ObjCProperty) {
14491 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14492 if (BinaryOperator::isAssignmentOp(Opc))
14493 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
14494 First, Second);
14495 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
14496 if (Result.isInvalid())
14497 return ExprError();
14498 First = Result.get();
14499 }
14500
14501 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
14502 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
14503 if (Result.isInvalid())
14504 return ExprError();
14505 Second = Result.get();
14506 }
14507
14508 // Determine whether this should be a builtin operation.
14509 if (Op == OO_Subscript) {
14510 if (!First->getType()->isOverloadableType() &&
14511 !Second->getType()->isOverloadableType())
14512 return getSema().CreateBuiltinArraySubscriptExpr(
14513 First, Callee->getBeginLoc(), Second, OpLoc);
14514 } else if (Op == OO_Arrow) {
14515 // -> is never a builtin operation.
14516 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
14517 } else if (Second == nullptr || isPostIncDec) {
14518 if (!First->getType()->isOverloadableType() ||
14519 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
14520 // The argument is not of overloadable type, or this is an expression
14521 // of the form &Class::member, so try to create a built-in unary
14522 // operation.
14523 UnaryOperatorKind Opc
14524 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14525
14526 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
14527 }
14528 } else {
14529 if (!First->getType()->isOverloadableType() &&
14530 !Second->getType()->isOverloadableType()) {
14531 // Neither of the arguments is an overloadable type, so try to
14532 // create a built-in binary operation.
14533 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14534 ExprResult Result
14535 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
14536 if (Result.isInvalid())
14537 return ExprError();
14538
14539 return Result;
14540 }
14541 }
14542
14543 // Compute the transformed set of functions (and function templates) to be
14544 // used during overload resolution.
14545 UnresolvedSet<16> Functions;
14546 bool RequiresADL;
14547
14548 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
14549 Functions.append(ULE->decls_begin(), ULE->decls_end());
14550 // If the overload could not be resolved in the template definition
14551 // (because we had a dependent argument), ADL is performed as part of
14552 // template instantiation.
14553 RequiresADL = ULE->requiresADL();
14554 } else {
14555 // If we've resolved this to a particular non-member function, just call
14556 // that function. If we resolved it to a member function,
14557 // CreateOverloaded* will find that function for us.
14558 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
14559 if (!isa<CXXMethodDecl>(ND))
14560 Functions.addDecl(ND);
14561 RequiresADL = false;
14562 }
14563
14564 // Add any functions found via argument-dependent lookup.
14565 Expr *Args[2] = { First, Second };
14566 unsigned NumArgs = 1 + (Second != nullptr);
14567
14568 // Create the overloaded operator invocation for unary operators.
14569 if (NumArgs == 1 || isPostIncDec) {
14570 UnaryOperatorKind Opc
14571 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14572 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
14573 RequiresADL);
14574 }
14575
14576 if (Op == OO_Subscript) {
14577 SourceLocation LBrace;
14578 SourceLocation RBrace;
14579
14580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
14581 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
14582 LBrace = NameLoc.getCXXOperatorNameBeginLoc();
14583 RBrace = NameLoc.getCXXOperatorNameEndLoc();
14584 } else {
14585 LBrace = Callee->getBeginLoc();
14586 RBrace = OpLoc;
14587 }
14588
14589 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
14590 First, Second);
14591 }
14592
14593 // Create the overloaded operator invocation for binary operators.
14594 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14595 ExprResult Result = SemaRef.CreateOverloadedBinOp(
14596 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
14597 if (Result.isInvalid())
14598 return ExprError();
14599
14600 return Result;
14601}
14602
14603template<typename Derived>
14604ExprResult
14605TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
14606 SourceLocation OperatorLoc,
14607 bool isArrow,
14608 CXXScopeSpec &SS,
14609 TypeSourceInfo *ScopeType,
14610 SourceLocation CCLoc,
14611 SourceLocation TildeLoc,
14612 PseudoDestructorTypeStorage Destroyed) {
14613 QualType BaseType = Base->getType();
14614 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
14615 (!isArrow && !BaseType->getAs<RecordType>()) ||
14616 (isArrow && BaseType->getAs<PointerType>() &&
14617 !BaseType->castAs<PointerType>()->getPointeeType()
14618 ->template getAs<RecordType>())){
14619 // This pseudo-destructor expression is still a pseudo-destructor.
14620 return SemaRef.BuildPseudoDestructorExpr(
14621 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
14622 CCLoc, TildeLoc, Destroyed);
14623 }
14624
14625 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
14626 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
14627 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
14628 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
14629 NameInfo.setNamedTypeInfo(DestroyedType);
14630
14631 // The scope type is now known to be a valid nested name specifier
14632 // component. Tack it on to the end of the nested name specifier.
14633 if (ScopeType) {
14634 if (!ScopeType->getType()->getAs<TagType>()) {
14635 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
14636 diag::err_expected_class_or_namespace)
14637 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
14638 return ExprError();
14639 }
14640 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
14641 CCLoc);
14642 }
14643
14644 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
14645 return getSema().BuildMemberReferenceExpr(Base, BaseType,
14646 OperatorLoc, isArrow,
14647 SS, TemplateKWLoc,
14648 /*FIXME: FirstQualifier*/ nullptr,
14649 NameInfo,
14650 /*TemplateArgs*/ nullptr,
14651 /*S*/nullptr);
14652}
14653
14654template<typename Derived>
14655StmtResult
14656TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
14657 SourceLocation Loc = S->getBeginLoc();
14658 CapturedDecl *CD = S->getCapturedDecl();
14659 unsigned NumParams = CD->getNumParams();
14660 unsigned ContextParamPos = CD->getContextParamPosition();
14661 SmallVector<Sema::CapturedParamNameType, 4> Params;
14662 for (unsigned I = 0; I < NumParams; ++I) {
14663 if (I != ContextParamPos) {
14664 Params.push_back(
14665 std::make_pair(
14666 CD->getParam(I)->getName(),
14667 getDerived().TransformType(CD->getParam(I)->getType())));
14668 } else {
14669 Params.push_back(std::make_pair(StringRef(), QualType()));
14670 }
14671 }
14672 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
14673 S->getCapturedRegionKind(), Params);
14674 StmtResult Body;
14675 {
14676 Sema::CompoundScopeRAII CompoundScope(getSema());
14677 Body = getDerived().TransformStmt(S->getCapturedStmt());
14678 }
14679
14680 if (Body.isInvalid()) {
14681 getSema().ActOnCapturedRegionError();
14682 return StmtError();
14683 }
14684
14685 return getSema().ActOnCapturedRegionEnd(Body.get());
14686}
14687
14688} // end namespace clang
14689
14690#endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H